metadata 0.2.0
Modern C++23 header-only metadata container (JSON-like)
Loading...
Searching...
No Matches
format.hpp
1#pragma once
2
3#include <md/object.hpp>
4#include <md/ostream.hpp>
5#include <md/value.hpp>
6
7#include <format>
8#include <sstream>
9#include <string>
10
11namespace md::detail {
12
13template <class T>
14struct CompactJsonFormatter {
15 template <class ParseCtx>
16 constexpr auto parse(ParseCtx& ctx) -> typename ParseCtx::iterator {
17 auto it = ctx.begin();
18 auto end = ctx.end();
19 if (it != end && *it != '}') {
20 throw std::format_error(
21 "metadata formatter: only the default (empty) format spec is supported");
22 }
23 return it;
24 }
25
26 template <class FormatCtx>
27 auto format(const T& v, FormatCtx& ctx) const -> typename FormatCtx::iterator {
28 std::ostringstream os;
29 detail::write_json(os, v);
30 const std::string s = os.str();
31 return std::ranges::copy(s, ctx.out()).out;
32 }
33};
34
35} // namespace md::detail
36
38template <>
39struct std::formatter<md::Value, char> : md::detail::CompactJsonFormatter<md::Value> {};
40
42template <>
43struct std::formatter<md::Object, char> : md::detail::CompactJsonFormatter<md::Object> {};
44
46template <>
47struct std::formatter<md::Array, char> : md::detail::CompactJsonFormatter<md::Array> {};