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{' '};
49 std::size_t indent_char_count{2};
50};
51
52/// Serialize JSON to a string, using `\n` and indents for objects and arrays.
53std::string ToPrettyString(const formats::json::Value& doc, PrettyFormat format = {});
54
55/// Log JSON
56logging::LogHelper& operator<<(logging::LogHelper&, const formats::json::Value&);
57
58/// @brief Blocking operations that should not be used on main task processor after startup
59namespace blocking {
60/// Read JSON from file
61formats::json::Value FromFile(const std::string& path);
62} // namespace blocking
63
64namespace impl {
65
66class StringBuffer final {
67public:
68 explicit StringBuffer(const formats::json::Value& value);
69 ~StringBuffer();
70
71 std::string_view GetStringView() const;
72
73private:
74 struct Impl;
75 static constexpr std::size_t kSize = 48;
76 static constexpr std::size_t kAlignment = 8;
77 utils::FastPimpl<Impl, kSize, kAlignment> pimpl_;
78};
79
80} // namespace impl
81
82} // namespace formats::json
83
84USERVER_NAMESPACE_END
85
86template <>
87struct fmt::formatter<USERVER_NAMESPACE::formats::json::Value> : fmt::formatter<std::string_view> {
88 constexpr static auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { return ctx.begin(); }
89
90 template <typename FormatContext>
91 auto format(const USERVER_NAMESPACE::formats::json::Value& value, FormatContext& ctx)
92 USERVER_FMT_CONST -> decltype(ctx.out()) {
93 const USERVER_NAMESPACE::formats::json::impl::StringBuffer buffer(value);
94 return fmt::format_to(ctx.out(), "{}", buffer.GetStringView());
95 }
96};