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
5
6#include <chrono>
7#include <iosfwd>
8#include <string_view>
9#include <type_traits>
10
11#include <userver/compiler/impl/nodebug.hpp>
15#include <userver/formats/json/impl/types.hpp>
19
20USERVER_NAMESPACE_BEGIN
21
22namespace logging {
23class LogHelper;
24} // namespace logging
25
26namespace formats::json {
27namespace impl {
28class InlineObjectBuilder;
29class InlineArrayBuilder;
30class MutableValueWrapper;
31class StringBuffer;
32class StableSerializer;
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
61class Value {
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
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
99 Value operator[](std::string_view key) const;
104 Value operator[](std::size_t index) const;
105
110 const_iterator begin() const;
111
114 const_iterator end() const;
115
118 const_reverse_iterator rbegin() const;
119
122 const_reverse_iterator rend() const;
123
127 bool IsEmpty() const;
128
131 std::size_t GetSize() const;
132
135 bool operator==(const Value& other) const;
136
139 bool IsMissing() const noexcept { return holder_ && !value_ptr_; }
140
142 bool IsNull() const noexcept;
143
145 bool IsBool() const noexcept;
146
148 bool IsInt() const noexcept;
149
151 bool IsInt64() const noexcept;
152
154 bool IsUInt() const noexcept;
155
157 bool IsUInt64() const noexcept;
158
160 bool IsDouble() const noexcept;
161
163 bool IsNumber() const noexcept;
164
166 bool IsString() const noexcept;
167
169 bool IsArray() const noexcept;
170
172 bool IsObject() const noexcept;
173
183 template <typename T>
184 auto As() const;
185
189 template <typename T, typename First, typename... Rest>
190 auto As(First&& default_arg, Rest&&... more_default_args) const;
191
195 template <typename T>
197
200 template <typename T>
201 T ConvertTo() const;
202
205 template <typename T, typename First, typename... Rest>
206 T ConvertTo(First&& default_arg, Rest&&... more_default_args) const;
207
210 bool HasMember(std::string_view key) const;
211
213 std::string GetPath() const;
214
216 void DropRootPath();
218
223 Value Clone() const;
224
226 void CheckNotMissing() const;
227
229 void CheckArrayOrNull() const;
230
232 void CheckObjectOrNull() const;
233
235 void CheckArray() const;
236
238 void CheckObject() const;
239
242
245 void CheckInBounds(std::size_t index) const;
246
248 bool IsRoot() const noexcept;
249
252 bool DebugIsReferencingSameMemory(const Value& other) const { return value_ptr_ == other.value_ptr_; }
253
254private:
255 struct EmplaceEnabler {
256 explicit EmplaceEnabler() = default;
257 };
258
259 class LazyDetachedPath;
260
261public:
263 Value(
264 EmplaceEnabler,
265 const impl::VersionedValuePtr& root,
266 const impl::Value* root_ptr_for_path,
267 const impl::Value* value_ptr,
268 int depth
269 );
270
271 Value(
272 EmplaceEnabler,
273 const impl::VersionedValuePtr& root,
274 impl::Value* root_ptr_for_path,
275 LazyDetachedPath&& lazy_detached_path
276 );
278
279private:
280 explicit Value(impl::VersionedValuePtr root) noexcept;
281
282 bool IsUniqueReference() const;
283 void EnsureNotMissing() const;
284 const impl::Value& GetNative() const;
285 impl::Value& GetNative();
286 impl::Value MoveNativeOrCopy(::rapidjson::CrtAllocator& allocator) &&;
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};
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 friend class impl::StableSerializer;
333
334 friend bool Parse(const Value& value, parse::To<bool>);
335 friend std::int64_t Parse(const Value& value, parse::To<std::int64_t>);
336 friend std::uint64_t Parse(const Value& value, parse::To<std::uint64_t>);
337 friend double Parse(const Value& value, parse::To<double>);
338 friend std::string Parse(const Value& value, parse::To<std::string>);
339
340 friend formats::json::Value FromString(std::string_view);
341 friend formats::json::Value FromStream(std::istream&);
342 friend void Serialize(const formats::json::Value&, std::ostream&);
343 friend std::string ToString(const formats::json::Value&);
344 friend std::string ToStableString(const formats::json::Value&);
346 friend std::string ToPrettyString(const formats::json::Value& doc, PrettyFormat format);
348};
349
350template <typename T>
351USERVER_IMPL_NODEBUG auto Value::As() const {
352 static_assert(
353 formats::common::impl::HasParse<Value, T>,
354 "There is no `Parse(const Value&, formats::parse::To<T>)` in namespace of `T` or `formats::parse`. "
355 "Probably you forgot to include the <userver/formats/parse/common_containers.hpp> or you "
356 "have not provided a `Parse` function overload."
357 );
358
359 return Parse(*this, formats::parse::To<T>{});
360}
361
362bool Parse(const Value& value, parse::To<bool>);
363
364std::int64_t Parse(const Value& value, parse::To<std::int64_t>);
365
366std::uint64_t Parse(const Value& value, parse::To<std::uint64_t>);
367
368double Parse(const Value& value, parse::To<double>);
369
370std::string Parse(const Value& value, parse::To<std::string>);
371
372template <>
373bool Value::ConvertTo<bool>() const;
374
375template <>
376int64_t Value::ConvertTo<int64_t>() const;
377
378template <>
379uint64_t Value::ConvertTo<uint64_t>() const;
380
381template <>
382double Value::ConvertTo<double>() const;
383
384template <>
385std::string Value::ConvertTo<std::string>() const;
386
387template <typename T, typename First, typename... Rest>
388auto Value::As(First&& default_arg, Rest&&... more_default_args) const {
389 if (IsMissing() || IsNull()) {
390 // intended raw ctor call, sometimes casts
391 // NOLINTNEXTLINE(google-readability-casting)
392 return decltype(As<T>())(std::forward<First>(default_arg), std::forward<Rest>(more_default_args)...);
393 }
394 return As<T>();
395}
396
397template <typename T>
399 return (IsMissing() || IsNull()) ? decltype(As<T>())() : As<T>();
400}
401
402template <typename T>
403USERVER_IMPL_NODEBUG T Value::ConvertTo() const {
404 if constexpr (formats::common::impl::HasConvert<Value, T>) {
405 return Convert(*this, formats::parse::To<T>{});
406 } else if constexpr (formats::common::impl::HasParse<Value, T>) {
407 return Parse(*this, formats::parse::To<T>{});
408 } else {
409 static_assert(
410 !sizeof(T),
411 "There is no `Convert(const Value&, formats::parse::To<T>)` or `Parse(const Value&, formats::parse::To<T>)`"
412 "in namespace of `T` or `formats::parse`. 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
428inline Value Parse(Value&& value, parse::To<Value>) { return std::move(value); }
429
430std::chrono::microseconds Parse(const Value& value, parse::To<std::chrono::microseconds>);
431
432std::chrono::milliseconds Parse(const Value& value, parse::To<std::chrono::milliseconds>);
433
434std::chrono::minutes Parse(const Value& value, parse::To<std::chrono::minutes>);
435
436std::chrono::hours Parse(const Value& value, parse::To<std::chrono::hours>);
437
442
444void PrintTo(const Value&, std::ostream*);
445
446} // namespace formats::json
447
451
452json::Value operator""_json(const char* str, std::size_t len);
453
454} // namespace formats::literals
455
456USERVER_NAMESPACE_END