userver: userver/formats/json/value.hpp Source File
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
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 <chrono>
7#include <iosfwd>
8#include <string_view>
9#include <type_traits>
10
11#include <userver/formats/common/items.hpp>
12#include <userver/formats/common/meta.hpp>
13#include <userver/formats/json/exception.hpp>
14#include <userver/formats/json/impl/types.hpp>
15#include <userver/formats/json/iterator.hpp>
16#include <userver/formats/json/string_builder_fwd.hpp>
17#include <userver/formats/parse/common.hpp>
18
19USERVER_NAMESPACE_BEGIN
20
21namespace logging {
22class LogHelper;
23} // namespace logging
24
25namespace formats::json {
26namespace impl {
27class InlineObjectBuilder;
28class InlineArrayBuilder;
29class MutableValueWrapper;
30class StringBuffer;
31
32// do not make a copy of string
33impl::Value MakeJsonStringViewValue(std::string_view view);
34
35} // namespace impl
36
37class ValueBuilder;
38struct PrettyFormat;
39class Schema;
40
41namespace parser {
42class JsonValueParser;
43} // namespace parser
44
45/// @ingroup userver_universal userver_containers userver_formats
46///
47/// @brief Non-mutable JSON value representation.
48///
49/// Class provides non mutable access JSON value. For modification and
50/// construction of new JSON values use formats::json::ValueBuilder.
51///
52/// ## Example usage:
53///
54/// @snippet formats/json/value_test.cpp Sample formats::json::Value usage
55///
56/// @see @ref scripts/docs/en/userver/formats.md
57///
58/// To iterate over `Value` as object use formats::common::Items.
59class Value final {
60public:
61 struct IterTraits {
62 using ValueType = formats::json::Value;
63 using Reference = const formats::json::Value&;
64 using Pointer = const formats::json::Value*;
65 using ContainerType = Value;
66 };
68
69 using const_iterator = Iterator<IterTraits, common::IteratorDirection::kForward>;
70 using const_reverse_iterator = Iterator<IterTraits, common::IteratorDirection::kReverse>;
71 using Exception = formats::json::Exception;
72 using ParseException = formats::json::ParseException;
73 using ExceptionWithPath = formats::json::ExceptionWithPath;
74 using Builder = ValueBuilder;
75
76 /// @brief Constructs a Value that holds a null.
78
79 Value(const Value&) = default;
80 Value(Value&&) noexcept;
81
82 Value& operator=(const Value&) & = default;
83 Value& operator=(Value&&) noexcept;
84
85 template <class T>
86 Value& operator=(T&&) && {
87 static_assert(
88 !sizeof(T),
89 "You're assigning to a temporary formats::json::Value! Use "
90 "formats::json::ValueBuilder for data modifications."
91 );
92 return *this;
93 }
94
95 /// @brief Access member by key for read.
96 /// @throw TypeMismatchException if not a missing value, an object or null.
97 Value operator[](std::string_view key) const;
98 /// @brief Access array member by index for read.
99 /// @throw TypeMismatchException if not an array value.
100 /// @throw OutOfBoundsException if index is greater or equal
101 /// than size.
102 Value operator[](std::size_t index) const;
103
104 /// @brief Returns an iterator to the beginning of the held array or map.
105 /// @throw TypeMismatchException if not an array, object, or null.
106 ///
107 /// To iterate over `Value` as object use formats::common::Items.
108 const_iterator begin() const;
109
110 /// @brief Returns an iterator to the end of the held array or map.
111 /// @throw TypeMismatchException if not an array, object, or null.
112 const_iterator end() const;
113
114 /// @brief Returns an iterator to the reversed begin of the held array.
115 /// @throw TypeMismatchException if not an array or null.
116 const_reverse_iterator rbegin() const;
117
118 /// @brief Returns an iterator to the reversed end of the held array.
119 /// @throw TypeMismatchException if not an array or null.
120 const_reverse_iterator rend() const;
121
122 /// @brief Returns whether the array or object is empty.
123 /// Returns true for null.
124 /// @throw TypeMismatchException if not an array, object, or null.
125 bool IsEmpty() const;
126
127 /// @brief Returns array size, object members count, or 0 for null.
128 /// @throw TypeMismatchException if not an array, object, or null.
129 std::size_t GetSize() const;
130
131 /// @brief Compares values.
132 /// @throw MemberMissingException if `*this` or `other` is missing.
133 bool operator==(const Value& other) const;
134 bool operator!=(const Value& other) const;
135
136 /// @brief Returns true if *this holds nothing. When `IsMissing()` returns
137 /// `true` any attempt to get the actual value or iterate over *this will
138 bool IsMissing() const noexcept;
139
140 /// @brief Returns true if *this holds a null (Type::kNull).
141 bool IsNull() const noexcept;
142
143 /// @brief Returns true if *this holds a bool.
144 bool IsBool() const noexcept;
145
146 /// @brief Returns true if *this holds an int.
147 bool IsInt() const noexcept;
148
149 /// @brief Returns true if *this holds an int64_t.
150 bool IsInt64() const noexcept;
151
152 /// @brief Returns true if *this holds an uint.
153 bool IsUInt() const noexcept;
154
155 /// @brief Returns true if *this holds an uint64_t.
156 bool IsUInt64() const noexcept;
157
158 /// @brief Returns true if *this holds a double.
159 bool IsDouble() const noexcept;
160
161 /// @brief Returns true if *this is holds a std::string.
162 bool IsString() const noexcept;
163
164 /// @brief Returns true if *this is holds an array (Type::kArray).
165 bool IsArray() const noexcept;
166
167 /// @brief Returns true if *this holds a map (Type::kObject).
168 bool IsObject() const noexcept;
169
170 // clang-format off
171
172 /// @brief Returns value of *this converted to the result type of
173 /// Parse(const Value&, parse::To<T>). Almost always it is T.
174 /// @throw Anything derived from std::exception.
175 ///
176 /// ## Example usage:
177 ///
178 /// @snippet formats/json/value_test.cpp Sample formats::json::Value::As<T>() usage
179 ///
180 /// @see @ref scripts/docs/en/userver/formats.md
181
182 // clang-format on
183
184 template <typename T>
185 auto As() const;
186
187 /// @brief Returns value of *this converted to T or T(args) if
188 /// this->IsMissing().
189 /// @throw Anything derived from std::exception.
190 template <typename T, typename First, typename... Rest>
191 auto As(First&& default_arg, Rest&&... more_default_args) const;
192
193 /// @brief Returns value of *this converted to T or T() if this->IsMissing().
194 /// @throw Anything derived from std::exception.
195 /// @note Use as `value.As<T>({})`
196 template <typename T>
197 auto As(DefaultConstructed) const;
198
199 /// @brief Extracts the specified type with relaxed type checks.
200 /// For example, `true` may be converted to 1.0.
201 template <typename T>
202 T ConvertTo() const;
203
204 /// Extracts the specified type with strict type checks, or constructs the
205 /// default value when the field is not present
206 template <typename T, typename First, typename... Rest>
207 T ConvertTo(First&& default_arg, Rest&&... more_default_args) const;
208
209 /// @brief Returns true if *this holds a `key`.
210 /// @throw TypeMismatchException if `*this` is not a map or null.
211 bool HasMember(std::string_view key) const;
212
213 /// @brief Returns full path to this value.
214 std::string GetPath() const;
215
216 /// @cond
217 void DropRootPath();
218 /// @endcond
219
220 /// @brief Returns new value that is an exact copy of the existing one
221 /// but references different memory (a deep copy of a *this). The returned
222 /// value is a root value with path '/'.
223 /// @throws MemberMissingException if `this->IsMissing()`.
224 Value Clone() const;
225
226 /// @throw MemberMissingException if `this->IsMissing()`.
227 void CheckNotMissing() const;
228
229 /// @throw MemberMissingException if `*this` is not an array or null.
230 void CheckArrayOrNull() const;
231
232 /// @throw TypeMismatchException if `*this` is not a map or null.
233 void CheckObjectOrNull() const;
234
235 /// @throw TypeMismatchException if `*this` is not a map.
236 void CheckObject() const;
237
238 /// @throw TypeMismatchException if `*this` is not a map, array or null.
240
241 /// @throw TypeMismatchException if `*this` is not a map, array or null;
242 /// `OutOfBoundsException` if `index >= this->GetSize()`.
243 void CheckInBounds(std::size_t index) const;
244
245 /// @brief Returns true if *this is a first (root) value.
246 bool IsRoot() const noexcept;
247
248 /// @brief Returns true if `*this` and `other` reference the value by the same
249 /// pointer.
250 bool DebugIsReferencingSameMemory(const Value& other) const { return value_ptr_ == other.value_ptr_; }
251
252private:
253 struct EmplaceEnabler {
254 explicit EmplaceEnabler() = default;
255 };
256
257 class LazyDetachedPath;
258
259public:
260 /// @cond
261 Value(
262 EmplaceEnabler,
263 const impl::VersionedValuePtr& root,
264 const impl::Value* root_ptr_for_path,
265 const impl::Value* value_ptr,
266 int depth
267 );
268
269 Value(
270 EmplaceEnabler,
271 const impl::VersionedValuePtr& root,
272 impl::Value* root_ptr_for_path,
273 LazyDetachedPath&& lazy_detached_path
274 );
275 /// @endcond
276
277private:
278 explicit Value(impl::VersionedValuePtr root) noexcept;
279
280 bool IsUniqueReference() const;
281 void EnsureNotMissing() const;
282 const impl::Value& GetNative() const;
283 impl::Value& GetNative();
284 void SetNative(impl::Value&); // does not copy
285 int GetExtendedType() const;
286
287 impl::VersionedValuePtr holder_{};
288 impl::Value* root_ptr_for_path_{nullptr};
289 impl::Value* value_ptr_{nullptr};
290 /// Depth of the node to ease recursive traversal in GetPath()
291 int depth_{0};
292
293 // We don't want to calculate the path for missing node before it is
294 // explicitly requested, because GetPath() call is very costly.
295 // This helps with patterns like 'json["missing"].As<T>({})':
296 // path is not needed here (note default arg), and if we have a lot of missing
297 // keys during parsing we save a lot of expensive calculations.
298 class LazyDetachedPath final {
299 public:
300 LazyDetachedPath() noexcept;
301 LazyDetachedPath(impl::Value* parent_value_ptr, int parent_depth, std::string_view key);
302
303 LazyDetachedPath(const LazyDetachedPath&);
304 LazyDetachedPath(LazyDetachedPath&&) noexcept;
305 LazyDetachedPath& operator=(const LazyDetachedPath&);
306 LazyDetachedPath& operator=(LazyDetachedPath&&) noexcept;
307
308 std::string Get(const impl::Value* root) const;
309 LazyDetachedPath Chain(std::string_view key) const;
310
311 private:
312 impl::Value* parent_value_ptr_{nullptr};
313 int parent_depth_{0};
314 std::string virtual_path_{};
315 };
316
317 LazyDetachedPath lazy_detached_path_;
318
319 template <typename, common::IteratorDirection>
320 friend class Iterator;
321 friend class ValueBuilder;
322 friend class StringBuilder;
323 friend class Schema;
324 friend class impl::InlineObjectBuilder;
325 friend class impl::InlineArrayBuilder;
326 friend class impl::MutableValueWrapper;
327 friend class parser::JsonValueParser;
328 friend class impl::StringBuffer;
329
330 friend bool Parse(const Value& value, parse::To<bool>);
331 friend std::int64_t Parse(const Value& value, parse::To<std::int64_t>);
332 friend std::uint64_t Parse(const Value& value, parse::To<std::uint64_t>);
333 friend double Parse(const Value& value, parse::To<double>);
334 friend std::string Parse(const Value& value, parse::To<std::string>);
335
336 friend formats::json::Value FromString(std::string_view);
337 friend formats::json::Value FromStream(std::istream&);
338 friend void Serialize(const formats::json::Value&, std::ostream&);
339 friend std::string ToString(const formats::json::Value&);
340 friend std::string ToStableString(const formats::json::Value&);
341 friend std::string ToStableString(formats::json::Value&&);
342 friend std::string ToPrettyString(const formats::json::Value& doc, PrettyFormat format);
343 friend logging::LogHelper& operator<<(logging::LogHelper&, const Value&);
344};
345
346template <typename T>
347auto Value::As() const {
348 static_assert(
349 formats::common::impl::kHasParse<Value, T>,
350 "There is no `Parse(const Value&, formats::parse::To<T>)` "
351 "in namespace of `T` or `formats::parse`. "
352 "Probably you forgot to include the "
353 "<userver/formats/parse/common_containers.hpp> or you "
354 "have not provided a `Parse` function overload."
355 );
356
357 return Parse(*this, formats::parse::To<T>{});
358}
359
360bool Parse(const Value& value, parse::To<bool>);
361
362std::int64_t Parse(const Value& value, parse::To<std::int64_t>);
363
364std::uint64_t Parse(const Value& value, parse::To<std::uint64_t>);
365
366double Parse(const Value& value, parse::To<double>);
367
368std::string Parse(const Value& value, parse::To<std::string>);
369
370template <>
371bool Value::ConvertTo<bool>() const;
372
373template <>
374int64_t Value::ConvertTo<int64_t>() const;
375
376template <>
377uint64_t Value::ConvertTo<uint64_t>() const;
378
379template <>
380double Value::ConvertTo<double>() const;
381
382template <>
383std::string Value::ConvertTo<std::string>() const;
384
385template <typename T, typename First, typename... Rest>
386auto Value::As(First&& default_arg, Rest&&... more_default_args) const {
387 if (IsMissing() || IsNull()) {
388 // intended raw ctor call, sometimes casts
389 // NOLINTNEXTLINE(google-readability-casting)
390 return decltype(As<T>())(std::forward<First>(default_arg), std::forward<Rest>(more_default_args)...);
391 }
392 return As<T>();
393}
394
395template <typename T>
396auto Value::As(Value::DefaultConstructed) const {
397 return (IsMissing() || IsNull()) ? decltype(As<T>())() : As<T>();
398}
399
400template <typename T>
401T Value::ConvertTo() const {
402 if constexpr (formats::common::impl::kHasConvert<Value, T>) {
403 return Convert(*this, formats::parse::To<T>{});
404 } else if constexpr (formats::common::impl::kHasParse<Value, T>) {
405 return Parse(*this, formats::parse::To<T>{});
406 } else {
407 static_assert(
408 !sizeof(T),
409 "There is no `Convert(const Value&, formats::parse::To<T>)` or"
410 "`Parse(const Value&, formats::parse::To<T>)`"
411 "in namespace of `T` or `formats::parse`. "
412 "Probably you have not provided a `Convert` function overload."
413 );
414 }
415}
416
417template <typename T, typename First, typename... Rest>
418T Value::ConvertTo(First&& default_arg, Rest&&... more_default_args) const {
419 if (IsMissing() || IsNull()) {
420 // NOLINTNEXTLINE(google-readability-casting)
421 return T(std::forward<First>(default_arg), std::forward<Rest>(more_default_args)...);
422 }
423 return ConvertTo<T>();
424}
425
426inline Value Parse(const Value& value, parse::To<Value>) { return value; }
427
428std::chrono::microseconds Parse(const Value& value, parse::To<std::chrono::microseconds>);
429
430std::chrono::milliseconds Parse(const Value& value, parse::To<std::chrono::milliseconds>);
431
432std::chrono::minutes Parse(const Value& value, parse::To<std::chrono::minutes>);
433
434std::chrono::hours Parse(const Value& value, parse::To<std::chrono::hours>);
435
436/// @brief Wrapper for handy python-like iteration over a map
437///
438/// @code
439/// for (const auto& [name, value]: Items(map)) ...
440/// @endcode
441using formats::common::Items;
442
443/// gtest formatter for formats::json::Value
444void PrintTo(const Value&, std::ostream*);
445
446} // namespace formats::json
447
448/// Although we provide user defined literals, please beware that
449/// 'using namespace ABC' may contradict code style of your company.
450namespace formats::literals {
451
452json::Value operator""_json(const char* str, std::size_t len);
453
454} // namespace formats::literals
455
456USERVER_NAMESPACE_END