userver: userver/formats/json/value.hpp Source File
Loading...
Searching...
No Matches
value.hpp
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
135 /// @brief Returns true if *this holds nothing. When `IsMissing()` returns
136 /// `true` any attempt to get the actual value or iterate over *this will
137 bool IsMissing() const noexcept;
138
139 /// @brief Returns true if *this holds a null (Type::kNull).
140 bool IsNull() const noexcept;
141
142 /// @brief Returns true if *this holds a bool.
143 bool IsBool() const noexcept;
144
145 /// @brief Returns true if *this holds an int.
146 bool IsInt() const noexcept;
147
148 /// @brief Returns true if *this holds an int64_t.
149 bool IsInt64() const noexcept;
150
151 /// @brief Returns true if *this holds an uint.
152 bool IsUInt() const noexcept;
153
154 /// @brief Returns true if *this holds an uint64_t.
155 bool IsUInt64() const noexcept;
156
157 /// @brief Returns true if *this holds a double.
158 bool IsDouble() const noexcept;
159
160 /// @brief Returns true if *this holds a number (integer or floating point).
161 bool IsNumber() const noexcept;
162
163 /// @brief Returns true if *this is holds a std::string.
164 bool IsString() const noexcept;
165
166 /// @brief Returns true if *this is holds an array (Type::kArray).
167 bool IsArray() const noexcept;
168
169 /// @brief Returns true if *this holds a map (Type::kObject).
170 bool IsObject() const noexcept;
171
172 // clang-format off
173
174 /// @brief Returns value of *this converted to the result type of
175 /// Parse(const Value&, parse::To<T>). Almost always it is T.
176 /// @throw Anything derived from std::exception.
177 ///
178 /// ## Example usage:
179 ///
180 /// @snippet formats/json/value_test.cpp Sample formats::json::Value::As<T>() usage
181 ///
182 /// @see @ref scripts/docs/en/userver/formats.md
183
184 // clang-format on
185
186 template <typename T>
187 auto As() const;
188
189 /// @brief Returns value of *this converted to T or T(args) if
190 /// this->IsMissing().
191 /// @throw Anything derived from std::exception.
192 template <typename T, typename First, typename... Rest>
193 auto As(First&& default_arg, Rest&&... more_default_args) const;
194
195 /// @brief Returns value of *this converted to T or T() if this->IsMissing().
196 /// @throw Anything derived from std::exception.
197 /// @note Use as `value.As<T>({})`
198 template <typename T>
200
201 /// @brief Extracts the specified type with relaxed type checks.
202 /// For example, `true` may be converted to 1.0.
203 template <typename T>
204 T ConvertTo() const;
205
206 /// Extracts the specified type with strict type checks, or constructs the
207 /// default value when the field is not present
208 template <typename T, typename First, typename... Rest>
209 T ConvertTo(First&& default_arg, Rest&&... more_default_args) const;
210
211 /// @brief Returns true if *this holds a `key`.
212 /// @throw TypeMismatchException if `*this` is not a map or null.
213 bool HasMember(std::string_view key) const;
214
215 /// @brief Returns full path to this value.
216 std::string GetPath() const;
217
218 /// @cond
219 void DropRootPath();
220 /// @endcond
221
222 /// @brief Returns new value that is an exact copy of the existing one
223 /// but references different memory (a deep copy of a *this). The returned
224 /// value is a root value with path '/'.
225 /// @throws MemberMissingException if `this->IsMissing()`.
226 Value Clone() const;
227
228 /// @throw MemberMissingException if `this->IsMissing()`.
229 void CheckNotMissing() const;
230
231 /// @throw TypeMismatchException if `*this` is not an array or null.
232 void CheckArrayOrNull() const;
233
234 /// @throw TypeMismatchException if `*this` is not a map or null.
235 void CheckObjectOrNull() const;
236
237 /// @throw TypeMismatchException if `*this` is not an array.
238 void CheckArray() const;
239
240 /// @throw TypeMismatchException if `*this` is not a map.
241 void CheckObject() const;
242
243 /// @throw TypeMismatchException if `*this` is not a map, array or null.
245
246 /// @throw TypeMismatchException if `*this` is not an array or null;
247 /// `OutOfBoundsException` if `index >= this->GetSize()`.
248 void CheckInBounds(std::size_t index) const;
249
250 /// @brief Returns true if *this is a first (root) value.
251 bool IsRoot() const noexcept;
252
253 /// @brief Returns true if `*this` and `other` reference the value by the same
254 /// pointer.
255 bool DebugIsReferencingSameMemory(const Value& other) const { return value_ptr_ == other.value_ptr_; }
256
257private:
258 struct EmplaceEnabler {
259 explicit EmplaceEnabler() = default;
260 };
261
262 class LazyDetachedPath;
263
264public:
265 /// @cond
266 Value(
267 EmplaceEnabler,
268 const impl::VersionedValuePtr& root,
269 const impl::Value* root_ptr_for_path,
270 const impl::Value* value_ptr,
271 int depth
272 );
273
274 Value(
275 EmplaceEnabler,
276 const impl::VersionedValuePtr& root,
277 impl::Value* root_ptr_for_path,
278 LazyDetachedPath&& lazy_detached_path
279 );
280 /// @endcond
281
282private:
283 explicit Value(impl::VersionedValuePtr root) noexcept;
284
285 bool IsUniqueReference() const;
286 void EnsureNotMissing() const;
287 const impl::Value& GetNative() const;
288 impl::Value& GetNative();
289 void SetNative(impl::Value&); // does not copy
290 int GetExtendedType() const;
291
292 impl::VersionedValuePtr holder_{};
293 impl::Value* root_ptr_for_path_{nullptr};
294 impl::Value* value_ptr_{nullptr};
295 /// Depth of the node to ease recursive traversal in GetPath()
296 int depth_{0};
297
298 // We don't want to calculate the path for missing node before it is
299 // explicitly requested, because GetPath() call is very costly.
300 // This helps with patterns like 'json["missing"].As<T>({})':
301 // path is not needed here (note default arg), and if we have a lot of missing
302 // keys during parsing we save a lot of expensive calculations.
303 class LazyDetachedPath final {
304 public:
305 LazyDetachedPath() noexcept;
306 LazyDetachedPath(impl::Value* parent_value_ptr, int parent_depth, std::string_view key);
307
308 LazyDetachedPath(const LazyDetachedPath&);
309 LazyDetachedPath(LazyDetachedPath&&) noexcept;
310 LazyDetachedPath& operator=(const LazyDetachedPath&);
311 LazyDetachedPath& operator=(LazyDetachedPath&&) noexcept;
312
313 std::string Get(const impl::Value* root) const;
314 LazyDetachedPath Chain(std::string_view key) const;
315
316 private:
317 impl::Value* parent_value_ptr_{nullptr};
318 int parent_depth_{0};
319 std::string virtual_path_{};
320 };
321
322 LazyDetachedPath lazy_detached_path_;
323
324 template <typename, common::IteratorDirection>
325 friend class Iterator;
326 friend class ValueBuilder;
327 friend class StringBuilder;
328 friend class Schema;
329 friend class impl::InlineObjectBuilder;
330 friend class impl::InlineArrayBuilder;
331 friend class impl::MutableValueWrapper;
332 friend class parser::JsonValueParser;
333 friend class impl::StringBuffer;
334
335 friend bool Parse(const Value& value, parse::To<bool>);
336 friend std::int64_t Parse(const Value& value, parse::To<std::int64_t>);
337 friend std::uint64_t Parse(const Value& value, parse::To<std::uint64_t>);
338 friend double Parse(const Value& value, parse::To<double>);
339 friend std::string Parse(const Value& value, parse::To<std::string>);
340
341 friend formats::json::Value FromString(std::string_view);
342 friend formats::json::Value FromStream(std::istream&);
343 friend void Serialize(const formats::json::Value&, std::ostream&);
344 friend std::string ToString(const formats::json::Value&);
345 friend std::string ToStableString(const formats::json::Value&);
346 friend std::string ToStableString(formats::json::Value&&);
347 friend std::string ToPrettyString(const formats::json::Value& doc, PrettyFormat format);
348 friend logging::LogHelper& operator<<(logging::LogHelper&, const Value&);
349};
350
351template <typename T>
352auto Value::As() const {
353 static_assert(
354 formats::common::impl::HasParse<Value, T>,
355 "There is no `Parse(const Value&, formats::parse::To<T>)` in namespace of `T` or `formats::parse`. "
356 "Probably you forgot to include the <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::HasConvert<Value, T>) {
406 return Convert(*this, formats::parse::To<T>{});
407 } else if constexpr (formats::common::impl::HasParse<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 `Parse(const Value&, formats::parse::To<T>)`"
413 "in namespace of `T` or `formats::parse`. Probably you have not provided a `Convert` function overload."
414 );
415 }
416}
417
418template <typename T, typename First, typename... Rest>
419T Value::ConvertTo(First&& default_arg, Rest&&... more_default_args) const {
420 if (IsMissing() || IsNull()) {
421 // NOLINTNEXTLINE(google-readability-casting)
422 return T(std::forward<First>(default_arg), std::forward<Rest>(more_default_args)...);
423 }
424 return ConvertTo<T>();
425}
426
427inline Value Parse(const Value& value, parse::To<Value>) { return value; }
428
429inline Value Parse(Value&& value, parse::To<Value>) { return std::move(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