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`.
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) : ValueBuilder() {}
75 ValueBuilder(bool t);
76 ValueBuilder(const char* str);
77 ValueBuilder(char* str);
78 ValueBuilder(const std::string& str);
79 ValueBuilder(std::string_view str);
80 ValueBuilder(int t);
81 ValueBuilder(unsigned int t);
82 ValueBuilder(uint64_t t);
83 ValueBuilder(int64_t t);
84 ValueBuilder(float t);
85 ValueBuilder(double t);
86 /// @}
87
88 /// Universal constructor using Serialize
89 template <
90 typename T,
91 typename = std::enable_if_t<
92 !std::is_same_v<std::decay_t<T>, ValueBuilder> && !std::is_same_v<std::decay_t<T>, Value> &&
93 !std::is_same_v<std::decay_t<T>, std::string>>>
94 ValueBuilder(T&& t) : ValueBuilder(DoSerialize(std::forward<T>(t))) {}
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 <
106 typename Tag,
107 utils::StrongTypedefOps Ops,
108 typename Enable = std::enable_if_t<utils::IsStrongTypedefLoggable(Ops)>>
109 ValueBuilder operator[](utils::StrongTypedef<Tag, std::string, Ops> key);
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.
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(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(T&& t) {
209 static_assert(
210 formats::common::impl::kHasSerialize<Value, std::remove_reference_t<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 "
215 "<userver/formats/serialize/common_containers.hpp> header "
216 "or one of the <formats/json/serialize_*.hpp> headers or you "
217 "have not provided a `Serialize` function overload."
218 );
219
220 return Serialize(std::forward<T>(t), formats::serialize::To<Value>());
221}
222
223template <typename T>
224std::enable_if_t<std::is_integral<T>::value && sizeof(T) <= sizeof(int64_t), Value>
225Serialize(T value, formats::serialize::To<Value>) {
226 using Type = std::conditional_t<std::is_signed<T>::value, int64_t, uint64_t>;
227 return json::ValueBuilder(static_cast<Type>(value)).ExtractValue();
228}
229
230json::Value Serialize(std::chrono::system_clock::time_point tp, formats::serialize::To<Value>);
231
232template <typename Tag, utils::StrongTypedefOps Ops, typename Enable>
233ValueBuilder ValueBuilder::operator[](utils::StrongTypedef<Tag, std::string, Ops> key) {
234 return (*this)[std::move(key.GetUnderlying())];
235}
236
237/// Optimized maps of StrongTypedefs serialization for JSON
238template <typename T>
239std::enable_if_t<meta::kIsUniqueMap<T> && utils::IsStrongTypedefLoggable(T::key_type::kOps), Value>
240Serialize(const T& value, formats::serialize::To<Value>) {
241 json::ValueBuilder builder(formats::common::Type::kObject);
242 for (const auto& [key, value] : value) {
243 builder.EmplaceNocheck(key.GetUnderlying(), value);
244 }
245 return builder.ExtractValue();
246}
247
248/// Optimized maps serialization for JSON
249template <typename T>
250std::enable_if_t<meta::kIsUniqueMap<T> && std::is_convertible_v<typename T::key_type, std::string>, Value>
251Serialize(const T& value, formats::serialize::To<Value>) {
252 json::ValueBuilder builder(formats::common::Type::kObject);
253 for (const auto& [key, value] : value) {
254 builder.EmplaceNocheck(key, value);
255 }
256 return builder.ExtractValue();
257}
258
259} // namespace formats::json
260
261USERVER_NAMESPACE_END