11 #include <nlohmann/detail/macro_scope.hpp>
18 template<
typename CharType>
struct output_adapter_protocol
20 virtual void write_character(CharType c) = 0;
21 virtual void write_characters(
const CharType* s, std::size_t length) = 0;
22 virtual ~output_adapter_protocol() =
default;
26 template<
typename CharType>
30 template<
typename CharType>
31 class output_vector_adapter :
public output_adapter_protocol<CharType>
34 explicit output_vector_adapter(std::vector<CharType>& vec) noexcept
38 void write_character(CharType c)
override
43 JSON_HEDLEY_NON_NULL(2)
44 void write_characters(const CharType* s, std::
size_t length)
override
46 std::copy(s, s + length, std::back_inserter(v));
50 std::vector<CharType>& v;
54 template<
typename CharType>
55 class output_stream_adapter :
public output_adapter_protocol<CharType>
58 explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept
62 void write_character(CharType c)
override
67 JSON_HEDLEY_NON_NULL(2)
68 void write_characters(const CharType* s, std::
size_t length)
override
70 stream.write(s,
static_cast<std::streamsize
>(length));
74 std::basic_ostream<CharType>& stream;
78 template<
typename CharType,
typename StringType = std::basic_
string<CharType>>
79 class output_string_adapter :
public output_adapter_protocol<CharType>
82 explicit output_string_adapter(StringType& s) noexcept
86 void write_character(CharType c)
override
91 JSON_HEDLEY_NON_NULL(2)
92 void write_characters(const CharType* s, std::
size_t length)
override
94 str.append(s, length);
101 template<
typename CharType,
typename StringType = std::basic_
string<CharType>>
105 output_adapter(std::vector<CharType>& vec)
106 : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
108 output_adapter(std::basic_ostream<CharType>& s)
109 : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
111 output_adapter(StringType& s)
112 : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
114 operator output_adapter_t<CharType>()
120 output_adapter_t<CharType> oa =
nullptr;