Add hash table formatters

This commit is contained in:
Nikita Lisitsa 2026-06-07 18:48:10 +03:00
parent 03af0a7099
commit 68aedbf2fa

View file

@ -6,6 +6,7 @@
#include <memory>
#include <initializer_list>
#include <format>
namespace psemek::util
{
@ -716,3 +717,59 @@ namespace psemek::util
};
}
namespace std
{
template <typename T, typename Hash, typename Equal, typename Char>
struct formatter<::psemek::util::hash_set<T, Hash, Equal>, Char>
: std::formatter<T, Char>
{
using std::formatter<T, Char>::parse;
template <typename FormatContext>
auto format(::psemek::util::hash_set<T, Hash, Equal> const & s, FormatContext & ctx) const
{
bool first = true;
ctx.advance_to(std::format_to(ctx.out(), "{{"));
for (auto const & v : s)
{
if (!first)
ctx.advance_to(std::format_to(ctx.out(), ", "));
first = false;
ctx.advance_to(formatter<T, Char>::format(v, ctx));
}
return std::format_to(ctx.out(), "}}");
}
};
template <typename Key, typename Value, typename KeyHash, typename KeyEqual, typename Char>
struct formatter<::psemek::util::hash_map<Key, Value, KeyHash, KeyEqual>, Char>
: std::pair<formatter<Key, Char>, formatter<Value, Char>>
{
template <typename ParseContext>
constexpr auto parse(ParseContext & ctx)
{
return std::pair<formatter<Key, Char>, formatter<Value, Char>>::first.parse(ctx);
}
template <typename FormatContext>
auto format(::psemek::util::hash_map<Key, Value, KeyHash, KeyEqual> const & m, FormatContext & ctx) const
{
bool first = true;
ctx.advance_to(std::format_to(ctx.out(), "{{"));
for (auto const & p : m)
{
if (!first)
ctx.advance_to(std::format_to(ctx.out(), ", "));
first = false;
ctx.advance_to(std::pair<formatter<Key, Char>, formatter<Value, Char>>::first.format(p.first, ctx));
ctx.advance_to(std::format_to(ctx.out(), ": "));
ctx.advance_to(std::pair<formatter<Key, Char>, formatter<Value, Char>>::second.format(p.second, ctx));
}
return std::format_to(ctx.out(), "}}");
}
};
}