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