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 <cstdint>
8#include <initializer_list>
9#include <ranges>
10#include <string>
11#include <string_view>
12#include <type_traits>
13#include <utility>
14#include <variant>
15
16#include <userver/compiler/impl/nodebug.hpp>
17#include <userver/formats/common/meta.hpp>
18#include <userver/formats/common/transfer_tag.hpp>
19#include <userver/formats/json/impl/mutable_value_wrapper.hpp>
20#include <userver/formats/json/value.hpp>
21#include <userver/utils/meta.hpp>
22#include <userver/utils/strong_typedef.hpp>
23
24USERVER_NAMESPACE_BEGIN
25
26namespace formats::json {
27
28namespace impl {
29
30template <typename T>
31concept IsNativeString =
32 std::is_convertible_v<const T&, std::string_view> &&
33 (std::is_same_v<T, std::string> || std::is_same_v<T, std::string_view> ||
34 (!std::is_class_v<T> && !std::is_union_v<T>) || !common::impl::HasSerialize<formats::json::Value, T>);
35
36template <typename T>
37concept IsNativeArithmetic =
38 meta::IsCharacter<T> || std::is_same_v<T, bool> || meta::IsInteger<T> ||
39 std::is_same_v<std::remove_cv_t<T>, float> || std::is_same_v<std::remove_cv_t<T>, double>;
40
41template <typename T>
42concept IsWrappedValue = meta::IsOptional<T> || meta::IsInstantiationOf<T, std::variant>;
43
44template <typename T>
45concept IsNormalizedArithmetic =
46 std::is_same_v<T, bool> || std::is_same_v<T, int> || std::is_same_v<T, unsigned int> ||
47 std::is_same_v<T, std::int64_t> || std::is_same_v<T, std::uint64_t> || std::is_same_v<T, float> ||
48 std::is_same_v<T, double>;
49
50} // namespace impl
51
52/// @ingroup userver_universal userver_containers userver_formats
53///
54/// @brief Builder for JSON.
55///
56/// Class provides methods for building JSON. For read only access to the
57/// existing JSON values use formats::json::Value.
58///
59/// ## Example usage:
60///
61/// @snippet universal/src/formats/json/value_builder_test.cpp Sample formats::json::ValueBuilder usage
62///
63/// ## Customization example:
64///
65/// @snippet universal/src/formats/json/value_builder_test.cpp Sample Customization formats::json::ValueBuilder usage
66///
67/// @see @ref scripts/docs/en/userver/formats.md
68class ValueBuilder final {
69public:
70 struct IterTraits {
71 using ValueType = formats::json::ValueBuilder;
72 using Reference = formats::json::ValueBuilder&;
73 using Pointer = formats::json::ValueBuilder*;
74 using ContainerType = impl::MutableValueWrapper;
75 };
76
77 using iterator = Iterator<IterTraits>;
78
79 /// Constructs a ValueBuilder that holds kNull
80 ValueBuilder() = default;
81
82 /// Constructs a valueBuilder that holds default value for provided `type`.
83 ValueBuilder(formats::common::Type type);
84
85 /// @brief Transfers the `ValueBuilder` object
86 /// @see formats::common::TransferTag for the transfer semantics
87 ValueBuilder(common::TransferTag, ValueBuilder&&) noexcept;
88
89 ValueBuilder(const ValueBuilder& other);
90 // NOLINTNEXTLINE(cppcoreguidelines-noexcept-move-operations, performance-noexcept-move-constructor)
91 ValueBuilder(ValueBuilder&& other);
92
93 ValueBuilder(const formats::json::Value& other);
94 ValueBuilder(formats::json::Value&& other);
95
96 /// @brief Constructs a number or boolean directly.
97 template <typename T>
98 requires(impl::IsNativeArithmetic<T> && !meta::IsCharacter<T>)
99 ValueBuilder(T value)
100 : value_(CreateArithmetic(NormalizeArithmetic(value)))
101 {}
102
103 /// @brief Constructs a number representing the character's code unit.
104 template <typename T>
105 requires(impl::IsNativeArithmetic<T> && meta::IsCharacter<T>)
106 [[deprecated(
107 "Characters will be converted into underlying integer type. Avoid this or wrap with static_cast<int>(...) "
108 "explicitly."
109 )]]
111 : value_(CreateArithmetic(NormalizeArithmetic(value)))
112 {}
113
114 /// @brief Constructs a string, copying its bytes into owned storage.
115 template <typename T>
116 requires impl::IsNativeString<T>
117 ValueBuilder(const T& value)
118 : value_(CreateString(std::string_view{value}))
119 {}
120 /// @}
121
122 /// Universal constructor using Serialize
123 template <typename T>
124 requires(!impl::IsNativeArithmetic<T> && !impl::IsNativeString<T>)
125 USERVER_IMPL_NODEBUG_INLINE_FUNC ValueBuilder(const T& t)
126 : value_(GetSerializedRoot(DoSerialize(t)))
127 {}
128
129 /// @name Native value constructors
130 /// @{
131 /// @brief Constructs a JSON null.
132 ValueBuilder(std::nullptr_t)
133 : ValueBuilder()
134 {}
135
136 /// @brief Access member by key for modification.
137 /// @throw `TypeMismatchException` if not object or null value.
138 ValueBuilder operator[](std::string key);
139 /// @brief Access array member by index for modification.
140 /// @throw `TypeMismatchException` if not an array value.
141 /// @throw `OutOfBoundsException` if index is greater than size.
142 ValueBuilder operator[](std::size_t index);
143 /// @brief Access member by key for modification.
144 /// @throw `TypeMismatchException` if not object or null value.
145 template <typename Tag, utils::StrongTypedefOps Ops>
146 requires(utils::IsStrongTypedefLoggable(Ops))
147 ValueBuilder operator[](utils::StrongTypedef<Tag, std::string, Ops> key) {
148 return (*this)[std::move(key.GetUnderlying())];
149 }
150
151 ValueBuilder& operator=(const ValueBuilder& other);
152 // NOLINTNEXTLINE(cppcoreguidelines-noexcept-move-operations, performance-noexcept-move-constructor)
153 ValueBuilder& operator=(ValueBuilder&& other);
154
155 /// @brief Assigns a numeric or boolean value directly, without creating a temporary builder.
156 template <typename T>
157 requires(impl::IsNativeArithmetic<T> && !meta::IsCharacter<std::remove_cv_t<T>>)
158 ValueBuilder& operator=(T value) {
159 AssignArithmetic(NormalizeArithmetic(value));
160 return *this;
161 }
162
163 /// @brief Assigns a number representing the character's code unit.
164 template <typename T>
165 requires(impl::IsNativeArithmetic<T> && meta::IsCharacter<std::remove_cv_t<T>>)
166 [[deprecated(
167 "Characters will be converted into underlying integer type. Avoid this or wrap with static_cast<int>(...) "
168 "explicitly."
169 )]]
170 ValueBuilder& operator=(T value) {
171 AssignArithmetic(NormalizeArithmetic(value));
172 return *this;
173 }
174
175 /// @brief Assigns a string, copying its bytes into owned storage.
176 /// The source remains unchanged and may be modified or destroyed afterwards.
177 template <typename T>
178 requires impl::IsNativeString<T>
179 ValueBuilder& operator=(const T& value) {
180 AssignString(std::string_view{value});
181 return *this;
182 }
183
184 /// @brief Assigns an existing JSON value without constructing a temporary builder.
185 /// Lvalues and const or shared rvalues are copied. Uniquely owned non-const rvalues are moved and become null.
186 /// Copied sources and their aliases remain unchanged.
187 /// @throw formats::json::MemberMissingException if the source value is missing.
188 template <typename T>
189 requires std::is_same_v<std::remove_cvref_t<T>, formats::json::Value>
190 ValueBuilder& operator=(T&& value) {
191 AssignValue(std::forward<T>(value));
192 return *this;
193 }
194
195 /// @brief Assigns JSON null directly, without creating a temporary builder.
196 ValueBuilder& operator=(std::nullptr_t) {
197 AssignNull();
198 return *this;
199 }
200
201 /// @brief Emplaces new member w/o a check whether the key already exists.
202 /// @warning May create invalid JSON with duplicate key.
203 /// @throw `TypeMismatchException` if not object or null value.
204 void EmplaceNocheck(std::string_view key, ValueBuilder value);
205
206 /// @brief Copies an existing JSON value directly, without constructing a temporary ValueBuilder.
207 /// @overload
208 void EmplaceNocheck(std::string_view key, const formats::json::Value& value);
209
210 /// @brief Moves a uniquely owned JSON value directly, copying shared values.
211 /// @overload
212 void EmplaceNocheck(std::string_view key, formats::json::Value&& value);
213
214 /// @overload
215 void EmplaceNocheck(std::string_view key, std::nullptr_t);
216
217 /// @overload
218 void EmplaceNocheck(std::string_view key, const std::string& value);
219
220 /// @overload
221 void EmplaceNocheck(std::string_view key, std::string_view value);
222
223 /// @overload
224 template <typename T>
225 requires std::is_convertible_v<const T&, std::string_view>
226 void EmplaceNocheck(std::string_view key, const T& value) {
227 if constexpr (impl::IsNativeString<T>) {
228 EmplaceNocheck(key, std::string_view{value});
229 } else {
230 EmplaceNocheck(key, ValueBuilder{value});
231 }
232 }
233
234 /// @brief Serializes and inserts a std::optional or std::variant without constructing a temporary builder.
235 /// Uses the same serialization customization as the universal constructor.
236 /// @overload
237 template <impl::IsWrappedValue T>
238 USERVER_IMPL_NODEBUG_INLINE_FUNC void EmplaceNocheck(std::string_view key, const T& value) {
239 EmplaceNocheck(key, DoSerialize(value));
240 }
241
242 /// @overload
243 template <typename T>
244 requires(impl::IsNativeArithmetic<T> && !meta::IsCharacter<std::remove_cv_t<T>>)
245 void EmplaceNocheck(std::string_view key, T value) {
246 EmplaceNocheckArithmetic(key, NormalizeArithmetic(value));
247 }
248
249 /// @brief Emplaces a number representing the character's code unit.
250 /// @overload
251 template <typename T>
252 requires(impl::IsNativeArithmetic<T> && meta::IsCharacter<std::remove_cv_t<T>>)
253 [[deprecated(
254 "Characters will be converted into underlying integer type. Avoid this or wrap with static_cast<int>(...) "
255 "explicitly."
256 )]]
257 void EmplaceNocheck(std::string_view key, T value) {
258 EmplaceNocheckArithmetic(key, NormalizeArithmetic(value));
259 }
260
261 /// @overload
262 template <typename T>
263 [[deprecated(
264 "Use natively passed argument instead of curly-braces wrapped. Such usage could affect the performance."
265 )]]
266 void EmplaceNocheck(std::string_view key, std::initializer_list<T> initializer) {
267 CheckSingleElementInitializerList(initializer.size());
268 EmplaceNocheck(key, *initializer.begin());
269 }
270
271 /// @brief Remove key from object. If key is missing nothing happens.
272 /// @throw `TypeMismatchException` if value is not an object.
273 void Remove(std::string_view key);
274
275 iterator begin();
276 iterator end();
277
278 /// @brief Returns whether the array or object is empty.
279 /// @throw `TypeMismatchException` if not an array or an object.
280 bool IsEmpty() const;
281
282 /// @brief Returns true if *this holds a Null (Type::kNull).
283 bool IsNull() const noexcept;
284
285 /// @brief Returns true if *this is convertible to bool.
286 bool IsBool() const noexcept;
287
288 /// @brief Returns true if *this is convertible to int.
289 bool IsInt() const noexcept;
290
291 /// @brief Returns true if *this is convertible to int64_t.
292 bool IsInt64() const noexcept;
293
294 /// @brief Returns true if *this is convertible to uint64_t.
295 bool IsUInt64() const noexcept;
296
297 /// @brief Returns true if *this is convertible to double.
298 bool IsDouble() const noexcept;
299
300 /// @brief Returns true if *this is convertible to std::string.
301 bool IsString() const noexcept;
302
303 /// @brief Returns true if *this is an array (Type::kArray).
304 bool IsArray() const noexcept;
305
306 /// @brief Returns true if *this holds a map (Type::kObject).
307 bool IsObject() const noexcept;
308
309 /// @brief Returns array size or object members count.
310 /// @throw `TypeMismatchException` if not an array or an object.
311 std::size_t GetSize() const;
312
313 /// @brief Returns storage capacity for array elements or object members.
314 /// @throw `TypeMismatchException` if not an array or an object.
315 std::size_t GetCapacity() const;
316
317 /// @brief Returns true if value holds a `key`.
318 /// @throw `TypeMismatchException` if `*this` is not a map or null.
319 bool HasMember(std::string_view key) const;
320
321 /// @brief Returns full path to this value.
322 std::string GetPath() const;
323
324 /// @brief Ensures storage capacity for array elements or object members is at least `capacity` without changing
325 /// size.
326 /// @throw `TypeMismatchException` if not an array or object.
327 void Reserve(std::size_t capacity);
328
329 /// @brief Resize the array value or convert null value
330 /// into an array of requested size.
331 /// @throw `TypeMismatchException` if not an array or null.
332 void Resize(std::size_t size);
333
334 /// @brief Appends a JSON `null` directly, without constructing a temporary `ValueBuilder`, converting this builder
335 /// from null to an array if necessary.
336 /// @throw `TypeMismatchException` if the builder contains neither an array nor null.
337 void PushBack(std::nullptr_t);
338
339 /// @brief Appends a string directly, without constructing a temporary `ValueBuilder`.
340 /// @throw `TypeMismatchException` if the builder contains neither an array nor null.
341 void PushBack(const std::string& value);
342
343 /// @overload
344 void PushBack(std::string_view value);
345
346 /// @brief Appends a string-like value directly, without constructing a temporary `ValueBuilder`.
347 /// @throw `TypeMismatchException` if the builder contains neither an array nor null.
348 template <typename T>
349 requires std::is_convertible_v<const T&, std::string_view>
350 void PushBack(const T& value) {
351 if constexpr (impl::IsNativeString<T>) {
352 PushBack(std::string_view{value});
353 } else {
354 PushBack(ValueBuilder{value});
355 }
356 }
357
358 /// @brief Serializes and appends a std::optional or std::variant without constructing a temporary builder.
359 /// Uses the same serialization customization as the universal constructor.
360 /// @throw formats::json::TypeMismatchException if the builder is neither an array nor null.
361 template <impl::IsWrappedValue T>
362 USERVER_IMPL_NODEBUG_INLINE_FUNC void PushBack(const T& value) {
363 PushBack(DoSerialize(value));
364 }
365
366 /// @brief Appends an arithmetic value directly, without constructing a temporary `ValueBuilder`.
367 /// @throw `TypeMismatchException` if the builder contains neither an array nor null.
368 template <typename T>
369 requires(std::is_arithmetic_v<T> && !meta::IsCharacter<std::remove_cv_t<T>>)
370 void PushBack(T value) {
371 if constexpr (std::is_same_v<T, long double>) {
372 PushBackArithmetic(static_cast<double>(value));
373 } else {
374 PushBackArithmetic(NormalizeArithmetic(value));
375 }
376 }
377
378 /// @brief Appends a number representing the character's code unit.
379 /// @throw `TypeMismatchException` if the builder contains neither an array nor null.
380 template <typename T>
381 requires(std::is_arithmetic_v<T> && meta::IsCharacter<std::remove_cv_t<T>>)
382 [[deprecated(
383 "Characters will be converted into underlying integer type. Avoid this or wrap with static_cast<int>(...) "
384 "explicitly."
385 )]]
386 void PushBack(T value) {
387 PushBackArithmetic(NormalizeArithmetic(value));
388 }
389
390 /// @brief Appends the single element of a braced initializer.
391 /// The element is forwarded to the matching `PushBack` overload, avoiding a temporary `ValueBuilder` when a direct
392 /// overload is available.
393 /// @throw `Exception` if the initializer does not contain exactly one element.
394 /// @throw `TypeMismatchException` if the builder contains neither an array nor null.
395 template <typename T>
396 [[deprecated(
397 "Use natively passed argument instead of curly-braces wrapped. Such usage could affect the performance."
398 )]]
399 void PushBack(std::initializer_list<T> initializer) {
400 CheckSingleElementInitializerList(initializer.size());
401 if constexpr (std::is_same_v<T, ValueBuilder>) {
402 PushBack(ValueBuilder{*initializer.begin()});
403 } else {
404 PushBack(*initializer.begin());
405 }
406 }
407
408 /// @brief Add element into the last position of array.
409 /// @throw `TypeMismatchException` if not an array or null.
410 void PushBack(ValueBuilder&& bld);
411
412 /// @brief Copy an existing JSON value into the last position of array.
413 /// @throw `TypeMismatchException` if not an array or null.
414 void PushBack(const formats::json::Value& value);
415
416 /// @brief Move an existing JSON value into the last position of array when
417 /// it is uniquely owned, otherwise copy it.
418 /// @throw `TypeMismatchException` if not an array or null.
419 void PushBack(formats::json::Value&& value);
420
421 /// @brief Take out the resulting `Value` object.
422 /// After calling this method the object is in unspecified
423 /// (but valid - possibly null) state.
424 /// @throw `json::Exception` if called not from the root builder.
426
427private:
428 class EmplaceEnabler {};
429
430public:
431 /// @cond
432 ValueBuilder(EmplaceEnabler, impl::MutableValueWrapper) noexcept;
433 /// @endcond
434
435private:
436 enum class CheckMemberExists { kYes, kNo };
437
438 explicit ValueBuilder(impl::MutableValueWrapper) noexcept;
439
440 static void Copy(impl::Value& to, const ValueBuilder& from);
441 static void Move(impl::Value& to, ValueBuilder&& from);
442
443 static impl::VersionedValuePtr GetSerializedRoot(Value value);
444 static impl::VersionedValuePtr GetMovedValueRoot(Value& value);
445 static impl::MutableValueWrapper GetMovedWrapper(ValueBuilder& other);
446
447 static impl::VersionedValuePtr CreateString(std::string_view value);
448
449 template <typename T>
450 requires impl::IsNormalizedArithmetic<T>
451 static impl::VersionedValuePtr CreateArithmetic(T value);
452
453 void AssignNative(impl::Value value);
454 void AssignNull();
455 void AssignString(std::string_view value);
456 void AssignValue(const Value& value);
457 void AssignValue(Value&& value);
458 template <typename T>
459 requires impl::IsNormalizedArithmetic<T>
460 void AssignArithmetic(T value);
461
462 template <typename T>
463 requires std::is_arithmetic_v<T>
464 static constexpr auto NormalizeArithmetic(T value) noexcept {
465 if constexpr (std::is_same_v<T, bool> || std::is_same_v<T, int> || std::is_same_v<T, unsigned int> ||
466 std::is_same_v<T, float> || std::is_same_v<T, double>)
467 {
468 return value;
469 } else {
470 static_assert(
471 std::is_integral_v<T> && sizeof(T) <= sizeof(std::int64_t),
472 "JSON arithmetic normalization requires an integer no wider than 64 bits"
473 );
474 if constexpr (std::is_signed_v<T>) {
475 return static_cast<std::int64_t>(value);
476 } else {
477 return static_cast<std::uint64_t>(value);
478 }
479 }
480 }
481
482 template <typename T>
483 requires impl::IsNormalizedArithmetic<T>
484 void EmplaceNocheckArithmetic(std::string_view key, T value);
485
486 template <typename T>
487 requires impl::IsNormalizedArithmetic<T>
488 void PushBackArithmetic(T value);
489
490 template <typename MakeValue>
491 USERVER_IMPL_NODEBUG_INLINE_FUNC inline void PushBackNative(MakeValue&& make_value);
492 static void CheckSingleElementInitializerList(std::size_t size);
493
494 impl::Value& AddMember(std::string_view key, CheckMemberExists);
495
496 template <typename MakeValue>
497 USERVER_IMPL_NODEBUG_INLINE_FUNC inline impl::Value& AddMember(
498 std::string_view key,
499 CheckMemberExists,
500 MakeValue&& make_value
501 );
502
503 template <typename T>
504 USERVER_IMPL_NODEBUG_INLINE_FUNC static Value DoSerialize(const T& t) {
505 static_assert(
506 formats::common::impl::HasSerialize<Value, T>,
507 "There is no `Serialize(const T&, formats::serialize::To<json::Value>)` "
508 "in namespace of `T` or `formats::serialize`. "
509 ""
510 "Probably you forgot to include the <userver/formats/serialize/common_containers.hpp> header "
511 "or one of the <formats/json/serialize_*.hpp> headers or you have not provided a `Serialize` function "
512 "overload."
513 );
514
515 return Serialize(t, formats::serialize::To<Value>());
516 }
517
518 impl::MutableValueWrapper value_;
519
520 friend class Iterator<IterTraits, common::IteratorDirection::kForward>;
521 friend class Iterator<IterTraits, common::IteratorDirection::kReverse>;
522};
523
524template <typename T>
525requires(std::is_integral_v<T> && sizeof(T) <= sizeof(std::int64_t))
526Value Serialize(T value, formats::serialize::To<Value>) {
527 using Type = std::conditional_t<std::is_signed<T>::value, int64_t, uint64_t>;
528 return json::ValueBuilder(static_cast<Type>(value)).ExtractValue();
529}
530
531json::Value Serialize(std::chrono::system_clock::time_point tp, formats::serialize::To<Value>);
532
533/// Optimized maps of StrongTypedefs serialization for JSON
534template <typename T>
535requires(meta::IsUniqueMap<T> && utils::IsStrongTypedefLoggable(T::key_type::kOps))
536Value Serialize(const T& value, formats::serialize::To<Value>) {
537 json::ValueBuilder builder(formats::common::Type::kObject);
538 if constexpr (requires { std::ranges::size(value); }) {
539 builder.Reserve(std::ranges::size(value));
540 }
541 for (const auto& [key, value] : value) {
542 builder.EmplaceNocheck(key.GetUnderlying(), value);
543 }
544 return builder.ExtractValue();
545}
546
547/// Optimized maps serialization for JSON
548template <typename T>
549requires meta::IsUniqueMap<T> && std::is_convertible_v<typename T::key_type, std::string>
550Value Serialize(const T& value, formats::serialize::To<Value>) {
551 json::ValueBuilder builder(formats::common::Type::kObject);
552 if constexpr (requires { std::ranges::size(value); }) {
553 builder.Reserve(std::ranges::size(value));
554 }
555 for (const auto& [key, value] : value) {
556 builder.EmplaceNocheck(key, value);
557 }
558 return builder.ExtractValue();
559}
560
561} // namespace formats::json
562
563USERVER_NAMESPACE_END