userver: userver/formats/json/value_builder.hpp Source File
Loading...
Searching...
No Matches
value_builder.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/formats/json/value_builder.hpp
4/// @brief @copybrief formats::json::ValueBuilder
5
6#include <chrono>
7#include <string_view>
8#include <type_traits>
9
10#include <userver/formats/common/meta.hpp>
11#include <userver/formats/common/transfer_tag.hpp>
12#include <userver/formats/json/impl/mutable_value_wrapper.hpp>
13#include <userver/formats/json/value.hpp>
14#include <userver/utils/strong_typedef.hpp>
15
16USERVER_NAMESPACE_BEGIN
17
18namespace formats::json {
19
20// clang-format off
21
22/// @ingroup userver_universal userver_containers userver_formats
23///
24/// @brief Builder for JSON.
25///
26/// Class provides methods for building JSON. For read only access to the
27/// existing JSON values use formats::json::Value.
28///
29/// ## Example usage:
30///
31/// @snippet formats/json/value_builder_test.cpp Sample formats::json::ValueBuilder usage
32///
33/// ## Customization example:
34///
35/// @snippet formats/json/value_builder_test.cpp Sample Customization formats::json::ValueBuilder usage
36///
37/// @see @ref scripts/docs/en/userver/formats.md
38
39// clang-format on
40
41class ValueBuilder final {
42public:
43 struct IterTraits {
44 using ValueType = formats::json::ValueBuilder;
45 using Reference = formats::json::ValueBuilder&;
46 using Pointer = formats::json::ValueBuilder*;
47 using ContainerType = impl::MutableValueWrapper;
48 };
49
50 using iterator = Iterator<IterTraits>;
51
52 /// Constructs a ValueBuilder that holds kNull
53 ValueBuilder() = default;
54
55 /// Constructs a valueBuilder that holds default value for provided `type`.
56 ValueBuilder(formats::common::Type type);
57
58 /// @brief Transfers the `ValueBuilder` object
59 /// @see formats::common::TransferTag for the transfer semantics
60 ValueBuilder(common::TransferTag, ValueBuilder&&) noexcept;
61
62 ValueBuilder(const ValueBuilder& other);
63 // NOLINTNEXTLINE(performance-noexcept-move-constructor)
64 ValueBuilder(ValueBuilder&& other);
65 ValueBuilder& operator=(const ValueBuilder& other);
66 // NOLINTNEXTLINE(performance-noexcept-move-constructor)
67 ValueBuilder& operator=(ValueBuilder&& other);
68
69 ValueBuilder(const formats::json::Value& other);
70 ValueBuilder(formats::json::Value&& other);
71
72 /// @name Concrete type constructors
73 /// @{
74 ValueBuilder(std::nullptr_t)
75 : ValueBuilder()
76 {}
77 ValueBuilder(bool t);
78 ValueBuilder(const char* str);
79 ValueBuilder(char* str);
80 ValueBuilder(const std::string& str);
81 ValueBuilder(std::string_view str);
82 ValueBuilder(int t);
83 ValueBuilder(unsigned int t);
84 ValueBuilder(uint64_t t);
85 ValueBuilder(int64_t t);
86 ValueBuilder(float t);
87 ValueBuilder(double t);
88 /// @}
89
90 /// Universal constructor using Serialize
91 template <typename T>
92 ValueBuilder(const T& t)
93 : ValueBuilder(DoSerialize(t))
94 {}
95
96 /// @brief Access member by key for modification.
97 /// @throw `TypeMismatchException` if not object or null value.
98 ValueBuilder operator[](std::string key);
99 /// @brief Access array member by index for modification.
100 /// @throw `TypeMismatchException` if not an array value.
101 /// @throw `OutOfBoundsException` if index is greater than size.
102 ValueBuilder operator[](std::size_t index);
103 /// @brief Access member by key for modification.
104 /// @throw `TypeMismatchException` if not object or null value.
105 template <typename Tag, utils::StrongTypedefOps Ops>
106 requires(utils::IsStrongTypedefLoggable(Ops))
107 ValueBuilder operator[](utils::StrongTypedef<Tag, std::string, Ops> key) {
108 return (*this)[std::move(key.GetUnderlying())];
109 }
110
111 /// @brief Emplaces new member w/o a check whether the key already exists.
112 /// @warning May create invalid JSON with duplicate key.
113 /// @throw `TypeMismatchException` if not object or null value.
114 void EmplaceNocheck(std::string_view key, ValueBuilder value);
115
116 /// @brief Remove key from object. If key is missing nothing happens.
117 /// @throw `TypeMismatchException` if value is not an object.
118 void Remove(std::string_view key);
119
120 iterator begin();
121 iterator end();
122
123 /// @brief Returns whether the array or object is empty.
124 /// @throw `TypeMismatchException` if not an array or an object.
125 bool IsEmpty() const;
126
127 /// @brief Returns true if *this holds a Null (Type::kNull).
128 bool IsNull() const noexcept;
129
130 /// @brief Returns true if *this is convertible to bool.
131 bool IsBool() const noexcept;
132
133 /// @brief Returns true if *this is convertible to int.
134 bool IsInt() const noexcept;
135
136 /// @brief Returns true if *this is convertible to int64_t.
137 bool IsInt64() const noexcept;
138
139 /// @brief Returns true if *this is convertible to uint64_t.
140 bool IsUInt64() const noexcept;
141
142 /// @brief Returns true if *this is convertible to double.
143 bool IsDouble() const noexcept;
144
145 /// @brief Returns true if *this is convertible to std::string.
146 bool IsString() const noexcept;
147
148 /// @brief Returns true if *this is an array (Type::kArray).
149 bool IsArray() const noexcept;
150
151 /// @brief Returns true if *this holds a map (Type::kObject).
152 bool IsObject() const noexcept;
153
154 /// @brief Returns array size or object members count.
155 /// @throw `TypeMismatchException` if not an array or an object.
156 std::size_t GetSize() const;
157
158 /// @brief Returns true if value holds a `key`.
159 /// @throw `TypeMismatchException` if `*this` is not a map or null.
160 bool HasMember(std::string_view key) const;
161
162 /// @brief Returns full path to this value.
163 std::string GetPath() const;
164
165 /// @brief Resize the array value or convert null value
166 /// into an array of requested size.
167 /// @throw `TypeMismatchException` if not an array or null.
168 void Resize(std::size_t size);
169
170 /// @brief Add element into the last position of array.
171 /// @throw `TypeMismatchException` if not an array or null.
172 void PushBack(ValueBuilder&& bld);
173
174 /// @brief Take out the resulting `Value` object.
175 /// After calling this method the object is in unspecified
176 /// (but valid - possibly null) state.
177 /// @throw `json::Exception` if called not from the root builder.
178 formats::json::Value ExtractValue();
179
180private:
181 class EmplaceEnabler {};
182
183public:
184 /// @cond
185 ValueBuilder(EmplaceEnabler, impl::MutableValueWrapper) noexcept;
186 /// @endcond
187
188private:
189 enum class CheckMemberExists { kYes, kNo };
190
191 explicit ValueBuilder(impl::MutableValueWrapper) noexcept;
192
193 static void Copy(impl::Value& to, const ValueBuilder& from);
194 static void Move(impl::Value& to, ValueBuilder&& from);
195
196 impl::Value& AddMember(std::string_view key, CheckMemberExists);
197
198 template <typename T>
199 static Value DoSerialize(const T& t);
200
201 impl::MutableValueWrapper value_;
202
203 friend class Iterator<IterTraits, common::IteratorDirection::kForward>;
204 friend class Iterator<IterTraits, common::IteratorDirection::kReverse>;
205};
206
207template <typename T>
208Value ValueBuilder::DoSerialize(const T& t) {
209 static_assert(
210 formats::common::impl::HasSerialize<Value, T>,
211 "There is no `Serialize(const T&, formats::serialize::To<json::Value>)` "
212 "in namespace of `T` or `formats::serialize`. "
213 ""
214 "Probably you forgot to include the <userver/formats/serialize/common_containers.hpp> header "
215 "or one of the <formats/json/serialize_*.hpp> headers or you have not provided a `Serialize` function overload."
216 );
217
218 return Serialize(t, formats::serialize::To<Value>());
219}
220
221template <typename T>
222requires(std::is_integral<T>::value && sizeof(T) <= sizeof(int64_t))
223Value Serialize(T value, formats::serialize::To<Value>) {
224 using Type = std::conditional_t<std::is_signed<T>::value, int64_t, uint64_t>;
225 return json::ValueBuilder(static_cast<Type>(value)).ExtractValue();
226}
227
228json::Value Serialize(std::chrono::system_clock::time_point tp, formats::serialize::To<Value>);
229
230/// Optimized maps of StrongTypedefs serialization for JSON
231template <typename T>
232requires(meta::kIsUniqueMap<T> && utils::IsStrongTypedefLoggable(T::key_type::kOps))
233Value Serialize(const T& value, formats::serialize::To<Value>) {
234 json::ValueBuilder builder(formats::common::Type::kObject);
235 for (const auto& [key, value] : value) {
236 builder.EmplaceNocheck(key.GetUnderlying(), value);
237 }
238 return builder.ExtractValue();
239}
240
241/// Optimized maps serialization for JSON
242template <typename T>
243requires meta::kIsUniqueMap<T> && std::is_convertible_v<typename T::key_type, std::string>
244Value Serialize(const T& value, formats::serialize::To<Value>) {
245 json::ValueBuilder builder(formats::common::Type::kObject);
246 for (const auto& [key, value] : value) {
247 builder.EmplaceNocheck(key, value);
248 }
249 return builder.ExtractValue();
250}
251
252} // namespace formats::json
253
254USERVER_NAMESPACE_END