userver: userver/formats/json/serialize.hpp Source File
Loading...
Searching...
No Matches
serialize.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/formats/json/serialize.hpp
4/// @brief Parsers and serializers to/from string and stream
5
6#include <iosfwd>
7#include <string_view>
8
9#include <fmt/format.h>
10
11#include <userver/formats/json/value.hpp>
12#include <userver/utils/fast_pimpl.hpp>
13#include <userver/utils/fmt_compat.hpp>
14
15USERVER_NAMESPACE_BEGIN
16
17namespace logging {
18
19class LogHelper;
20
21} // namespace logging
22
23namespace formats::json {
24
25constexpr inline std::size_t kDepthParseLimit = 128;
26
27/// Parse JSON from string
28formats::json::Value FromString(std::string_view doc);
29
30/// Parse JSON from stream
31formats::json::Value FromStream(std::istream& is);
32
33/// Serialize JSON to stream
34void Serialize(const formats::json::Value& doc, std::ostream& os);
35
36/// Serialize JSON to string
37std::string ToString(const formats::json::Value& doc);
38
39/// Stably serialize JSON to string. In result there is no whitespace, keys
40/// are sorted and character escaping is stabilized
41std::string ToStableString(const formats::json::Value& doc);
42
43/// @overload
44std::string ToStableString(formats::json::Value&& doc);
45
46/// @see formats::json::ToPrettyString
47struct PrettyFormat final {
48 char indent_char{' '};
50};
51
52/// Serialize JSON to a string, using `\n` and indents for objects and arrays.
53std::string ToPrettyString(const formats::json::Value& doc,
54 PrettyFormat format = {});
55
56/// Log JSON
57logging::LogHelper& operator<<(logging::LogHelper&,
58 const formats::json::Value&);
59
60/// Blocking operations that should not be used on main task processor after
61/// startup
62namespace blocking {
63/// Read JSON from file
64formats::json::Value FromFile(const std::string& path);
65} // namespace blocking
66
67namespace impl {
68
69class StringBuffer final {
70 public:
71 explicit StringBuffer(const formats::json::Value& value);
72 ~StringBuffer();
73
74 std::string_view GetStringView() const;
75
76 private:
77 struct Impl;
78 static constexpr std::size_t kSize = 48;
79 static constexpr std::size_t kAlignment = 8;
80 utils::FastPimpl<Impl, kSize, kAlignment> pimpl_;
81};
82
83} // namespace impl
84
85} // namespace formats::json
86
87USERVER_NAMESPACE_END
88
89template <>
90struct fmt::formatter<USERVER_NAMESPACE::formats::json::Value>
91 : fmt::formatter<std::string_view> {
92 constexpr static auto parse(format_parse_context& ctx)
93 -> decltype(ctx.begin()) {
94 return ctx.begin();
95 }
96
97 template <typename FormatContext>
98 auto format(const USERVER_NAMESPACE::formats::json::Value& value,
99 FormatContext& ctx) USERVER_FMT_CONST->decltype(ctx.out()) {
100 const USERVER_NAMESPACE::formats::json::impl::StringBuffer buffer(value);
101 return formatter<string_view>::format(buffer.GetStringView(), ctx);
102 }
103};