JSON Voorhees
Killer JSON for C++
Loading...
Searching...
No Matches
value.hpp
Go to the documentation of this file.
1/// \file jsonv/value.hpp
2///
3/// Copyright (c) 2012-2020 by Travis Gockel. All rights reserved.
4///
5/// This program is free software: you can redistribute it and/or modify it under the terms of the Apache License
6/// as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later
7/// version.
8///
9/// \author Travis Gockel (travis@gockelhut.com)
10#pragma once
11
12#include <jsonv/config.hpp>
13#include <jsonv/kind.hpp>
14#include <string_view>
16
17#include <compare>
18#include <cstddef>
19#include <cstdint>
20#include <initializer_list>
21#include <iosfwd>
22#include <iterator>
23#include <functional>
24#include <stdexcept>
25#include <string>
26#include <type_traits>
27#include <utility>
28
29namespace jsonv
30{
31
32class path;
33class value;
34class object_node_handle;
35
36namespace detail
37{
38
39class object_impl;
40class array_impl;
41class string_impl;
42struct value_access;
43
44union value_storage
45{
46 object_impl* object;
47 array_impl* array;
48 string_impl* string;
49 int64_t integer;
50 double decimal;
51 bool boolean;
52};
53
54/// The longest string a \c value holds in itself rather than in a block of its own.
55inline constexpr std::size_t value_inline_string_capacity = 14U;
56
57/// The \c string_length of a \c kind::string whose text is in a block of its own.
58inline constexpr unsigned char value_string_out_of_line = 0xffU;
59
60/// How a \c value lays out everything but a string short enough to keep in itself.
61struct value_words
62{
64 /// For a \c kind::string, \c value_string_out_of_line; ignored otherwise.
65 unsigned char string_length;
66 value_storage data;
67};
68
69/// How a \c value lays out a string of at most \c value_inline_string_capacity bytes.
70struct value_short_string
71{
73 unsigned char string_length;
74 char text[value_inline_string_capacity];
75};
76
77/// The 16 bytes of a \c value. Both layouts start with the same \c kind and \c string_length, so those can be read
78/// through \c words whichever layout is in use. Both have trivial default constructors, so assigning to either one
79/// makes it the one in use.
80union value_representation
81{
82 value_words words;
83 value_short_string short_string;
84
85 constexpr value_representation() :
86 words{ jsonv::kind::null, 0U, { .object = nullptr } }
87 { }
88};
89
90static_assert(sizeof(value_representation) == 16U, "a value is 16 bytes");
91
92}
93
94/// \defgroup Value
95/// JSON \ref value instances.
96///
97/// The side-effect-free parts of this API -- the predicates, the accessors, the constant lookups and everything which
98/// returns a freshly built \ref value -- are \c JSONV_NODISCARD. Calling one and dropping the result does nothing at
99/// all, so the compiler says so. The accessors which create on demand (non-`const` \ref value::path and
100/// \ref value::operator[] for an object key) and the mutators are deliberately left alone, since discarding those is
101/// how they are normally used.
102/// \{
103
104/// Get a string representation of the given \c value.
106
107/// Thrown from various \c value methods when attempting to perform an operation which is not valid for the \c kind of
108/// value.
110 public std::logic_error
111{
112public:
113 explicit kind_error(const std::string& description);
114
115 virtual ~kind_error() noexcept;
116};
117
118/// Represents a single JSON value, which can be any one of a potential \c kind, each behaving slightly differently.
119/// Instances will vary their behavior based on their kind -- functions will throw a \c kind_error if the operation does
120/// not apply to the value's kind. For example, it does not make sense to call \c find on an \c integer.
121///
122/// - \c kind::null
123/// You cannot do anything with this...it is just null.
124/// - \c kind::boolean
125/// These values can be \c true or \c false.
126/// - \c kind::integer
127/// A numeric value which can be added, subtracted and all the other things you would expect.
128/// - \c kind::decimal
129/// Floating-point values should be considered "more general" than integers -- you may request an integer value as a
130/// decimal, but you cannot request a decimal as an integer, even when doing so would not require rounding. The
131/// literal \c 20.0 will always have \c kind::decimal.
132/// - \c kind::string
133/// A UTF-8 encoded string, read through the \c std::string_view which \c as_string returns. Some random functions
134/// work in the cases where it makes sense (for example: \c empty and \c size), but in general, string manipulation
135/// should be done after calling \c as_string. A string of up to 14 bytes is kept in the \c value itself, and a longer
136/// one in a single allocation of its own.
137/// - \c kind::array
138/// An array behaves like a \c std::vector: its elements are contiguous, growing it may move them all, and inserting
139/// or erasing shifts the elements after the position. Element references are invalidated when \c std::vector's
140/// would be. The elements share one allocation with the array's size and capacity, and an empty array may hold no
141/// allocation at all. If you feel the documentation is lacking, read this:
142/// http://en.cppreference.com/w/cpp/container/vector.
143/// - \c kind::object
144/// An object behaves like a \c std::flat_map: its members are kept sorted by key in one contiguous array, so it
145/// iterates in key order, looking a key up is a binary search, and inserting or erasing shifts the members after
146/// the position and invalidates iterators and references to them. Dereferencing an \c object_iterator gives an
147/// \c object_reference, a proxy like \c std::flat_map::reference. The members share one allocation with the
148/// object's size and capacity, and an empty object may hold no allocation at all. If you feel the documentation is
149/// lacking, read this: http://en.cppreference.com/w/cpp/container/flat_map. This library follows the recommendation in RFC 7159
150/// to not allow for duplicate keys because most other libraries can not deal with it. It would also make the AST
151/// significantly more painful.
152///
153/// \par Nesting depth
154/// Destroying a \c value, clearing it, or move-assigning over one takes any depth of nesting: the tree is taken
155/// apart iteratively, not once per level on the call stack. The operations which walk a whole tree -- copying it,
156/// comparing two, encoding one to text, \c std::hash, and the \c algorithm.hpp walks such as \c traverse,
157/// \c diff, \c map and \c merge -- do recurse, so they cost stack in proportion to the depth of the tree and are
158/// safe to perform on a tree nested tens of thousands deep on a thread with the usual stack, and less than that on
159/// a small one. Parsing cannot build a tree deeper than \c parse_options::k::max_structure_depth, so this is only
160/// reachable for a tree built in code, through the mutators, \c path, or a \c value_encoder.
161///
162/// \see http://json.org/
163/// \see http://tools.ietf.org/html/rfc7159
165{
166public:
167 typedef std::size_t size_type;
168 typedef std::ptrdiff_t difference_type;
169
170 /** The base type for iterating over array values. **/
171 template <typename T, typename TArrayView>
173 {
174 public:
175 using iterator_category = std::random_access_iterator_tag;
176 using value_type = T;
177 using difference_type = std::ptrdiff_t;
178 using pointer = T*;
179 using reference = T&;
181 _owner(0),
182 _index(0)
183 { }
184
185 basic_array_iterator(TArrayView* owner, size_type index) :
186 _owner(owner),
187 _index(index)
188 { }
189
190 template <typename U, typename UArrayView>
192 typename std::enable_if<std::is_convertible<U*, T*>::value>::type* = 0
193 ) :
194 _owner(source._owner),
195 _index(source._index)
196 { }
197
198 basic_array_iterator& operator++()
199 {
200 ++_index;
201 return *this;
202 }
203
204 basic_array_iterator operator++(int)
205 {
206 basic_array_iterator clone = *this;
207 ++*this;
208 return clone;
209 }
210
211 basic_array_iterator& operator--()
212 {
213 --_index;
214 return *this;
215 }
216
217 basic_array_iterator operator--(int)
218 {
219 basic_array_iterator clone = *this;
220 --*this;
221 return clone;
222 }
223
224 template <typename U, typename UArrayView>
226 bool operator==(const basic_array_iterator<U, UArrayView>& other) const
227 {
228 return _owner == other._owner && _index == other._index;
229 }
230
231 template <typename U, typename UArrayView>
233 bool operator!=(const basic_array_iterator<U, UArrayView>& other) const
234 {
235 return !operator==(other);
236 }
237
239 T& operator*() const
240 {
241 return _owner->operator[](_index);
242 }
243
245 T* operator->() const
246 {
247 return &_owner->operator[](_index);
248 }
249
250 basic_array_iterator& operator+=(size_type n)
251 {
252 _index += n;
253 return *this;
254 }
255
257 basic_array_iterator operator+(size_type n) const
258 {
259 basic_array_iterator clone = *this;
260 clone += n;
261 return clone;
262 }
263
264 basic_array_iterator& operator-=(size_type n)
265 {
266 _index -= n;
267 return *this;
268 }
269
271 basic_array_iterator operator-(size_type n) const
272 {
273 basic_array_iterator clone = *this;
274 clone -= n;
275 return clone;
276 }
277
279 difference_type operator-(const basic_array_iterator& other) const
280 {
281 return difference_type(_index) - difference_type(other._index);
282 }
283
285 bool operator<(const basic_array_iterator& rhs) const
286 {
287 return _index < rhs._index;
288 }
289
291 bool operator<=(const basic_array_iterator& rhs) const
292 {
293 return _index <= rhs._index;
294 }
295
297 bool operator>(const basic_array_iterator& rhs) const
298 {
299 return _index > rhs._index;
300 }
301
303 bool operator>=(const basic_array_iterator& rhs) const
304 {
305 return _index >= rhs._index;
306 }
307
309 T& operator[](size_type n) const
310 {
311 return _owner->operator[](_index + n);
312 }
313 private:
314 template <typename U, typename UArrayView>
315 friend struct basic_array_iterator;
316
317 friend class value;
318
319 private:
320 TArrayView* _owner;
321 size_type _index;
322 };
323
324 /** The \c array_iterator is applicable when \c kind is \c kind::array. It allows you to use algorithms as if
325 * a \c value was a normal sequence container.
326 **/
329
330 /** If \c kind is \c kind::array, an \c array_view allows you to access a value as a sequence container. This is
331 * most useful for range-based for loops.
332 **/
333 typedef detail::basic_view<array_iterator, const_array_iterator> array_view;
334 typedef detail::basic_view<const_array_iterator> const_array_view;
335 typedef detail::basic_owning_view<value, array_iterator, const_array_iterator> owning_array_view;
336
337 /** The type of value stored when \c kind is \c kind::object, as an owning pair. Iterating an object does not give
338 * references to this type: members are stored sorted by key in contiguous memory, and an iterator gives an
339 * \ref object_reference instead. Converting one into this type copies the member, so it has to be asked for.
340 **/
341 typedef std::pair<const std::string, value> object_value_type;
342
343 /** What dereferencing an \c object_iterator (\c TValue of \c value) or a \c const_object_iterator
344 * (\c TValue of `const value`) gives: references to the key and value of one member. Like the \c reference of
345 * \c std::flat_map, it is a proxy returned by value, so `auto& m : obj.as_object()` does not compile -- write
346 * `auto&& m`, `const auto& m` or `auto&& [key, val]`. The key is always \c const, since changing it would break
347 * the order members are kept in.
348 *
349 * The conversion to \ref object_value_type is \c explicit because it copies the value. A loop written as
350 * `const value::object_value_type& m : obj.as_object()` -- which before members were stored contiguously bound
351 * straight to the member -- would otherwise still compile and deep-copy every one of them.
352 **/
353 template <typename TValue>
355 {
356 public:
357 /// The type of \ref first, as in \c std::pair, which this stands in for.
358 using first_type = const std::string;
359
360 /// The type of \ref second, as in \c std::pair.
361 using second_type = TValue;
362
363 public:
364 /// The key of the member.
365 const std::string& first;
366
367 /// The value of the member.
368 TValue& second;
369
370 public:
371 /// Refer to \a key and \a val.
372 basic_object_reference(const std::string& key, TValue& val) noexcept :
373 first(key),
374 second(val)
375 { }
376
377 /// Refer to the key and value of \a pair.
378 basic_object_reference(std::conditional_t<std::is_const_v<TValue>, const object_value_type&, object_value_type&>
379 pair
380 ) noexcept :
381 first(pair.first),
382 second(pair.second)
383 { }
384
385 /// This allows conversion from an \c object_reference to a \c const_object_reference.
386 template <typename UValue,
387 typename = std::enable_if_t< !std::is_same_v<UValue, TValue>
388 && std::is_convertible_v<UValue&, TValue&>
389 >
390 >
392 first(source.first),
393 second(source.second)
394 { }
395
396 /// Copy the member into an \ref object_value_type.
397 ///
398 /// \tparam TPair Always \ref object_value_type. It is a parameter so that nothing names that pair until the
399 /// conversion is used: MSVC instantiates a type a template's body names when it reads the body, and here that
400 /// is before \c value is complete.
401 template <typename TPair, typename = std::enable_if_t<std::is_same_v<TPair, object_value_type>>>
403 explicit operator TPair() const
404 {
405 return TPair(first, second);
406 }
407 };
408
409 /** \see basic_object_reference **/
411
412 /** \see basic_object_reference **/
414
415 /** The base iterator type for iterating over object types. It is a random-access iterator over the members of an
416 * object, which are kept sorted by key, and dereferences to a \ref basic_object_reference. Like
417 * \c std::vector<bool>::iterator, it gives \c std::random_access_iterator_tag as its \c iterator_category although
418 * its \c reference is a proxy: the functions which dispatch on the category, like \c std::prev and
419 * \c std::advance, need it to step backward or jump.
420 *
421 * Like the iterators of a \c std::vector, these are invalidated by inserting into or erasing from the object.
422 **/
423 template <typename TValue, typename TMember>
425 {
426 public:
427 /// What this models in C++20 terms: a random-access iterator, whose \c reference may be a proxy.
428 using iterator_concept = std::random_access_iterator_tag;
429
430 /// What this gives the functions which dispatch on the category. \see basic_object_iterator
431 using iterator_category = std::random_access_iterator_tag;
432 using value_type = object_value_type;
433 using difference_type = std::ptrdiff_t;
435
436 /// What \c operator-> returns: it holds the \c reference, so `iter->first` and `iter->second` work.
437 struct pointer
438 {
439 /// The member the iterator was at.
441
442 /// The member the iterator was at, for the built-in \c -> to reach into.
443 const reference* operator->() const noexcept
444 {
445 return &ref;
446 }
447 };
448
449 public:
450 basic_object_iterator() noexcept :
451 _member(nullptr)
452 { }
453
454 /** This allows conversion from an \c object_iterator to a \c const_object_iterator. **/
455 template <typename UValue,
456 typename UMember,
457 typename = std::enable_if_t< !std::is_same_v<UMember, TMember>
458 && std::is_convertible_v<UMember*, TMember*>
459 >
460 >
462 _member(source._member)
463 { }
464
465 basic_object_iterator& operator++() noexcept
466 {
467 ++_member;
468 return *this;
469 }
470
471 basic_object_iterator operator++(int) noexcept
472 {
473 basic_object_iterator clone(*this);
474 ++_member;
475 return clone;
476 }
477
478 basic_object_iterator& operator--() noexcept
479 {
480 --_member;
481 return *this;
482 }
483
484 basic_object_iterator operator--(int) noexcept
485 {
486 basic_object_iterator clone(*this);
487 --_member;
488 return clone;
489 }
490
491 basic_object_iterator& operator+=(difference_type n) noexcept
492 {
493 _member += n;
494 return *this;
495 }
496
497 basic_object_iterator& operator-=(difference_type n) noexcept
498 {
499 _member -= n;
500 return *this;
501 }
502
504 basic_object_iterator operator+(difference_type n) const noexcept
505 {
506 return basic_object_iterator(_member + n);
507 }
508
510 friend basic_object_iterator operator+(difference_type n, const basic_object_iterator& iter) noexcept
511 {
512 return iter + n;
513 }
514
516 basic_object_iterator operator-(difference_type n) const noexcept
517 {
518 return basic_object_iterator(_member - n);
519 }
520
521 template <typename UValue, typename UMember>
523 difference_type operator-(const basic_object_iterator<UValue, UMember>& other) const noexcept
524 {
525 return _member - other._member;
526 }
527
528 template <typename UValue, typename UMember>
530 bool operator==(const basic_object_iterator<UValue, UMember>& other) const noexcept
531 {
532 return _member == other._member;
533 }
534
535 template <typename UValue, typename UMember>
537 auto operator<=>(const basic_object_iterator<UValue, UMember>& other) const noexcept
538 {
539 return _member <=> other._member;
540 }
541
543 reference operator*() const noexcept
544 {
545 return reference(_member->first, _member->second);
546 }
547
549 pointer operator->() const noexcept
550 {
551 return pointer{ **this };
552 }
553
555 reference operator[](difference_type n) const noexcept
556 {
557 return *(*this + n);
558 }
559
560 private:
561 template <typename UValue, typename UMember>
562 friend struct basic_object_iterator;
563
564 friend class value;
565
566 explicit basic_object_iterator(TMember* member) noexcept :
567 _member(member)
568 { }
569
570 private:
571 TMember* _member;
572 };
573
574 /** The \c object_iterator is applicable when \c kind is \c kind::object. It allows you to use algorithms as if
575 * a \c value was a normal associative container.
576 **/
579
580 /** If \c kind is \c kind::object, an \c object_view allows you to access a value as an associative container.
581 * This is most useful for range-based for loops.
582 **/
583 typedef detail::basic_view<object_iterator, const_object_iterator> object_view;
584 typedef detail::basic_view<const_object_iterator> const_object_view;
585 typedef detail::basic_owning_view<value, object_iterator, const_object_iterator> owning_object_view;
586
587 /// Type returned from \c insert operations when this has \ref kind::object. It is generally compatible with the
588 /// \c insert_return_type of \c std::map, with the notable lack of \c node.
589 ///
590 /// \see insert
592 {
593 /// The position of the inserted member or the member with the duplicate key.
595
596 /// Did the insert operation perform an insert? A value of \c false indicates there was a key already present
597 /// with the same name.
599 };
600
601public:
602 /** Default-construct this to null. **/
603 constexpr value() = default;
604
605 /// The nullptr overload will fail to compile -- use \c jsonv::null if you want a \c kind::null.
606 value(std::nullptr_t) = delete;
607
608 /** Copy the contents of \a source into a new instance. **/
609 value(const value& source);
610
611 /** Create a \c kind::string with the given \a value. **/
612 value(const std::string& value);
613
614 /** Create a \c kind::string with the given \a value. **/
615 value(const std::string_view& value);
616
617 /// Create a \c kind::string with the given \a value.
618 ///
619 /// \param value The value to create with. This must be null-terminated.
620 value(const char* value);
621
622 /// Create a \c kind::string with the given \a value. Keep in mind that it will be converted to and stored as a
623 /// UTF-8 encoded string.
624 ///
625 /// \throws std::range_error if \a value is not valid UTF-16, such as when it holds an unpaired surrogate or, where
626 /// \c wchar_t is 32 bits, a code unit above 0xFFFF.
627 value(const std::wstring& value);
628
629 /** Create a \c kind::string with the given \a value. Keep in mind that it will be converted to and stored as a
630 * UTF-8 encoded string.
631 *
632 * \param value The value to create with. This must be null-terminated.
633 * \throws std::range_error if \a value is not valid UTF-16, such as when it holds an unpaired surrogate or, where
634 * \c wchar_t is 32 bits, a code unit above 0xFFFF.
635 **/
636 value(const wchar_t* value);
637
638 /** Create a \c kind::integer with the given \a value. **/
639 value(int64_t value);
640
641 /** Create a \c kind::decimal with the given \a value. **/
642 value(double value);
643
644 /** Create a \c kind::decimal with the given \a value. **/
645 value(float value);
646
647 /** Create a \c kind::boolean with the given \a value. **/
649
650 #define JSONV_VALUE_INTEGER_ALTERNATIVE_CTOR_PROTO_GENERATOR(type_) \
651 value(type_ val);
652 JSONV_INTEGER_ALTERNATES_LIST(JSONV_VALUE_INTEGER_ALTERNATIVE_CTOR_PROTO_GENERATOR)
653 #undef JSONV_VALUE_INTEGER_ALTERNATIVE_CTOR_PROTO_GENERATOR
654
655 /** Destruction will never throw. **/
656 ~value() noexcept;
657
658 /** Copy-assigns \c source to this.
659 *
660 * If an exception is thrown during the copy, it is propagated out. This instance will remain unchanged.
661 **/
662 value& operator=(const value& source);
663
664 /** Move-construct this instance, leaving \a source as a null value. **/
665 value(value&& source) noexcept;
666
667 /** Move-assigns \c source to this, leaving \a source as a null value.
668 *
669 * Unlike a copy, this will never throw.
670 *
671 * \a source may be a descendant of this value (`doc = std::move(doc["data"])`), but this value must not be a
672 * descendant of \a source (`doc.at(0) = std::move(doc)`): the block would end up owning itself and leak. Debug
673 * builds assert that, looking only at the first few hundred values of \a source.
674 **/
675 value& operator=(value&& source) noexcept;
676
677 /** Get this value as a string. The view is into this \c value, so it is good until the value changes or goes away:
678 * `auto text = parse(input).as_string();` leaves \c text referring to a destroyed temporary. Make a
679 * \c std::string from it to keep the text, or to get a NUL-terminated \c c_str.
680 *
681 * \throws kind_error if this value does not represent a string.
682 **/
684 std::string_view as_string() const;
685
686 /** Tests if this \c kind is \c kind::string. **/
688 bool is_string() const;
689
690 /** The same as \c as_string. It is your responsibility to ensure the \c value instance remains valid.
691 *
692 * \throws kind_error if this value does not represent a string.
693 **/
695 std::string_view as_string_view() const &;
696
697 /** Get this value as a wide string. Keep in mind that this is slower than \c as_string, as the text is stored as
698 * UTF-8 and has to be converted. The result is UTF-16 even where \c wchar_t is 32 bits, so a code point outside
699 * the BMP takes a surrogate pair there too.
700 *
701 * \throws kind_error if this value does not represent a string.
702 * \throws std::range_error if the stored string is not valid UTF-8.
703 **/
705 std::wstring as_wstring() const;
706
707 /** Get this value as an integer.
708 *
709 * \throws kind_error if this value does not represent an integer.
710 **/
712 int64_t as_integer() const;
713
714 /** Tests if this \c kind is \c kind::integer. **/
716 bool is_integer() const;
717
718 /** Get this value as a decimal. If the value's underlying kind is actually an integer type, cast the integer to a
719 * double before returning. This ignores the potential loss of precision.
720 *
721 * \throws kind_error if this value does not represent a decimal or integer.
722 **/
724 double as_decimal() const;
725
726 /** Tests if this \c kind is \c kind::integer or \c kind::decimal. **/
728 bool is_decimal() const;
729
730 /** Get this value as a boolean.
731 *
732 * \throws kind_error if this value does not represent a boolean.
733 **/
735 bool as_boolean() const;
736
737 /** Tests if this \c kind is \c kind::boolean. **/
739 bool is_boolean() const;
740
741 /** Tests if this \c kind is \c kind::array. **/
743 bool is_array() const;
744
745 /** Tests if this \c kind is \c kind::object. **/
747 bool is_object() const;
748
749 /** Tests if this \c kind is \c kind::null. **/
751 bool is_null() const;
752
753 /** Resets this value to null. **/
754 void clear();
755
756 /** Get this value's kind. **/
758 inline jsonv::kind kind() const
759 {
760 return _repr.words.kind;
761 }
762
763 /// \{
764
765 /** Get the value specified by the path \a p.
766 *
767 * \throws std::out_of_range if any path along the chain did not exist.
768 * \throws kind_error if the path traversal is not valid for the value (for example: if the path specifies an array
769 * index when the value is a string).
770 * \throws std::invalid_argument if a \c std::string_view was specified that did not have a valid specification
771 * (see \c path::create).
772 **/
773 value& at_path(const path& p);
774 value& at_path(std::string_view p);
775 value& at_path(size_type p);
777 const value& at_path(const path& p) const;
779 const value& at_path(std::string_view p) const;
781 const value& at_path(size_type p) const;
782 /// \}
783
784 /// \{
785
786 /** Similar to \c count, but walks the given path \a p to determine its presence.
787 *
788 * \returns \c 1 if the path finds an element; \c 0 if there is no such path in the tree.
789 *
790 * \throws std::invalid_argument if a \c std::string_view was specified that did not have a valid specification
791 * (see \c path::create).
792 **/
794 size_type count_path(const path& p) const;
796 size_type count_path(std::string_view p) const;
798 size_type count_path(size_type p) const;
799 /// \}
800
801 /// \{
802
803 /** Get or create the value specified by the path \a p. This is the moral equivalent to \c operator[] for paths. If
804 * no value exists at the path, a new one is created as the default (\c null) value. If any path along the way
805 * either does not exist or is \c null, it is created for you, based on the \e implications of the specification
806 * \a p. Unlike \c at_path, which will throw if accessing a non-existent key of an \c object or going past the end
807 * of an \c array, this will simply create that path and fill in the blanks with \c null values.
808 *
809 * \throws kind_error if the path traversal is not valid for the value (for example: if the path specifies an array
810 * index when the value is a string).
811 * \throws std::invalid_argument if a \c std::string_view was specified that did not have a valid specification
812 * (see \c path::create).
813 * \throws std::length_error if the path has an array index which no array can hold, such as the largest
814 * \c std::size_t.
815 * \throws std::bad_alloc if there is not enough memory to create what the path needs.
816 *
817 * If this throws, for any reason, \c *this is left as it was. What the path needs is built apart from the tree and
818 * added to it in a single step at the end, so there is no partial result: a \c null does not become \c [] and a
819 * key on the way to the failing index is not created. A path which already exists is only followed, with nothing
820 * allocated.
821 *
822 * \see at_path
823 **/
824 value& path(const path& p);
825 value& path(std::string_view p);
826 value& path(size_type p);
827 /// \}
828
829 /** Swap the value this instance represents with \a other. **/
830 void swap(value& other) noexcept;
831
832 /** Compares two JSON values for equality. Two JSON values are equal if and only if all of the following conditions
833 * apply:
834 *
835 * 1. They have the same valid value for \c kind, where \c kind::integer and \c kind::decimal count as the same.
836 * - If \c kind is invalid (memory corruption), then two JSON values are \e not equal, even if they have been
837 * corrupted in the same way and even if they share \c this (a corrupt object is not equal to itself).
838 * 2. The kind comparison is also equal:
839 * - Two null values are always equivalent.
840 * - string, integer and boolean follow the classic rules for their type.
841 * - decimals compare exactly, with signed zeros equal and all NaNs equal (see \c compare).
842 * - an integer and a decimal are equal only when the decimal holds exactly that integer (see \c compare).
843 * - objects are equal if they have the same keys and values corresponding with the same key are also equal.
844 * - arrays are equal if they have the same length and the values at each index are also equal.
845 *
846 * \note
847 * The rules for equality are based on Python \c dict and \c list.
848 **/
850 bool operator==(const value& other) const;
851
852 /** Compares two JSON values for inequality. The rules for inequality are the exact opposite of equality.
853 **/
855 bool operator!=(const value& other) const;
856
857 /** Used to build a strict-ordering of JSON values. When comparing values of the same kind, the ordering should
858 * align with your intuition. When comparing values of different kinds, some arbitrary rules were created based on
859 * how "complicated" the author thought the type to be.
860 *
861 * - null: less than everything but null, which it is equal to.
862 * - boolean: false is less than true.
863 * - integer, decimal: compared by their exact numeric value. An integer is never converted to a decimal to
864 * compare it with one, so \c 9007199254740993 is greater than the decimal \c 9007199254740992.0 even though
865 * converting it would round to that decimal. Decimal comparison is exact, without an epsilon tolerance. Signed
866 * zeros compare equal to each other and to the integer \c 0; infinities follow numeric order. All NaNs compare
867 * equal to each other and greater than every other number, regardless of sign or payload.
868 * - string: compared lexicographically by character code (with basic char strings and non-ASCII encoding, this
869 * might lead to surprising results)
870 * - array: compared lexicographically by elements (recursively following this same technique)
871 * - object: entries in the object are sorted and compared lexicographically, first by key then by value
872 *
873 * \returns A negative number if this is less than other by the rules stated above; 0 if this is equal to other; a
874 * positive number otherwise. Only the sign is meaningful: strings and object keys pass on the result of
875 * \c std::string::compare, which need not be -1 or 1.
876 **/
878 int compare(const value& other) const;
879
881 bool operator< (const value& other) const;
883 bool operator> (const value& other) const;
885 bool operator<=(const value& other) const;
887 bool operator>=(const value& other) const;
888
889 /// Output this value to a stream, through an \c ostream_encoder. The stream's format flags, width, fill and locale
890 /// do not change the text written.
891 friend std::ostream& operator<<(std::ostream& stream, const value& val);
892
893 /// Get a string representation of the given \c value.
894 friend std::string to_string(const value&);
895
896 /// \{
897
898 /// Get an iterator to the beginning of this array.
899 ///
900 /// \throws kind_error if the kind is not an array.
905 /// \}
906
907 /// \{
908
909 /// Get an iterator to the end of this array.
910 ///
911 /// \throws kind_error if the kind is not an array.
916 /// \}
917
918 /// \{
919
920 /// View this instance as an array.
921 ///
922 /// \throws kind_error if the kind is not an array.
926 const_array_view as_array() const &;
928 owning_array_view as_array() &&;
929 /// \}
930
931 /// \{
932
933 /// Get the value in this array at the given \a idx. The overloads which accept an \c int are required to resolve
934 /// the type ambiguity of the literal \c 0 between a size_type and a char*.
935 ///
936 /// \throws kind_error if the kind is not an array.
937 value& operator[](size_type idx);
939 const value& operator[](size_type idx) const;
940 inline value& operator[](int idx) { return operator[](size_type(idx)); }
942 inline const value& operator[](int idx) const { return operator[](size_type(idx)); }
943 /// \}
944
945 /// \{
946
947 /// Get the value in this array at the given \a idx.
948 ///
949 /// \throws kind_error if the kind is not an array.
950 /// \throws std::out_of_range if the provided \a idx is above \c size.
951 ///
952 value& at(size_type idx);
954 const value& at(size_type idx) const;
955 /// \}
956
957 /// \{
958
959 /// Push \a item to the back of this array.
960 ///
961 /// \throws kind_error if the kind is not an array.
962 void push_back(value&& item);
963 void push_back(const value& item);
964 /// \}
965
966 /// Pop an item off the back of this array.
967 ///
968 /// \throws kind_error if the kind is not an array.
969 /// \throws std::logic_error if the array is empty.
970 void pop_back();
971
972 /// Insert an item into \a position on this array.
973 ///
974 /// \throws kind_error if the kind is not an array.
976
977 /// Insert the range defined by [\a first, \a last) at \a position in this array.
978 ///
979 /// \throws kind_error if the kind is not an array.
980 template <typename TForwardIterator>
981 array_iterator insert(const_array_iterator position, TForwardIterator first, TForwardIterator last)
982 {
983 difference_type orig_offset = std::distance(const_array_iterator(begin_array()), position);
984
985 for (difference_type offset = orig_offset ; first != last; ++first, ++offset)
986 insert(begin_array() + offset, *first);
987 return begin_array() + orig_offset;
988 }
989
990 /// Assign \a count elements to this array with \a val.
991 ///
992 /// \throws kind_error if the kind is not an array.
993 void assign(size_type count, const value& val);
994
995 /// Assign the contents of range [\a first, \a last) to this array.
996 ///
997 /// \throws kind_error if the kind is not an array.
998 template <typename TForwardIterator>
999 void assign(TForwardIterator first, TForwardIterator last)
1000 {
1001 resize(std::distance(first, last), value());
1002 auto iter = begin_array();
1003 while (first != last)
1004 {
1005 *iter = *first;
1006 ++iter;
1007 ++first;
1008 }
1009 }
1010
1011 /// Assign the given \a items to this array.
1012 ///
1013 /// \throws kind_error if the kind is not an array.
1014 void assign(std::initializer_list<value> items);
1015
1016 /// Reserve at least \a count elements in the array.
1017 ///
1018 /// \throws kind_error if the kind is not an array.
1019 void reserve(size_type count);
1020
1021 /// Resize the length of this array to \a count items. If the resize creates new elements, fill those newly-created
1022 /// elements with \a val.
1023 ///
1024 /// \throws kind_error if the kind is not an array.
1025 void resize(size_type count, const value& val = value());
1026
1027 /// Erase the item at this array's \a position.
1028 ///
1029 /// \throws kind_error if the kind is not an array.
1031
1032 /// Erase the range [\a first, \a last) from this array.
1033 ///
1034 /// \throws kind_error if the kind is not an array.
1036
1037 /// \{
1038
1039 /** Get an iterator to the first key-value pair in this object.
1040 *
1041 * \throws kind_error if the kind is not an object.
1042 **/
1047 /// \}
1048
1049 /// \{
1050
1051 /** Get an iterator to the one past the end of this object.
1052 *
1053 * \throws kind_error if the kind is not an object.
1054 **/
1059 /// \}
1060
1061 /// \{
1062
1063 /** View this instance as an object.
1064 *
1065 * \throws kind_error if the kind is not an object.
1066 **/
1070 const_object_view as_object() const &;
1072 owning_object_view as_object() &&;
1073 /// \}
1074
1075 /// \{
1076
1077 /** Get the value associated with the given \a key of this object. If the \a key does not exist, it will be created.
1078 * Creating it invalidates iterators and references as \ref insert does.
1079 *
1080 * \throws kind_error if the kind is not an object.
1081 **/
1082 value& operator[](const std::string& key);
1083 value& operator[](std::string&& key);
1084 value& operator[](const std::wstring& key);
1085 /// \}
1086
1087 /// \{
1088
1089 /** Get the value associated with the given \a key of this object.
1090 *
1091 * \throws kind_error if the kind is not an object.
1092 * \throws std::out_of_range if the \a key is not in this object.
1093 **/
1094 value& at(const std::string& key);
1095 value& at(const std::wstring& key);
1097 const value& at(const std::string& key) const;
1099 const value& at(const std::wstring& key) const;
1100 /// \}
1101
1102 /// \{
1103
1104 /** Check if the given \a key exists in this object.
1105 *
1106 * \throws kind_error if the kind is not an object.
1107 **/
1109 size_type count(const std::string& key) const;
1111 size_type count(const std::wstring& key) const;
1112 /// \}
1113
1114 /// \{
1115
1116 /** Attempt to locate a key-value pair with the provided \a key in this object.
1117 *
1118 * \throws kind_error if the kind is not an object.
1119 **/
1121 object_iterator find(const std::string& key);
1123 object_iterator find(const std::wstring& key);
1125 const_object_iterator find(const std::string& key) const;
1127 const_object_iterator find(const std::wstring& key) const;
1128 /// \}
1129
1130 /// \{
1131
1132 /// Insert \a pair into this object, unless an element with an equivalent key is already present.
1133 ///
1134 /// Inserting invalidates every iterator and reference to a member at or after the position inserted at, and every
1135 /// one of them if the object has to grow.
1136 ///
1137 /// \returns A pair whose \c first refers to the newly-inserted element (or the element which shares the key) and
1138 /// whose \c second is \c true if the insertion took place.
1139 /// \throws kind_error if the kind is not an object.
1140 std::pair<object_iterator, bool> insert(std::pair<std::string, value> pair);
1141 std::pair<object_iterator, bool> insert(std::pair<std::wstring, value> pair);
1142 /// \}
1143
1144 /// \{
1145
1146 /// Insert \a pair into this object, unless an element with an equivalent key is already present. If \a hint is
1147 /// where the key goes -- every member before it has a lesser key and \a hint itself a greater one -- the key is not
1148 /// searched for. A \a hint of \ref end_object for a key greater than every one present appends in amortized
1149 /// constant time; any other insertion shifts the members after it. A wrong \a hint costs a binary search.
1150 ///
1151 /// Inserting invalidates every iterator and reference to a member at or after the position inserted at, and every
1152 /// one of them if the object has to grow.
1153 ///
1154 /// \returns An iterator to the newly-inserted element (or the element which shares the key).
1155 /// \throws kind_error if the kind is not an object.
1156 object_iterator insert(const_object_iterator hint, std::pair<std::string, value> pair);
1157 object_iterator insert(const_object_iterator hint, std::pair<std::wstring, value> pair);
1158 /// \}
1159
1160 /// Insert range defined by [\a first, \a last) into this object. Each element is hinted just past the previous one,
1161 /// so a source in ascending key order needs no searching, and one whose keys all sort after what this object holds
1162 /// is appended in amortized constant time per element. Any element which does not go at the end shifts the
1163 /// members after it.
1164 ///
1165 /// Inserting invalidates every iterator and reference to a member at or after the position inserted at, and every
1166 /// one of them if the object has to grow.
1167 ///
1168 /// \throws kind_error if the kind is not an object.
1169 template <typename TForwardIterator>
1170 void insert(TForwardIterator first, TForwardIterator last)
1171 {
1172 // Each element is hinted just past the one before it, which is right for any ascending source -- most
1173 // importantly one building a fresh object, where that is the end. Reading end_object() also rejects a
1174 // non-object when the range is empty.
1175 const_object_iterator hint = end_object();
1176 for ( ; first != last; ++first)
1177 hint = insert(hint, *first) + 1;
1178 }
1179
1180 /// Insert the contents of \a handle. If \a handle is empty, this does nothing. If the insertion succeeds, \a handle
1181 /// is moved from and left empty; otherwise it retains ownership of the element.
1182 ///
1183 /// Inserting invalidates every iterator and reference to a member at or after the position inserted at, and every
1184 /// one of them if the object has to grow.
1185 ///
1186 /// \returns If \a handle is empty, \c inserted is \c false and \c position is `end_object()`. If the insertion took
1187 /// place, \c inserted is \c true and \c position points to the inserted element. If the insertion was attempted
1188 /// but failed, \c inserted is \c false and \c position points to an element with a key equivalent to
1189 /// `handle.key()`.
1190 /// \throws kind_error if the kind is not an object.
1192
1193 /// If \a handle is an empty node handle, does nothing and returns \ref end_object. Otherwise, inserts the element
1194 /// owned by \a handle into the container, if the container doesn't already contain an element with a key equivalent
1195 /// to `handle.key()` and returns the iterator pointing to the element with key equivalent to `handle.key()`. If the
1196 /// insertion succeeds, \a handle is moved from, otherwise it retains ownership of the element. \a hint works as it
1197 /// does for \ref insert of a pair.
1198 ///
1199 /// Inserting invalidates every iterator and reference to a member at or after the position inserted at, and every
1200 /// one of them if the object has to grow.
1201 ///
1202 /// \returns An iterator pointing to an element with a key equivalent to `handle.key()` if \a handle was not empty.
1203 /// If \a handle was empty, `end_object()`.
1204 /// \throws kind_error if the kind is not an object.
1206
1207 /// \{
1208
1209 /// Insert \a items into this object.
1210 ///
1211 /// Inserting invalidates every iterator and reference to a member at or after the position inserted at, and every
1212 /// one of them if the object has to grow.
1213 ///
1214 /// \throws kind_error if the kind is not an object.
1215 void insert(std::initializer_list<std::pair<std::string, value>> items);
1216 void insert(std::initializer_list<std::pair<std::wstring, value>> items);
1217 /// \}
1218
1219 /// \{
1220
1221 /// Construct an element from \a key and \a val and insert it into this object. If an element with an equivalent
1222 /// key is already present, the insertion does not happen and the existing element is not overwritten.
1223 ///
1224 /// \note
1225 /// \a key is taken by value, so a call which does not insert has still built and destroyed it. Prefer
1226 /// \ref try_emplace when collisions are expected.
1227 ///
1228 /// Inserting invalidates every iterator and reference to a member at or after the position inserted at, and every
1229 /// one of them if the object has to grow.
1230 ///
1231 /// \returns A pair whose \c first refers to the newly-inserted element (or the element which shares the key) and
1232 /// whose \c second is \c true if the insertion took place.
1233 /// \throws kind_error if the kind is not an object.
1234 ///
1235 /// \see insert
1236 /// \see try_emplace
1237 std::pair<object_iterator, bool> emplace(std::string key, value val);
1238 std::pair<object_iterator, bool> emplace(const std::wstring& key, value val);
1239 /// \}
1240
1241 /// \{
1242
1243 /// Insert \a val with the given \a key into this object, but only if no element with an equivalent key is already
1244 /// present. Unlike \ref emplace, \a key is not copied when the key is already present.
1245 ///
1246 /// \note
1247 /// \a val is taken by value, so a caller who passes `std::move(x)` has moved from \c x by the time this function
1248 /// is entered whether or not the insertion happens. It is the key which is spared, not \a val.
1249 ///
1250 /// Inserting invalidates every iterator and reference to a member at or after the position inserted at, and every
1251 /// one of them if the object has to grow.
1252 ///
1253 /// \returns A pair whose \c first refers to the newly-inserted element (or the element which shares the key) and
1254 /// whose \c second is \c true if the insertion took place.
1255 /// \throws kind_error if the kind is not an object.
1256 ///
1257 /// \see insert
1258 /// \see insert_or_assign
1259 std::pair<object_iterator, bool> try_emplace(const std::string& key, value val);
1260 std::pair<object_iterator, bool> try_emplace(const std::wstring& key, value val);
1261 /// \}
1262
1263 /// \{
1264
1265 /// Insert \a val with the given \a key into this object if no element with an equivalent key is present;
1266 /// otherwise, assign \a val to the existing element. Unlike \ref try_emplace, \a val is stored either way.
1267 ///
1268 /// \returns A pair whose \c first refers to the inserted or assigned element and whose \c second is \c true if an
1269 /// insertion took place and \c false if an assignment took place. Unlike \ref insert, a \c second of \c false
1270 /// does \e not mean the operation failed -- this function always modifies the object.
1271 /// \throws kind_error if the kind is not an object.
1272 ///
1273 /// An insertion invalidates iterators and references as \ref insert does; an assignment invalidates none.
1274 ///
1275 /// \see insert
1276 /// \see try_emplace
1277 std::pair<object_iterator, bool> insert_or_assign(const std::string& key, value val);
1278 std::pair<object_iterator, bool> insert_or_assign(const std::wstring& key, value val);
1279 /// \}
1280
1281 /// \{
1282
1283 /// Erase the item with the given \a key.
1284 ///
1285 /// Erasing invalidates every iterator and reference to a member at or after the position erased from.
1286 ///
1287 /// \returns 1 if \a key was erased; 0 if it did not.
1288 /// \throws kind_error if the kind is not an object.
1289 size_type erase(const std::string& key);
1290 size_type erase(const std::wstring& key);
1291 /// \}
1292
1293 /// Erase the item at the given \a position.
1294 ///
1295 /// Erasing invalidates every iterator and reference to a member at or after the position erased from.
1296 ///
1297 /// \returns An iterator to the member which followed the erased one.
1298 /// \throws kind_error if the kind is not an object.
1300
1301 /// Erase the range defined by [\a first, \a last).
1302 ///
1303 /// Erasing invalidates every iterator and reference to a member at or after the position erased from.
1304 ///
1305 /// \returns An iterator to the member which followed the erased range.
1306 /// \throws kind_error if the kind is not an object.
1308
1309 /// Move the key and value of the member at \a position into a node handle, erase the member, and return the handle.
1310 ///
1311 /// Erasing invalidates every iterator and reference to a member at or after the position erased from.
1312 ///
1313 /// \throws kind_error if the kind is not an object.
1315
1316 /// \{
1317
1318 /// If the container has an element with the given \a key, moves its key and value into a node handle, erases it,
1319 /// and returns the handle. Otherwise, returns an empty node handle.
1320 ///
1321 /// Erasing invalidates every iterator and reference to a member at or after the position erased from.
1322 ///
1323 /// \throws kind_error if the kind is not an object.
1324 object_node_handle extract(const std::string& key);
1325 object_node_handle extract(const std::wstring& key);
1326 /// \}
1327
1328 /** Is the underlying structure empty?
1329 *
1330 * - object: Are there no keys?
1331 * - array: Are there no values?
1332 * - string: Is the string 0 length?
1333 * - null: true (always)
1334 * - all other types: false (always)
1335 *
1336 * \throws nothing
1337 **/
1339 bool empty() const noexcept;
1340
1341 /** Get the number of items in this value.
1342 *
1343 * - object: The number of key/value pairs.
1344 * - array: The number of values.
1345 * - string: The number of code points in the string (including \c \\0 values and counting multi-byte encodings as
1346 * more than one value).
1347 *
1348 * \throws kind_error if the kind is not an object, array or string.
1349 **/
1351 size_type size() const;
1352
1353 /** \addtogroup Algorithm
1354 * \{
1355 **/
1356
1357 /** Run a function over the values of this instance. The behavior of this function is different, depending on the
1358 * \c kind. For scalar kinds (\c kind::integer, \c kind::null, etc), \a func is called once with the value. If this
1359 * is \c kind::array, \c func is called for every value in the array and the output will be an array with each
1360 * element transformed by \a func. If this is \c kind::object, the result will be an object with each key
1361 * transformed by \a func.
1362 *
1363 * \param func The function to apply to the element or elements of this instance.
1364 **/
1366 value map(const std::function<value (const value&)>& func) const&;
1367
1368 /** Run a function over the values of this instance. The behavior of this function is different, depending on the
1369 * \c kind. For scalar kinds (\c kind::integer, \c kind::null, etc), \a func is called once with the value. If this
1370 * is \c kind::array, \c func is called for every value in the array and the output will be an array with each
1371 * element transformed by \a func. If this is \c kind::object, the result will be an object with each key
1372 * transformed by \a func.
1373 *
1374 * \param func The function to apply to the element or elements of this instance.
1375 *
1376 * \note
1377 * This version of \c map provides only a basic exception-safety guarantee. If an exception is thrown while
1378 * transforming a non-scalar \c kind, there is no rollback action, so \c this is left in a usable, but
1379 * \e unpredictable state. If you need a strong exception guarantee, use the constant reference version of \c map.
1380 **/
1382 value map(const std::function<value (value)>& func) &&;
1383
1384 /** \} **/
1385
1386private:
1387 friend JSONV_PUBLIC value array();
1388 friend JSONV_PUBLIC value object();
1389 friend struct detail::value_access;
1390
1391private:
1392 detail::value_representation _repr;
1393};
1394
1395/** An instance with \c kind::null. This is intended to be used for convenience and readability (as opposed to using the
1396 * default constructor of \c value.
1397**/
1398JSONV_PUBLIC extern const value null;
1399
1400/** A user-defined literal for parsing JSON. Uses the default (non-strict) \c parse_options.
1401 *
1402 * \code
1403 * R"({
1404 * "taco": "cat",
1405 * "burrito": "dog",
1406 * "whatever": [ "goes", "here", 1, 2, 3, 4 ]
1407 * })"_json;
1408 * \endcode
1409**/
1410JSONV_NODISCARD JSONV_PUBLIC value operator""_json(const char* str, std::size_t len);
1411
1412/** Swap the values \a a and \a b. **/
1413JSONV_PUBLIC void swap(value& a, value& b) noexcept;
1414
1415/** Create an empty array value. **/
1417
1418/** Create an array value from the given source. **/
1419JSONV_NODISCARD JSONV_PUBLIC value array(std::initializer_list<value> source);
1420
1421/** Create an array with contents defined by range [\a first, \a last). **/
1422template <typename TForwardIterator>
1423value array(TForwardIterator first, TForwardIterator last)
1424{
1425 value arr = array();
1426 arr.assign(first, last);
1427 return arr;
1428}
1429
1430/** Create an empty object. **/
1432
1433/** Create an object with key-value pairs from the given \a source. **/
1434JSONV_NODISCARD JSONV_PUBLIC value object(std::initializer_list<std::pair<std::string, value>> source);
1435JSONV_NODISCARD JSONV_PUBLIC value object(std::initializer_list<std::pair<std::wstring, value>> source);
1436
1437/** Create an object whose contents are defined by range [\a first, \a last). **/
1438template <typename TForwardIterator>
1439value object(TForwardIterator first, TForwardIterator last)
1440{
1441 value obj = object();
1442 obj.insert(first, last);
1443 return obj;
1444}
1445
1446/// A <a href="http://en.cppreference.com/w/cpp/container/node_handle">node handle</a> used when a value is
1447/// \ref kind::object to access elements of the object in potentially destructive manner. This makes it possible to
1448/// modify the contents of a node extracted from an object, and then re-insert it without having to copy the element.
1450{
1451public:
1452 /// The key type of the object.
1453 using key_type = std::string;
1454
1455 /// The mapped type of the object.
1457
1458public:
1459 explicit object_node_handle() noexcept :
1460 _has_value(false)
1461 { }
1462
1463 /// Take over the element owned by \a src, if any. \a src is left \ref empty.
1465
1466 /// Release the element this handle owns, if any, and take over the one owned by \a src, if any. \a src is left
1467 /// \ref empty. Self-assignment has no effect.
1469
1470 ~object_node_handle() noexcept;
1471
1472 /// \returns \c true if the node handle is empty; \c false if otherwise.
1474 bool empty() const noexcept { return !_has_value; }
1475
1476 /// \returns \c false if the node handle is empty; \c true if otherwise.
1478 explicit operator bool() const noexcept { return _has_value; }
1479
1480 /// Returns a non-const reference to the \ref key_type member of the element.
1481 ///
1482 /// \throws std::invalid_argument if the node handle is \ref empty.
1483 key_type& key() const;
1484
1485 /// Returns a non-const reference to the \ref mapped_type member of the element.
1486 ///
1487 /// \throws std::invalid_argument if the node handle is \ref empty.
1489
1490private:
1491 enum class purposeful_construction
1492 { };
1493
1494 explicit object_node_handle(purposeful_construction, key_type, mapped_type) noexcept;
1495
1496 friend class value;
1497
1498private:
1499 bool _has_value;
1500 mutable key_type _key;
1501 mutable mapped_type _value;
1502};
1503
1504/// \}
1505
1506}
1507
1508namespace std
1509{
1510
1511/// Explicit specialization of \c std::hash for \c jsonv::value types so you can store a \c value in an unordered
1512/// container. Values which compare equal hash equal. Since an integer compares equal to the decimal of the same number,
1513/// both \c kind::integer and \c kind::decimal hash through \c value::as_decimal: \c value(2) and \c value(2.0) share a
1514/// hash, as do distinct integers past 2^53 which convert to the same \c double. All NaNs share a hash. For aggregate
1515/// kinds \c array and \c object, hashing visits every sub-element recursively. This might be expensive, but is required
1516/// when storing multiple values with similar layouts in a set (which is the most common use case).
1517template <>
1518struct JSONV_PUBLIC hash<jsonv::value>
1519{
1521 std::size_t operator()(const jsonv::value& val) const noexcept;
1522};
1523
1524/// A member reference and an owning member have \c jsonv::value::const_object_reference in common: both convert to it.
1525/// This is what makes the object iterators, whose \c reference is a proxy, model \c std::random_access_iterator.
1526template <typename TValue, template <typename> class TQual, template <typename> class UQual>
1527struct basic_common_reference<jsonv::value::basic_object_reference<TValue>,
1529 TQual,
1530 UQual
1531 >
1532{
1534};
1535
1536/// The same, with the arguments the other way around.
1537template <typename TValue, template <typename> class TQual, template <typename> class UQual>
1538struct basic_common_reference<jsonv::value::object_value_type,
1540 TQual,
1541 UQual
1542 >
1543{
1545};
1546
1547}
Copyright (c) 2014-2020 by Travis Gockel.
Thrown from various value methods when attempting to perform an operation which is not valid for the ...
Definition value.hpp:111
A node handle used when a value is kind::object to access elements of the object in potentially destr...
Definition value.hpp:1450
object_node_handle & operator=(object_node_handle &&src) noexcept
Release the element this handle owns, if any, and take over the one owned by src, if any.
key_type & key() const
Returns a non-const reference to the key_type member of the element.
mapped_type & mapped() const
Returns a non-const reference to the mapped_type member of the element.
std::string key_type
The key type of the object.
Definition value.hpp:1453
object_node_handle(object_node_handle &&src) noexcept
Take over the element owned by src, if any. src is left empty.
Represents an exact path in some JSON structure.
Definition path.hpp:107
Represents a single JSON value, which can be any one of a potential kind, each behaving slightly diff...
Definition value.hpp:165
void assign(TForwardIterator first, TForwardIterator last)
Assign the contents of range [first, last) to this array.
Definition value.hpp:999
const value & at_path(std::string_view p) const
Get the value specified by the path p.
value(const std::string_view &value)
Create a kind::string with the given value.
void insert(std::initializer_list< std::pair< std::wstring, value > > items)
Insert items into this object.
value(std::nullptr_t)=delete
The nullptr overload will fail to compile – use jsonv::null if you want a kind::null.
std::pair< object_iterator, bool > emplace(const std::wstring &key, value val)
Construct an element from key and val and insert it into this object.
array_iterator erase(const_array_iterator first, const_array_iterator last)
Erase the range [first, last) from this array.
value(float value)
Create a kind::decimal with the given value.
value & at_path(const path &p)
Get the value specified by the path p.
const value & at_path(size_type p) const
Get the value specified by the path p.
value & path(const path &p)
Get or create the value specified by the path p.
friend std::ostream & operator<<(std::ostream &stream, const value &val)
Output this value to a stream, through an ostream_encoder.
const_object_iterator end_object() const
Get an iterator to the one past the end of this object.
std::pair< object_iterator, bool > try_emplace(const std::wstring &key, value val)
Insert val with the given key into this object, but only if no element with an equivalent key is alre...
value & at_path(std::string_view p)
Get the value specified by the path p.
void assign(size_type count, const value &val)
Assign count elements to this array with val.
object_iterator erase(const_object_iterator position)
Erase the item at the given position.
value & at_path(size_type p)
Get the value specified by the path p.
const value & at_path(const path &p) const
Get the value specified by the path p.
size_type count_path(const path &p) const
Similar to count, but walks the given path p to determine its presence.
bool operator!=(const value &other) const
Compares two JSON values for inequality.
detail::basic_view< object_iterator, const_object_iterator > object_view
If kind is kind::object, an object_view allows you to access a value as an associative container.
Definition value.hpp:583
basic_object_reference< const value > const_object_reference
Definition value.hpp:413
array_view as_array() &
View this instance as an array.
object_iterator end_object()
Get an iterator to the one past the end of this object.
const value & operator[](int idx) const
Get the value in this array at the given idx.
Definition value.hpp:942
int compare(const value &other) const
Used to build a strict-ordering of JSON values.
object_node_handle extract(const_object_iterator position)
Move the key and value of the member at position into a node handle, erase the member,...
size_type count_path(std::string_view p) const
Similar to count, but walks the given path p to determine its presence.
void push_back(const value &item)
Push item to the back of this array.
const_object_iterator begin_object() const
Get an iterator to the first key-value pair in this object.
detail::basic_view< array_iterator, const_array_iterator > array_view
If kind is kind::array, an array_view allows you to access a value as a sequence container.
Definition value.hpp:333
object_node_handle extract(const std::string &key)
If the container has an element with the given key, moves its key and value into a node handle,...
size_type count_path(size_type p) const
Similar to count, but walks the given path p to determine its presence.
value(const wchar_t *value)
Create a kind::string with the given value.
constexpr value()=default
Default-construct this to null.
const_array_iterator begin_array() const
Get an iterator to the beginning of this array.
object_insert_return_type insert(object_node_handle &&handle)
Insert the contents of handle.
std::pair< object_iterator, bool > try_emplace(const std::string &key, value val)
Insert val with the given key into this object, but only if no element with an equivalent key is alre...
object_iterator insert(const_object_iterator hint, object_node_handle &&handle)
If handle is an empty node handle, does nothing and returns end_object.
array_iterator erase(const_array_iterator position)
Erase the item at this array's position.
std::pair< object_iterator, bool > insert_or_assign(const std::wstring &key, value val)
Insert val with the given key into this object if no element with an equivalent key is present; other...
basic_object_reference< value > object_reference
Definition value.hpp:410
bool operator==(const value &other) const
Compares two JSON values for equality.
array_iterator insert(const_array_iterator position, TForwardIterator first, TForwardIterator last)
Insert the range defined by [first, last) at position in this array.
Definition value.hpp:981
friend JSONV_PUBLIC value object()
Create an empty object.
void push_back(value &&item)
Push item to the back of this array.
basic_object_iterator< value, std::pair< std::string, value > > object_iterator
The object_iterator is applicable when kind is kind::object.
Definition value.hpp:577
void resize(size_type count, const value &val=value())
Resize the length of this array to count items.
value & at(size_type idx)
Get the value in this array at the given idx.
std::pair< object_iterator, bool > emplace(std::string key, value val)
Construct an element from key and val and insert it into this object.
value(const std::wstring &value)
Create a kind::string with the given value.
const value & at(size_type idx) const
Get the value in this array at the given idx.
const_array_iterator end_array() const
Get an iterator to the end of this array.
value(bool value)
Create a kind::boolean with the given value.
basic_array_iterator< value, value > array_iterator
The array_iterator is applicable when kind is kind::array.
Definition value.hpp:327
~value() noexcept
Destruction will never throw.
value(const value &source)
Copy the contents of source into a new instance.
std::pair< object_iterator, bool > insert_or_assign(const std::string &key, value val)
Insert val with the given key into this object if no element with an equivalent key is present; other...
std::pair< const std::string, value > object_value_type
The type of value stored when kind is kind::object, as an owning pair.
Definition value.hpp:341
size_type erase(const std::wstring &key)
Erase the item with the given key.
const_object_iterator position
The position of the inserted member or the member with the duplicate key.
Definition value.hpp:594
value(const std::string &value)
Create a kind::string with the given value.
void swap(value &other) noexcept
Swap the value this instance represents with other.
object_iterator begin_object()
Get an iterator to the first key-value pair in this object.
value & operator[](int idx)
Get the value in this array at the given idx.
Definition value.hpp:940
void insert(std::initializer_list< std::pair< std::string, value > > items)
Insert items into this object.
bool inserted
Did the insert operation perform an insert? A value of false indicates there was a key already presen...
Definition value.hpp:598
object_view as_object() &
View this instance as an object.
bool empty() const noexcept
Is the underlying structure empty?
friend std::string to_string(const value &)
Get a string representation of the given value.
value(const char *value)
Create a kind::string with the given value.
void pop_back()
Pop an item off the back of this array.
object_iterator erase(const_object_iterator first, const_object_iterator last)
Erase the range defined by [first, last).
array_iterator insert(const_array_iterator position, value item)
Insert an item into position on this array.
const_object_view as_object() const &
View this instance as an object.
size_type erase(const std::string &key)
Erase the item with the given key.
value & path(size_type p)
Get or create the value specified by the path p.
object_node_handle extract(const std::wstring &key)
If the container has an element with the given key, moves its key and value into a node handle,...
array_iterator begin_array()
Get an iterator to the beginning of this array.
array_iterator end_array()
Get an iterator to the end of this array.
value(double value)
Create a kind::decimal with the given value.
void assign(std::initializer_list< value > items)
Assign the given items to this array.
value & path(std::string_view p)
Get or create the value specified by the path p.
value(int64_t value)
Create a kind::integer with the given value.
void reserve(size_type count)
Reserve at least count elements in the array.
const_array_view as_array() const &
View this instance as an array.
Type returned from insert operations when this has kind::object.
Definition value.hpp:592
Copyright (c) 2014-2020 by Travis Gockel.
#define JSONV_NODISCARD
Warn if the caller discards the result of this function.
Definition config.hpp:143
#define JSONV_INTEGER_ALTERNATES_LIST(item)
An item list of types to also consider as an integer.
Definition config.hpp:158
#define JSONV_PUBLIC
This function or class is part of the public API for JSON Voorhees.
Definition config.hpp:124
@ insert
Insert the correct key/value pair as part of serialization.
kind
Describes the kind of data a value holds.
Definition kind.hpp:30
JSONV_PUBLIC std::string to_string(const ast_node_type &type)
Get what operator<< writes for type as a std::string.
JSONV_PUBLIC value object()
Create an empty object.
JSONV_PUBLIC const value null
An instance with kind::null.
JSONV_PUBLIC value array()
Create an empty array value.
Copyright (c) 2019-2020 by Travis Gockel.
STL namespace.
The base type for iterating over array values.
Definition value.hpp:173
What operator-> returns: it holds the reference, so iter->first and iter->second work.
Definition value.hpp:438
const reference * operator->() const noexcept
The member the iterator was at, for the built-in -> to reach into.
Definition value.hpp:443
reference ref
The member the iterator was at.
Definition value.hpp:440
The base iterator type for iterating over object types.
Definition value.hpp:425
std::random_access_iterator_tag iterator_category
What this gives the functions which dispatch on the category.
Definition value.hpp:431
std::random_access_iterator_tag iterator_concept
What this models in C++20 terms: a random-access iterator, whose reference may be a proxy.
Definition value.hpp:428
basic_object_iterator(const basic_object_iterator< UValue, UMember > &source) noexcept
This allows conversion from an object_iterator to a const_object_iterator.
Definition value.hpp:461
What dereferencing an object_iterator (TValue of value) or a const_object_iterator (TValue of const v...
Definition value.hpp:355
basic_object_reference(const basic_object_reference< UValue > &source) noexcept
This allows conversion from an object_reference to a const_object_reference.
Definition value.hpp:391
const std::string first_type
The type of first, as in std::pair, which this stands in for.
Definition value.hpp:358
TValue second_type
The type of second, as in std::pair.
Definition value.hpp:361
const std::string & first
The key of the member.
Definition value.hpp:365
TValue & second
The value of the member.
Definition value.hpp:368
basic_object_reference(const std::string &key, TValue &val) noexcept
Refer to key and val.
Definition value.hpp:372
basic_object_reference(std::conditional_t< std::is_const_v< TValue >, const object_value_type &, object_value_type & > pair) noexcept
Refer to the key and value of pair.
Definition value.hpp:378