userver: userver/formats/json/value.hpp Source File
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 <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 {
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>
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 TypeMismatchException 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 an array.
236 void CheckArray() const;
237
238 /// @throw TypeMismatchException if `*this` is not a map.
239 void CheckObject() const;
240
241 /// @throw TypeMismatchException if `*this` is not a map, array or null.
243
244 /// @throw TypeMismatchException if `*this` is not an array or null;
245 /// `OutOfBoundsException` if `index >= this->GetSize()`.
246 void CheckInBounds(std::size_t index) const;
247
248 /// @brief Returns true if *this is a first (root) value.
249 bool IsRoot() const noexcept;
250
251 /// @brief Returns true if `*this` and `other` reference the value by the same
252 /// pointer.
253 bool DebugIsReferencingSameMemory(const Value& other) const { return value_ptr_ == other.value_ptr_; }
254
255private:
256 struct EmplaceEnabler {
257 explicit EmplaceEnabler() = default;
258 };
259
260 class LazyDetachedPath;
261
262public:
263 /// @cond
264 Value(
265 EmplaceEnabler,
266 const impl::VersionedValuePtr& root,
267 const impl::Value* root_ptr_for_path,
268 const impl::Value* value_ptr,
269 int depth
270 );
271
272 Value(
273 EmplaceEnabler,
274 const impl::VersionedValuePtr& root,
275 impl::Value* root_ptr_for_path,
276 LazyDetachedPath&& lazy_detached_path
277 );
278 /// @endcond
279
280private:
281 explicit Value(impl::VersionedValuePtr root) noexcept;
282
283 bool IsUniqueReference() const;
284 void EnsureNotMissing() const;
285 const impl::Value& GetNative() const;
286 impl::Value& GetNative();
287 void SetNative(impl::Value&); // does not copy
288 int GetExtendedType() const;
289
290 impl::VersionedValuePtr holder_{};
291 impl::Value* root_ptr_for_path_{nullptr};
292 impl::Value* value_ptr_{nullptr};
293 /// Depth of the node to ease recursive traversal in GetPath()
294 int depth_{0};
295
296 // We don't want to calculate the path for missing node before it is
297 // explicitly requested, because GetPath() call is very costly.
298 // This helps with patterns like 'json["missing"].As<T>({})':
299 // path is not needed here (note default arg), and if we have a lot of missing
300 // keys during parsing we save a lot of expensive calculations.
301 class LazyDetachedPath final {
302 public:
303 LazyDetachedPath() noexcept;
304 LazyDetachedPath(impl::Value* parent_value_ptr, int parent_depth, std::string_view key);
305
306 LazyDetachedPath(const LazyDetachedPath&);
307 LazyDetachedPath(LazyDetachedPath&&) noexcept;
308 LazyDetachedPath& operator=(const LazyDetachedPath&);
309 LazyDetachedPath& operator=(LazyDetachedPath&&) noexcept;
310
311 std::string Get(const impl::Value* root) const;
312 LazyDetachedPath Chain(std::string_view key) const;
313
314 private:
315 impl::Value* parent_value_ptr_{nullptr};
316 int parent_depth_{0};
317 std::string virtual_path_{};
318 };
319
320 LazyDetachedPath lazy_detached_path_;
321
322 template <typename, common::IteratorDirection>
323 friend class Iterator;
324 friend class ValueBuilder;
325 friend class StringBuilder;
326 friend class Schema;
327 friend class impl::InlineObjectBuilder;
328 friend class impl::InlineArrayBuilder;
329 friend class impl::MutableValueWrapper;
330 friend class parser::JsonValueParser;
331 friend class impl::StringBuffer;
332
333 friend bool Parse(const Value& value, parse::To<bool>);
334 friend std::int64_t Parse(const Value& value, parse::To<std::int64_t>);
335 friend std::uint64_t Parse(const Value& value, parse::To<std::uint64_t>);
336 friend double Parse(const Value& value, parse::To<double>);
337 friend std::string Parse(const Value& value, parse::To<std::string>);
338
339 friend formats::json::Value FromString(std::string_view);
340 friend formats::json::Value FromStream(std::istream&);
341 friend void Serialize(const formats::json::Value&, std::ostream&);
342 friend std::string ToString(const formats::json::Value&);
343 friend std::string ToStableString(const formats::json::Value&);
344 friend std::string ToStableString(formats::json::Value&&);
345 friend std::string ToPrettyString(const formats::json::Value& doc, PrettyFormat format);
346 friend logging::LogHelper& operator<<(logging::LogHelper&, const Value&);
347};
348
349template <typename T>
350auto Value::As() const {
351 static_assert(
352 formats::common::impl::kHasParse<Value, T>,
353 "There is no `Parse(const Value&, formats::parse::To<T>)` "
354 "in namespace of `T` or `formats::parse`. "
355 "Probably you forgot to include the "
356 "<userver/formats/parse/common_containers.hpp> or you "
357 "have not provided a `Parse` function overload."
358 );
359
360 return Parse(*this, formats::parse::To<T>{});
361}
362
363bool Parse(const Value& value, parse::To<bool>);
364
365std::int64_t Parse(const Value& value, parse::To<std::int64_t>);
366
367std::uint64_t Parse(const Value& value, parse::To<std::uint64_t>);
368
369double Parse(const Value& value, parse::To<double>);
370
371std::string Parse(const Value& value, parse::To<std::string>);
372
373template <>
374bool Value::ConvertTo<bool>() const;
375
376template <>
377int64_t Value::ConvertTo<int64_t>() const;
378
379template <>
380uint64_t Value::ConvertTo<uint64_t>() const;
381
382template <>
383double Value::ConvertTo<double>() const;
384
385template <>
386std::string Value::ConvertTo<std::string>() const;
387
388template <typename T, typename First, typename... Rest>
389auto Value::As(First&& default_arg, Rest&&... more_default_args) const {
390 if (IsMissing() || IsNull()) {
391 // intended raw ctor call, sometimes casts
392 // NOLINTNEXTLINE(google-readability-casting)
393 return decltype(As<T>())(std::forward<First>(default_arg), std::forward<Rest>(more_default_args)...);
394 }
395 return As<T>();
396}
397
398template <typename T>
400 return (IsMissing() || IsNull()) ? decltype(As<T>())() : As<T>();
401}
402
403template <typename T>
404T Value::ConvertTo() const {
405 if constexpr (formats::common::impl::kHasConvert<Value, T>) {
406 return Convert(*this, formats::parse::To<T>{});
407 } else if constexpr (formats::common::impl::kHasParse<Value, T>) {
408 return Parse(*this, formats::parse::To<T>{});
409 } else {
410 static_assert(
411 !sizeof(T),
412 "There is no `Convert(const Value&, formats::parse::To<T>)` or"
413 "`Parse(const Value&, formats::parse::To<T>)`"
414 "in namespace of `T` or `formats::parse`. "
415 "Probably you have not provided a `Convert` function overload."
416 );
417 }
418}
419
420template <typename T, typename First, typename... Rest>
421T Value::ConvertTo(First&& default_arg, Rest&&... more_default_args) const {
422 if (IsMissing() || IsNull()) {
423 // NOLINTNEXTLINE(google-readability-casting)
424 return T(std::forward<First>(default_arg), std::forward<Rest>(more_default_args)...);
425 }
426 return ConvertTo<T>();
427}
428
429inline Value Parse(const Value& value, parse::To<Value>) { return value; }
430
431std::chrono::microseconds Parse(const Value& value, parse::To<std::chrono::microseconds>);
432
433std::chrono::milliseconds Parse(const Value& value, parse::To<std::chrono::milliseconds>);
434
435std::chrono::minutes Parse(const Value& value, parse::To<std::chrono::minutes>);
436
437std::chrono::hours Parse(const Value& value, parse::To<std::chrono::hours>);
438
439/// @brief Wrapper for handy python-like iteration over a map
440///
441/// @code
442/// for (const auto& [name, value]: Items(map)) ...
443/// @endcode
444using formats::common::Items;
445
446/// gtest formatter for formats::json::Value
447void PrintTo(const Value&, std::ostream*);
448
449} // namespace formats::json
450
451/// Although we provide user defined literals, please beware that
452/// 'using namespace ABC' may contradict code style of your company.
453namespace formats::literals {
454
455json::Value operator""_json(const char* str, std::size_t len);
456
457} // namespace formats::literals
458
459USERVER_NAMESPACE_END