Github   Telegram
Loading...
Searching...
No Matches
value.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/formats/json/value.hpp
4/// @brief @copybrief formats::json::Value
5
6#include <string_view>
7#include <type_traits>
8
9#include <userver/formats/common/items.hpp>
10#include <userver/formats/common/meta.hpp>
11#include <userver/formats/json/exception.hpp>
12#include <userver/formats/json/impl/types.hpp>
13#include <userver/formats/json/iterator.hpp>
14#include <userver/formats/json/serialize.hpp>
15#include <userver/formats/json/string_builder_fwd.hpp>
16#include <userver/formats/parse/common.hpp>
17
18USERVER_NAMESPACE_BEGIN
19
20namespace logging {
21class LogHelper;
22} // namespace logging
23
24namespace formats::json {
25namespace impl {
26class InlineObjectBuilder;
27class InlineArrayBuilder;
28class MutableValueWrapper;
29class StringBuffer;
30
31// do not make a copy of string
32impl::Value MakeJsonStringViewValue(std::string_view view);
33
34} // namespace impl
35
36class ValueBuilder;
37
38namespace parser {
39class JsonValueParser;
40} // namespace parser
41
42/// @ingroup userver_containers userver_formats
43///
44/// @brief Non-mutable JSON value representation.
45///
46/// Class provides non mutable access JSON value. For modification and
47/// construction of new JSON values use formats::json::ValueBuilder.
48///
49/// ## Example usage:
50///
51/// @snippet formats/json/value_test.cpp Sample formats::json::Value usage
52///
53/// @see @ref md_en_userver_formats
54class Value final {
55 public:
56 struct IterTraits {
57 using ValueType = formats::json::Value;
58 using Reference = const formats::json::Value&;
59 using Pointer = const formats::json::Value*;
60 using ContainerType = Value;
61 };
63
64 using const_iterator =
70 using Builder = ValueBuilder;
71
72 /// @brief Constructs a Value that holds a null.
73 Value() noexcept = default;
74
75 Value(const Value&) = default;
76 Value(Value&&) noexcept = default;
77
78 Value& operator=(const Value&) & = default;
79 Value& operator=(Value&& other) & noexcept = default;
80
81 template <class T>
82 Value& operator=(T&&) && {
83 static_assert(!sizeof(T),
84 "You're assigning to a temporary formats::json::Value! Use "
85 "formats::json::ValueBuilder for data modifications.");
86 return *this;
87 }
88
89 /// @brief Access member by key for read.
90 /// @throw TypeMismatchException if not a missing value, an object or null.
92 /// @brief Access array member by index for read.
93 /// @throw TypeMismatchException if not an array value.
94 /// @throw OutOfBoundsException if index is greater or equal
95 /// than size.
97
98 /// @brief Returns an iterator to the beginning of the held array or map.
99 /// @throw TypeMismatchException if not an array, object, or null.
101
102 /// @brief Returns an iterator to the end of the held array or map.
103 /// @throw TypeMismatchException if not an array, object, or null.
105
106 /// @brief Returns an iterator to the reversed begin of the held array.
107 /// @throw TypeMismatchException if not an array or null.
109
110 /// @brief Returns an iterator to the reversed end of the held array.
111 /// @throw TypeMismatchException if not an array or null.
113
114 /// @brief Returns whether the array or object is empty.
115 /// Returns true for null.
116 /// @throw TypeMismatchException if not an array, object, or null.
117 bool IsEmpty() const;
118
119 /// @brief Returns array size, object members count, or 0 for null.
120 /// @throw TypeMismatchException if not an array, object, or null.
122
123 /// @brief Compares values.
124 /// @throw MemberMissingException if `*this` or `other` is missing.
125 bool operator==(const Value& other) const;
126 bool operator!=(const Value& other) const;
127
128 /// @brief Returns true if *this holds nothing. When `IsMissing()` returns
129 /// `true` any attempt to get the actual value or iterate over *this will
130 bool IsMissing() const noexcept;
131
132 /// @brief Returns true if *this holds a null (Type::kNull).
133 bool IsNull() const noexcept;
134
135 /// @brief Returns true if *this holds a bool.
136 bool IsBool() const noexcept;
137
138 /// @brief Returns true if *this holds an int.
139 bool IsInt() const noexcept;
140
141 /// @brief Returns true if *this holds an int64_t.
142 bool IsInt64() const noexcept;
143
144 /// @brief Returns true if *this holds an uint64_t.
145 bool IsUInt64() const noexcept;
146
147 /// @brief Returns true if *this holds a double.
148 bool IsDouble() const noexcept;
149
150 /// @brief Returns true if *this is holds a std::string.
151 bool IsString() const noexcept;
152
153 /// @brief Returns true if *this is holds an array (Type::kArray).
154 bool IsArray() const noexcept;
155
156 /// @brief Returns true if *this holds a map (Type::kObject).
157 bool IsObject() const noexcept;
158
159 // clang-format off
160
161 /// @brief Returns value of *this converted to T.
162 /// @throw Anything derived from std::exception.
163 ///
164 /// ## Example usage:
165 ///
166 /// @snippet formats/json/value_test.cpp Sample formats::json::Value::As<T>() usage
167 ///
168 /// @see @ref md_en_userver_formats
169
170 // clang-format on
171
172 template <typename T>
173 T As() const;
174
175 /// @brief Returns value of *this converted to T or T(args) if
176 /// this->IsMissing().
177 /// @throw Anything derived from std::exception.
178 template <typename T, typename First, typename... Rest>
180
181 /// @brief Returns value of *this converted to T or T() if this->IsMissing().
182 /// @throw Anything derived from std::exception.
183 /// @note Use as `value.As<T>({})`
184 template <typename T>
185 T As(DefaultConstructed) const;
186
187 /// @brief Extracts the specified type with relaxed type checks.
188 /// For example, `true` may be converted to 1.0.
189 template <typename T>
190 T ConvertTo() const;
191
192 /// Extracts the specified type with strict type checks, or constructs the
193 /// default value when the field is not present
194 template <typename T, typename First, typename... Rest>
196
197 /// @brief Returns true if *this holds a `key`.
198 /// @throw TypeMismatchException if `*this` is not a map or null.
200
201 /// @brief Returns full path to this value.
203
204 /// @brief Returns new value that is an exact copy if the existing one
205 /// but references different memory (a deep copy of a *this). The returned
206 /// value is a root value with path '/'.
207 /// @throws MemberMissingException id `this->IsMissing()`.
208 Value Clone() const;
209
210 /// @throw MemberMissingException if `this->IsMissing()`.
211 void CheckNotMissing() const;
212
213 /// @throw MemberMissingException if `*this` is not an array or null.
214 void CheckArrayOrNull() const;
215
216 /// @throw TypeMismatchException if `*this` is not a map or null.
217 void CheckObjectOrNull() const;
218
219 /// @throw TypeMismatchException if `*this` is not a map.
220 void CheckObject() const;
221
222 /// @throw TypeMismatchException if `*this` is not a map, array or null.
224
225 /// @throw TypeMismatchException if `*this` is not a map, array or null;
226 /// `OutOfBoundsException` if `index >= this->GetSize()`.
228
229 /// @brief Returns true if *this is a first (root) value.
230 bool IsRoot() const noexcept;
231
232 /// @brief Returns true if `*this` and `other` reference the value by the same
233 /// pointer.
235 return value_ptr_ == other.value_ptr_;
236 }
237
238 private:
239 class EmplaceEnabler {};
240
241 public:
242 /// @cond
244 const impl::Value& value, int depth);
245 /// @endcond
246
247 private:
248 explicit Value(impl::VersionedValuePtr root) noexcept;
251
252 bool IsUniqueReference() const;
253 void EnsureNotMissing();
254 const impl::Value& GetNative() const;
255 impl::Value& GetNative();
256 void SetNative(impl::Value&); // does not copy
257 int GetExtendedType() const;
258
260 impl::Value* value_ptr_{nullptr};
261 /// Full path of node (only for missing nodes)
263 /// Depth of the node to ease recursive traversal in GetPath()
264 int depth_{0};
265
266 template <typename, common::IteratorDirection>
267 friend class Iterator;
268 friend class ValueBuilder;
269 friend class StringBuilder;
270 friend class impl::InlineObjectBuilder;
271 friend class impl::InlineArrayBuilder;
272 friend class impl::MutableValueWrapper;
273 friend class parser::JsonValueParser;
274 friend class impl::StringBuffer;
275
278 friend void Serialize(const formats::json::Value&, std::ostream&);
279 friend std::string ToString(const formats::json::Value&);
283};
284
285template <typename T>
286T Value::As() const {
287 static_assert(formats::common::impl::kHasParse<Value, T>,
288 "There is no `Parse(const Value&, formats::parse::To<T>)` "
289 "in namespace of `T` or `formats::parse`. "
290 "Probably you forgot to include the "
291 "<userver/formats/parse/common_containers.hpp> or you "
292 "have not provided a `Parse` function overload.");
293
294 return Parse(*this, formats::parse::To<T>{});
295}
296
297template <>
298bool Value::As<bool>() const;
299
300template <>
301int64_t Value::As<int64_t>() const;
302
303template <>
304uint64_t Value::As<uint64_t>() const;
305
306template <>
307double Value::As<double>() const;
308
309template <>
310std::string Value::As<std::string>() const;
311
312template <>
313bool Value::ConvertTo<bool>() const;
314
315template <>
316int64_t Value::ConvertTo<int64_t>() const;
317
318template <>
319uint64_t Value::ConvertTo<uint64_t>() const;
320
321template <>
322double Value::ConvertTo<double>() const;
323
324template <>
325std::string Value::ConvertTo<std::string>() const;
326
327template <typename T, typename First, typename... Rest>
328T Value::As(First&& default_arg, Rest&&... more_default_args) const {
329 if (IsMissing() || IsNull()) {
330 // intended raw ctor call, sometimes casts
331 // NOLINTNEXTLINE(google-readability-casting)
332 return T(std::forward<First>(default_arg),
333 std::forward<Rest>(more_default_args)...);
334 }
335 return As<T>();
336}
337
338template <typename T>
339T Value::As(Value::DefaultConstructed) const {
340 return (IsMissing() || IsNull()) ? T() : As<T>();
341}
342
343template <typename T>
344T Value::ConvertTo() const {
345 if constexpr (formats::common::impl::kHasConvert<Value, T>) {
346 return Convert(*this, formats::parse::To<T>{});
347 } else if constexpr (formats::common::impl::kHasParse<Value, T>) {
348 return Parse(*this, formats::parse::To<T>{});
349 } else {
350 static_assert(
351 !sizeof(T),
352 "There is no `Convert(const Value&, formats::parse::To<T>)` or"
353 "`Parse(const Value&, formats::parse::To<T>)`"
354 "in namespace of `T` or `formats::parse`. "
355 "Probably you have not provided a `Convert` function overload.");
356 }
357}
358
359template <typename T, typename First, typename... Rest>
360T Value::ConvertTo(First&& default_arg, Rest&&... more_default_args) const {
361 if (IsMissing() || IsNull()) {
362 // NOLINTNEXTLINE(google-readability-casting)
363 return T(std::forward<First>(default_arg),
364 std::forward<Rest>(more_default_args)...);
365 }
366 return ConvertTo<T>();
367}
368
369inline Value Parse(const Value& value, parse::To<Value>) { return value; }
370
371/// @brief Wrapper for handy python-like iteration over a map
372///
373/// @code
374/// for (const auto& [name, value]: Items(map)) ...
375/// @endcode
376using formats::common::Items;
377
378} // namespace formats::json
379
380/// Although we provide user defined literals, please beware that
381/// 'using namespace ABC' may contradict code style of your company.
382namespace formats::literals {
383
384json::Value operator"" _json(const char* str, std::size_t len);
385
386} // namespace formats::literals
387
388USERVER_NAMESPACE_END