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 uint64_t.
153 bool IsUInt64() const noexcept;
154
155 /// @brief Returns true if *this holds a double.
156 bool IsDouble() const noexcept;
157
158 /// @brief Returns true if *this is holds a std::string.
159 bool IsString() const noexcept;
160
161 /// @brief Returns true if *this is holds an array (Type::kArray).
162 bool IsArray() const noexcept;
163
164 /// @brief Returns true if *this holds a map (Type::kObject).
165 bool IsObject() const noexcept;
166
167 // clang-format off
168
169 /// @brief Returns value of *this converted to the result type of
170 /// Parse(const Value&, parse::To<T>). Almost always it is T.
171 /// @throw Anything derived from std::exception.
172 ///
173 /// ## Example usage:
174 ///
175 /// @snippet formats/json/value_test.cpp Sample formats::json::Value::As<T>() usage
176 ///
177 /// @see @ref scripts/docs/en/userver/formats.md
178
179 // clang-format on
180
181 template <typename T>
182 auto As() const;
183
184 /// @brief Returns value of *this converted to T or T(args) if
185 /// this->IsMissing().
186 /// @throw Anything derived from std::exception.
187 template <typename T, typename First, typename... Rest>
188 auto As(First&& default_arg, Rest&&... more_default_args) const;
189
190 /// @brief Returns value of *this converted to T or T() if this->IsMissing().
191 /// @throw Anything derived from std::exception.
192 /// @note Use as `value.As<T>({})`
193 template <typename T>
194 auto As(DefaultConstructed) const;
195
196 /// @brief Extracts the specified type with relaxed type checks.
197 /// For example, `true` may be converted to 1.0.
198 template <typename T>
199 T ConvertTo() const;
200
201 /// Extracts the specified type with strict type checks, or constructs the
202 /// default value when the field is not present
203 template <typename T, typename First, typename... Rest>
204 T ConvertTo(First&& default_arg, Rest&&... more_default_args) const;
205
206 /// @brief Returns true if *this holds a `key`.
207 /// @throw TypeMismatchException if `*this` is not a map or null.
208 bool HasMember(std::string_view key) const;
209
210 /// @brief Returns full path to this value.
211 std::string GetPath() const;
212
213 /// @cond
214 void DropRootPath();
215 /// @endcond
216
217 /// @brief Returns new value that is an exact copy of the existing one
218 /// but references different memory (a deep copy of a *this). The returned
219 /// value is a root value with path '/'.
220 /// @throws MemberMissingException if `this->IsMissing()`.
221 Value Clone() const;
222
223 /// @throw MemberMissingException if `this->IsMissing()`.
224 void CheckNotMissing() const;
225
226 /// @throw MemberMissingException if `*this` is not an array or null.
227 void CheckArrayOrNull() const;
228
229 /// @throw TypeMismatchException if `*this` is not a map or null.
230 void CheckObjectOrNull() const;
231
232 /// @throw TypeMismatchException if `*this` is not a map.
233 void CheckObject() const;
234
235 /// @throw TypeMismatchException if `*this` is not a map, array or null.
237
238 /// @throw TypeMismatchException if `*this` is not a map, array or null;
239 /// `OutOfBoundsException` if `index >= this->GetSize()`.
240 void CheckInBounds(std::size_t index) const;
241
242 /// @brief Returns true if *this is a first (root) value.
243 bool IsRoot() const noexcept;
244
245 /// @brief Returns true if `*this` and `other` reference the value by the same
246 /// pointer.
247 bool DebugIsReferencingSameMemory(const Value& other) const { return value_ptr_ == other.value_ptr_; }
248
249private:
250 struct EmplaceEnabler {
251 explicit EmplaceEnabler() = default;
252 };
253
254 class LazyDetachedPath;
255
256public:
257 /// @cond
258 Value(
259 EmplaceEnabler,
260 const impl::VersionedValuePtr& root,
261 const impl::Value* root_ptr_for_path,
262 const impl::Value* value_ptr,
263 int depth
264 );
265
266 Value(
267 EmplaceEnabler,
268 const impl::VersionedValuePtr& root,
269 impl::Value* root_ptr_for_path,
270 LazyDetachedPath&& lazy_detached_path
271 );
272 /// @endcond
273
274private:
275 explicit Value(impl::VersionedValuePtr root) noexcept;
276
277 bool IsUniqueReference() const;
278 void EnsureNotMissing() const;
279 const impl::Value& GetNative() const;
280 impl::Value& GetNative();
281 void SetNative(impl::Value&); // does not copy
282 int GetExtendedType() const;
283
284 impl::VersionedValuePtr holder_{};
285 impl::Value* root_ptr_for_path_{nullptr};
286 impl::Value* value_ptr_{nullptr};
287 /// Depth of the node to ease recursive traversal in GetPath()
288 int depth_{0};
289
290 // We don't want to calculate the path for missing node before it is
291 // explicitly requested, because GetPath() call is very costly.
292 // This helps with patterns like 'json["missing"].As<T>({})':
293 // path is not needed here (note default arg), and if we have a lot of missing
294 // keys during parsing we save a lot of expensive calculations.
295 class LazyDetachedPath final {
296 public:
297 LazyDetachedPath() noexcept;
298 LazyDetachedPath(impl::Value* parent_value_ptr, int parent_depth, std::string_view key);
299
300 LazyDetachedPath(const LazyDetachedPath&);
301 LazyDetachedPath(LazyDetachedPath&&) noexcept;
302 LazyDetachedPath& operator=(const LazyDetachedPath&);
303 LazyDetachedPath& operator=(LazyDetachedPath&&) noexcept;
304
305 std::string Get(const impl::Value* root) const;
306 LazyDetachedPath Chain(std::string_view key) const;
307
308 private:
309 impl::Value* parent_value_ptr_{nullptr};
310 int parent_depth_{0};
311 std::string virtual_path_{};
312 };
313
314 LazyDetachedPath lazy_detached_path_;
315
316 template <typename, common::IteratorDirection>
317 friend class Iterator;
318 friend class ValueBuilder;
319 friend class StringBuilder;
320 friend class Schema;
321 friend class impl::InlineObjectBuilder;
322 friend class impl::InlineArrayBuilder;
323 friend class impl::MutableValueWrapper;
324 friend class parser::JsonValueParser;
325 friend class impl::StringBuffer;
326
327 friend bool Parse(const Value& value, parse::To<bool>);
328 friend std::int64_t Parse(const Value& value, parse::To<std::int64_t>);
329 friend std::uint64_t Parse(const Value& value, parse::To<std::uint64_t>);
330 friend double Parse(const Value& value, parse::To<double>);
331 friend std::string Parse(const Value& value, parse::To<std::string>);
332
333 friend formats::json::Value FromString(std::string_view);
334 friend formats::json::Value FromStream(std::istream&);
335 friend void Serialize(const formats::json::Value&, std::ostream&);
336 friend std::string ToString(const formats::json::Value&);
337 friend std::string ToStableString(const formats::json::Value&);
338 friend std::string ToStableString(formats::json::Value&&);
339 friend std::string ToPrettyString(const formats::json::Value& doc, PrettyFormat format);
340 friend logging::LogHelper& operator<<(logging::LogHelper&, const Value&);
341};
342
343template <typename T>
344auto Value::As() const {
345 static_assert(
346 formats::common::impl::kHasParse<Value, T>,
347 "There is no `Parse(const Value&, formats::parse::To<T>)` "
348 "in namespace of `T` or `formats::parse`. "
349 "Probably you forgot to include the "
350 "<userver/formats/parse/common_containers.hpp> or you "
351 "have not provided a `Parse` function overload."
352 );
353
354 return Parse(*this, formats::parse::To<T>{});
355}
356
357bool Parse(const Value& value, parse::To<bool>);
358
359std::int64_t Parse(const Value& value, parse::To<std::int64_t>);
360
361std::uint64_t Parse(const Value& value, parse::To<std::uint64_t>);
362
363double Parse(const Value& value, parse::To<double>);
364
365std::string Parse(const Value& value, parse::To<std::string>);
366
367template <>
368bool Value::ConvertTo<bool>() const;
369
370template <>
371int64_t Value::ConvertTo<int64_t>() const;
372
373template <>
374uint64_t Value::ConvertTo<uint64_t>() const;
375
376template <>
377double Value::ConvertTo<double>() const;
378
379template <>
380std::string Value::ConvertTo<std::string>() const;
381
382template <typename T, typename First, typename... Rest>
383auto Value::As(First&& default_arg, Rest&&... more_default_args) const {
384 if (IsMissing() || IsNull()) {
385 // intended raw ctor call, sometimes casts
386 // NOLINTNEXTLINE(google-readability-casting)
387 return decltype(As<T>())(std::forward<First>(default_arg), std::forward<Rest>(more_default_args)...);
388 }
389 return As<T>();
390}
391
392template <typename T>
393auto Value::As(Value::DefaultConstructed) const {
394 return (IsMissing() || IsNull()) ? decltype(As<T>())() : As<T>();
395}
396
397template <typename T>
398T Value::ConvertTo() const {
399 if constexpr (formats::common::impl::kHasConvert<Value, T>) {
400 return Convert(*this, formats::parse::To<T>{});
401 } else if constexpr (formats::common::impl::kHasParse<Value, T>) {
402 return Parse(*this, formats::parse::To<T>{});
403 } else {
404 static_assert(
405 !sizeof(T),
406 "There is no `Convert(const Value&, formats::parse::To<T>)` or"
407 "`Parse(const Value&, formats::parse::To<T>)`"
408 "in namespace of `T` or `formats::parse`. "
409 "Probably you have not provided a `Convert` function overload."
410 );
411 }
412}
413
414template <typename T, typename First, typename... Rest>
415T Value::ConvertTo(First&& default_arg, Rest&&... more_default_args) const {
416 if (IsMissing() || IsNull()) {
417 // NOLINTNEXTLINE(google-readability-casting)
418 return T(std::forward<First>(default_arg), std::forward<Rest>(more_default_args)...);
419 }
420 return ConvertTo<T>();
421}
422
423inline Value Parse(const Value& value, parse::To<Value>) { return value; }
424
425std::chrono::microseconds Parse(const Value& value, parse::To<std::chrono::microseconds>);
426
427std::chrono::milliseconds Parse(const Value& value, parse::To<std::chrono::milliseconds>);
428
429std::chrono::minutes Parse(const Value& value, parse::To<std::chrono::minutes>);
430
431std::chrono::hours Parse(const Value& value, parse::To<std::chrono::hours>);
432
433/// @brief Wrapper for handy python-like iteration over a map
434///
435/// @code
436/// for (const auto& [name, value]: Items(map)) ...
437/// @endcode
438using formats::common::Items;
439
440/// gtest formatter for formats::json::Value
441void PrintTo(const Value&, std::ostream*);
442
443} // namespace formats::json
444
445/// Although we provide user defined literals, please beware that
446/// 'using namespace ABC' may contradict code style of your company.
447namespace formats::literals {
448
449json::Value operator"" _json(const char* str, std::size_t len);
450
451} // namespace formats::literals
452
453USERVER_NAMESPACE_END