JSON Voorhees
Killer JSON for C++
value.hpp
Go to the documentation of this file.
1 /** \file jsonv/value.hpp
2  *
3  * Copyright (c) 2012-2018 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 **/
11 #ifndef __JSONV_VALUE_HPP_INCLUDED__
12 #define __JSONV_VALUE_HPP_INCLUDED__
13 
14 #include <jsonv/config.hpp>
15 #include <jsonv/string_view.hpp>
17 
18 #include <cstddef>
19 #include <cstdint>
20 #include <initializer_list>
21 #include <iosfwd>
22 #include <iterator>
23 #include <functional>
24 #include <map>
25 #include <stdexcept>
26 #include <string>
27 #include <type_traits>
28 #include <utility>
29 
30 namespace jsonv
31 {
32 
33 class path;
34 class value;
35 class object_node_handle;
36 
37 namespace detail
38 {
39 
40 class object_impl;
41 class array_impl;
42 class string_impl;
43 
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  constexpr value_storage() :
54  object(nullptr)
55  { }
56 };
57 
58 }
59 
60 /** \defgroup Value
61  * JSON \ref value instances.
62  * \{
63 **/
64 
65 /** Describes the \e kind of data a \c value holds. See \c value for more information.
66  *
67  * \see http://json.org/
68 **/
69 enum class kind : unsigned char
70 {
71  null,
72  object,
73  array,
74  string,
75  integer,
76  decimal,
77  boolean
78 };
79 
80 /** Print out the name of the \c kind. **/
81 JSONV_PUBLIC std::ostream& operator<<(std::ostream&, const kind&);
82 
83 /** Get the name of the \c kind. **/
84 JSONV_PUBLIC std::string to_string(const kind&);
85 
86 /** Get a string representation of the given \c value. **/
87 JSONV_PUBLIC std::string to_string(const value&);
88 
89 /** Thrown from various \c value methods when attempting to perform an operation which is not valid for the \c kind of
90  * value.
91 **/
93  public std::logic_error
94 {
95 public:
96  explicit kind_error(const std::string& description);
97 
98  virtual ~kind_error() noexcept;
99 };
100 
101 /** Represents a single JSON value, which can be any one of a potential \c kind, each behaving slightly differently.
102  * Instances will vary their behavior based on their kind -- functions will throw a \c kind_error if the operation does
103  * not apply to the value's kind. For example, it does not make sense to call \c find on an \c integer.
104  *
105  * - \c kind::null
106  * You cannot do anything with this...it is just null.
107  * - \c kind::boolean
108  * These values can be \c true or \c false.
109  * - \c kind::integer
110  * A numeric value which can be added, subtracted and all the other things you would expect.
111  * - \c kind::decimal
112  * Floating-point values should be considered "more general" than integers -- you may request an integer value as a
113  * decimal, but you cannot request a decimal as an integer, even when doing so would not require rounding. The
114  * literal \c 20.0 will always have \c kind::decimal.
115  * - \c kind::string
116  * A UTF-8 encoded string which is mostly accessed through the \c std::string class. Some random functions work in
117  * the cases where it makes sense (for example: \c empty and \c size), but in general, string manipulation should be
118  * done after calling \c as_string.
119  * - \c kind::array
120  * An array behaves like a \c std::deque because it is ultimately backed by one. If you feel the documentation is
121  * lacking, read this: http://en.cppreference.com/w/cpp/container/deque.
122  * - \c kind::object
123  * An object behaves lake a \c std::map because it is ultimately backed by one. If you feel the documentation is
124  * lacking, read this: http://en.cppreference.com/w/cpp/container/map. This library follows the recommendation in
125  * RFC 7159 to not allow for duplicate keys because most other libraries can not deal with it. It would also make
126  * the AST significantly more painful.
127  *
128  * \see http://json.org/
129  * \see http://tools.ietf.org/html/rfc7159
130 **/
132 {
133 public:
134  typedef std::size_t size_type;
135  typedef std::ptrdiff_t difference_type;
136 
137  /** The base type for iterating over array values. **/
138  template <typename T, typename TArrayView>
140  public std::iterator<std::random_access_iterator_tag, T>
141  {
142  public:
144  _owner(0),
145  _index(0)
146  { }
147 
148  basic_array_iterator(TArrayView* owner, size_type index) :
149  _owner(owner),
150  _index(index)
151  { }
152 
153  template <typename U, typename UArrayView>
155  typename std::enable_if<std::is_convertible<U*, T*>::value>::type* = 0
156  ) :
157  _owner(source._owner),
158  _index(source._index)
159  { }
160 
161  basic_array_iterator& operator++()
162  {
163  ++_index;
164  return *this;
165  }
166 
167  basic_array_iterator operator++(int) const
168  {
169  basic_array_iterator clone = *this;
170  ++clone;
171  return clone;
172  }
173 
174  basic_array_iterator& operator--()
175  {
176  --_index;
177  return *this;
178  }
179 
180  basic_array_iterator operator--(int) const
181  {
182  basic_array_iterator clone = *this;
183  --clone;
184  return clone;
185  }
186 
187  template <typename U, typename UArrayView>
188  bool operator==(const basic_array_iterator<U, UArrayView>& other) const
189  {
190  return _owner == other._owner && _index == other._index;
191  }
192 
193  template <typename U, typename UArrayView>
194  bool operator!=(const basic_array_iterator<U, UArrayView>& other) const
195  {
196  return !operator==(other);
197  }
198 
199  T& operator*() const
200  {
201  return _owner->operator[](_index);
202  }
203 
204  T* operator->() const
205  {
206  return &_owner->operator[](_index);
207  }
208 
209  basic_array_iterator& operator+=(size_type n)
210  {
211  _index += n;
212  return *this;
213  }
214 
215  basic_array_iterator operator+(size_type n) const
216  {
217  basic_array_iterator clone = *this;
218  clone += n;
219  return clone;
220  }
221 
222  basic_array_iterator& operator-=(size_type n)
223  {
224  _index -= n;
225  return *this;
226  }
227 
228  basic_array_iterator operator-(size_type n) const
229  {
230  basic_array_iterator clone = *this;
231  clone -= n;
232  return clone;
233  }
234 
235  difference_type operator-(const basic_array_iterator& other) const
236  {
237  return difference_type(_index) - difference_type(other._index);
238  }
239 
240  bool operator<(const basic_array_iterator& rhs) const
241  {
242  return _index < rhs._index;
243  }
244 
245  bool operator<=(const basic_array_iterator& rhs) const
246  {
247  return _index <= rhs._index;
248  }
249 
250  bool operator>(const basic_array_iterator& rhs) const
251  {
252  return _index > rhs._index;
253  }
254 
255  bool operator>=(const basic_array_iterator& rhs) const
256  {
257  return _index >= rhs._index;
258  }
259 
260  T& operator[](size_type n) const
261  {
262  return _owner->operator[](_index + n);
263  }
264  private:
265  template <typename U, typename UArrayView>
266  friend struct basic_array_iterator;
267 
268  friend class value;
269 
270  private:
271  TArrayView* _owner;
272  size_type _index;
273  };
274 
275  /** The \c array_iterator is applicable when \c kind is \c kind::array. It allows you to use algorithms as if
276  * a \c value was a normal sequence container.
277  **/
280 
281  /** If \c kind is \c kind::array, an \c array_view allows you to access a value as a sequence container. This is
282  * most useful for range-based for loops.
283  **/
287 
288  /** The base iterator type for iterating over object types. It is a bidirectional iterator similar to a
289  * \c std::map<std::string, jsonv::value>.
290  **/
291  template <typename T, typename TIterator>
293  public std::iterator<std::bidirectional_iterator_tag, T>
294  {
295  public:
297  _impl()
298  { }
299 
301  _impl(source._impl)
302  { }
303 
304  /** This allows assignment from an \c object_iterator to a \c const_object_iterator. **/
305  template <typename U, typename UIterator>
307  typename std::enable_if<std::is_convertible<U*, T*>::value>::type* = 0
308  ) :
309  _impl(source._impl)
310  { }
311 
312  basic_object_iterator& operator=(const basic_object_iterator& source)
313  {
314  _impl = source._impl;
315  return *this;
316  }
317 
318  template <typename U, typename UIterator>
319  typename std::enable_if<std::is_convertible<U*, T*>::value, basic_object_iterator&>::type
320  operator=(const basic_object_iterator<U, UIterator>& source)
321  {
322  return operator=(basic_object_iterator(source));
323  }
324 
325  basic_object_iterator& operator++()
326  {
327  increment();
328  return *this;
329  }
330 
331  basic_object_iterator operator++(int) const
332  {
333  basic_object_iterator clone(*this);
334  clone.increment();
335  return clone;
336  }
337 
338  basic_object_iterator& operator--()
339  {
340  decrement();
341  return *this;
342  }
343 
344  basic_object_iterator operator--(int) const
345  {
346  basic_object_iterator clone(*this);
347  clone.decrement();
348  return clone;
349  }
350 
351  template <typename U, typename UIterator>
352  bool operator ==(const basic_object_iterator<U, UIterator>& other) const
353  {
354  return _impl == other._impl;
355  }
356 
357  template <typename U, typename UIterator>
358  bool operator !=(const basic_object_iterator<U, UIterator>& other) const
359  {
360  return _impl != other._impl;
361  }
362 
363  T& operator *() const
364  {
365  return current();
366  }
367 
368  T* operator ->() const
369  {
370  return &current();
371  }
372 
373  private:
374  friend class value;
375 
376  template <typename UIterator>
377  explicit basic_object_iterator(const UIterator& iter) :
378  _impl(iter)
379  { }
380 
381  void increment()
382  {
383  ++_impl;
384  }
385 
386  void decrement()
387  {
388  --_impl;
389  }
390 
391  T& current() const
392  {
393  return *_impl;
394  }
395 
396  private:
397  TIterator _impl;
398  };
399 
400  /** The type of value stored when \c kind is \c kind::object. **/
401  typedef std::pair<const std::string, value> object_value_type;
402 
403  /** The \c object_iterator is applicable when \c kind is \c kind::object. It allows you to use algorithms as if
404  * a \c value was a normal associative container.
405  **/
408 
409  /** If \c kind is \c kind::object, an \c object_view allows you to access a value as an associative container.
410  * This is most useful for range-based for loops.
411  **/
415 
416  /// Type returned from \c insert operations when this has \ref kind::object. It is generally compatible with the
417  /// \c insert_return_type of \c std::map, with the notable lack of \c node.
418  ///
419  /// \see insert
421  {
422  /// The position of the inserted node or node with the duplicate key.
423  const_object_iterator position;
424 
425  /// Did the insert operation perform an insert? A value of \c false indicates there was a key already present
426  /// with the same name.
427  bool inserted;
428  };
429 
430 public:
431  /** Default-construct this to null. **/
432  constexpr value() :
433  _kind(jsonv::kind::null)
434  { }
435 
436  /** The nullptr overload will fail to compile -- use \c null if you want a \c kind::null. **/
437  value(std::nullptr_t) = delete;
438 
439  /** Copy the contents of \a source into a new instance. **/
440  value(const value& source);
441 
442  /** Create a \c kind::string with the given \a value. **/
443  value(const std::string& value);
444 
445  /** Create a \c kind::string with the given \a value. **/
446  value(const string_view& value);
447 
448  /** Create a \c kind::string with the given \a value.
449  *
450  * \param value The value to create with. This must be null-terminated.
451  **/
452  value(const char* value);
453 
454  /// Create a \c kind::string with the given \a value. Keep in mind that it will be converted to and stored as a
455  /// UTF-8 encoded string.
456  value(const std::wstring& value);
457 
458  /** Create a \c kind::string with the given \a value. Keep in mind that it will be converted to and stored as a
459  * UTF-8 encoded string.
460  *
461  * \param value The value to create with. This must be null-terminated.
462  **/
463  value(const wchar_t* value);
464 
465  /** Create a \c kind::integer with the given \a value. **/
466  value(int64_t value);
467 
468  /** Create a \c kind::decimal with the given \a value. **/
469  value(double value);
470 
471  /** Create a \c kind::decimal with the given \a value. **/
472  value(float value);
473 
474  /** Create a \c kind::boolean with the given \a value. **/
475  value(bool value);
476 
477  #define JSONV_VALUE_INTEGER_ALTERNATIVE_CTOR_PROTO_GENERATOR(type_) \
478  value(type_ val);
479  JSONV_INTEGER_ALTERNATES_LIST(JSONV_VALUE_INTEGER_ALTERNATIVE_CTOR_PROTO_GENERATOR)
480 
481  /** Destruction will never throw. **/
482  ~value() noexcept;
483 
484  /** Copy-assigns \c source to this.
485  *
486  * If an exception is thrown during the copy, it is propagated out. This instance will remain unchanged.
487  **/
488  value& operator=(const value& source);
489 
490  /** Move-construct this instance, leaving \a source as a null value. **/
491  value(value&& source) noexcept;
492 
493  /** Move-assigns \c source to this, leaving \a source as a null value.
494  *
495  * Unlike a copy, this will never throw.
496  **/
497  value& operator=(value&& source) noexcept;
498 
499  /** Get this value as a string.
500  *
501  * \throws kind_error if this value does not represent a string.
502  **/
503  const std::string& as_string() const;
504 
505  /** Tests if this \c kind is \c kind::string. **/
506  bool is_string() const;
507 
508  /** Get this value as a \c string_view. It is your responsibility to ensure the \c value instance remains valid.
509  *
510  * \throws kind_error if this value does not represent a string.
511  **/
512  string_view as_string_view() const &;
513 
514  /** Get this value as a wide string. Keep in mind that this is slower than \c as_string, as the internal storage is
515  * the \c char base \c std::string.
516  *
517  * \throws kind_error if this value does not represent a string.
518  **/
519  std::wstring as_wstring() const;
520 
521  /** Get this value as an integer.
522  *
523  * \throws kind_error if this value does not represent an integer.
524  **/
525  int64_t as_integer() const;
526 
527  /** Tests if this \c kind is \c kind::integer. **/
528  bool is_integer() const;
529 
530  /** Get this value as a decimal. If the value's underlying kind is actually an integer type, cast the integer to a
531  * double before returning. This ignores the potential loss of precision.
532  *
533  * \throws kind_error if this value does not represent a decimal or integer.
534  **/
535  double as_decimal() const;
536 
537  /** Tests if this \c kind is \c kind::integer or \c kind::decimal. **/
538  bool is_decimal() const;
539 
540  /** Get this value as a boolean.
541  *
542  * \throws kind_error if this value does not represent a boolean.
543  **/
544  bool as_boolean() const;
545 
546  /** Tests if this \c kind is \c kind::boolean. **/
547  bool is_boolean() const;
548 
549  /** Tests if this \c kind is \c kind::array. **/
550  bool is_array() const;
551 
552  /** Tests if this \c kind is \c kind::object. **/
553  bool is_object() const;
554 
555  /** Tests if this \c kind is \c kind::null. **/
556  bool is_null() const;
557 
558  /** Resets this value to null. **/
559  void clear();
560 
561  /** Get this value's kind. **/
562  inline jsonv::kind kind() const
563  {
564  return _kind;
565  }
566 
567  /** Get the value specified by the path \a p.
568  *
569  * \throws std::out_of_range if any path along the chain did not exist.
570  * \throws kind_error if the path traversal is not valid for the value (for example: if the path specifies an array
571  * index when the value is a string).
572  * \throws parse_error if a \c string_view was specified that did not have a valid specification (see
573  * \c path::create).
574  **/
575  value& at_path(const path& p);
576  value& at_path(string_view p);
577  value& at_path(size_type p);
578  const value& at_path(const path& p) const;
579  const value& at_path(string_view p) const;
580  const value& at_path(size_type p) const;
581 
582  /** Similar to \c count, but walks the given path \a p to determine its presence.
583  *
584  * \returns \c 1 if the path finds an element; \c 0 if there is no such path in the tree.
585  *
586  * \throws parse_error if a \c string_view was specified that did not have a valid specification (see
587  * \c path::create).
588  **/
589  size_type count_path(const path& p) const;
590  size_type count_path(string_view p) const;
591  size_type count_path(size_type p) const;
592 
593  /** Get or create the value specified by the path \a p. This is the moral equivalent to \c operator[] for paths. If
594  * no value exists at the path, a new one is created as the default (\c null) value. If any path along the way
595  * either does not exist or is \c null, it is created for you, based on the \e implications of the specification
596  * \a p. Unlike \c at_path, which will throw if accessing a non-existent key of an \c object or going past the end
597  * of an \c array, this will simply create that path and fill in the blanks with \c null values.
598  *
599  * \throws kind_error if the path traversal is not valid for the value (for example: if the path specifies an array
600  * index when the value is a string).
601  * \throws parse_error if a \c string_view was specified that did not have a valid specification (see
602  * \c path::create).
603  *
604  * \see at_path
605  **/
606  value& path(const path& p);
607  value& path(string_view p);
608  value& path(size_type p);
609 
610  /** Swap the value this instance represents with \a other. **/
611  void swap(value& other) noexcept;
612 
613  /** Compares two JSON values for equality. Two JSON values are equal if and only if all of the following conditions
614  * apply:
615  *
616  * 1. They have the same valid value for \c kind.
617  * - If \c kind is invalid (memory corruption), then two JSON values are \e not equal, even if they have been
618  * corrupted in the same way and even if they share \c this (a corrupt object is not equal to itself).
619  * 2. The kind comparison is also equal:
620  * - Two null values are always equivalent.
621  * - string, integer, decimal and boolean follow the classic rules for their type.
622  * - objects are equal if they have the same keys and values corresponding with the same key are also equal.
623  * - arrays are equal if they have the same length and the values at each index are also equal.
624  *
625  * \note
626  * The rules for equality are based on Python \c dict and \c list.
627  **/
628  bool operator==(const value& other) const;
629 
630  /** Compares two JSON values for inequality. The rules for inequality are the exact opposite of equality.
631  **/
632  bool operator!=(const value& other) const;
633 
634  /** Used to build a strict-ordering of JSON values. When comparing values of the same kind, the ordering should
635  * align with your intuition. When comparing values of different kinds, some arbitrary rules were created based on
636  * how "complicated" the author thought the type to be.
637  *
638  * - null: less than everything but null, which it is equal to.
639  * - boolean: false is less than true.
640  * - integer, decimal: compared by their numeric value. Comparisons between two integers do not cast, but comparison
641  * between an integer and a decimal will coerce to decimal.
642  * - string: compared lexicographically by character code (with basic char strings and non-ASCII encoding, this
643  * might lead to surprising results)
644  * - array: compared lexicographically by elements (recursively following this same technique)
645  * - object: entries in the object are sorted and compared lexicographically, first by key then by value
646  *
647  * \returns -1 if this is less than other by the rules stated above; 0 if this is equal to other; -1 if otherwise.
648  **/
649  int compare(const value& other) const;
650 
651  bool operator< (const value& other) const;
652  bool operator> (const value& other) const;
653  bool operator<=(const value& other) const;
654  bool operator>=(const value& other) const;
655 
656  /** Output this value to a stream. **/
657  friend std::ostream& operator<<(std::ostream& stream, const value& val);
658 
659  /** Get a string representation of the given \c value. **/
660  friend std::string to_string(const value&);
661 
662  /** Get an iterator to the beginning of this array.
663  *
664  * \throws kind_error if the kind is not an array.
665  **/
666  array_iterator begin_array();
667  const_array_iterator begin_array() const;
668 
669  /** Get an iterator to the end of this array.
670  *
671  * \throws kind_error if the kind is not an array.
672  **/
673  array_iterator end_array();
674  const_array_iterator end_array() const;
675 
676  /** View this instance as an array.
677  *
678  * \throws kind_error if the kind is not an array.
679  **/
680  array_view as_array() &;
681  const_array_view as_array() const &;
682  owning_array_view as_array() &&;
683 
684  /** Get the value in this array at the given \a idx. The overloads which accept an \c int are required to resolve
685  * the type ambiguity of the literal \c 0 between a size_type and a char*.
686  *
687  * \throws kind_error if the kind is not an array.
688  **/
689  value& operator[](size_type idx);
690  const value& operator[](size_type idx) const;
691  inline value& operator[](int idx) { return operator[](size_type(idx)); }
692  inline const value& operator[](int idx) const { return operator[](size_type(idx)); }
693 
694  /** Get the value in this array at the given \a idx.
695  *
696  * \throws kind_error if the kind is not an array.
697  * \throws std::out_of_range if the provided \a idx is above \c size.
698  **/
699  value& at(size_type idx);
700  const value& at(size_type idx) const;
701 
702  /** Push \a item to the back of this array.
703  *
704  * \throws kind_error if the kind is not an array.
705  **/
706  void push_back(value item);
707 
708  /** Pop an item off the back of this array.
709  *
710  * \throws kind_error if the kind is not an array.
711  * \throws std::logic_error if the array is empty.
712  **/
713  void pop_back();
714 
715  /** Push \a item to the front of this array.
716  *
717  * \throws kind_error if the kind is not an array.
718  **/
719  void push_front(value item);
720 
721  /** Pop an item from the front of this array.
722  *
723  * \throws kind_error if the kind is not an array.
724  * \throws std::logic_error if the array is empty.
725  **/
726  void pop_front();
727 
728  /** Insert an item into \a position on this array.
729  *
730  * \throws kind_error if the kind is not an array.
731  **/
732  array_iterator insert(const_array_iterator position, value item);
733 
734  /** Insert the range defined by [\a first, \a last) at \a position in this array.
735  *
736  * \throws kind_error if the kind is not an array.
737  **/
738  template <typename TForwardIterator>
739  array_iterator insert(const_array_iterator position, TForwardIterator first, TForwardIterator last)
740  {
741  difference_type orig_offset = std::distance(const_array_iterator(begin_array()), position);
742 
743  for (difference_type offset = orig_offset ; first != last; ++first, ++offset)
744  insert(begin_array() + offset, *first);
745  return begin_array() + orig_offset;
746  }
747 
748  /** Assign \a count elements to this array with \a val.
749  *
750  * \throws kind_error if the kind is not an array.
751  **/
752  void assign(size_type count, const value& val);
753 
754  /** Assign the contents of range [\a first, \a last) to this array.
755  *
756  * \throws kind_error if the kind is not an array.
757  **/
758  template <typename TForwardIterator>
759  void assign(TForwardIterator first, TForwardIterator last)
760  {
761  resize(std::distance(first, last), value());
762  auto iter = begin_array();
763  while (first != last)
764  {
765  *iter = *first;
766  ++iter;
767  ++first;
768  }
769  }
770 
771  /** Assign the given \a items to this array.
772  *
773  * \throws kind_error if the kind is not an array.
774  **/
775  void assign(std::initializer_list<value> items);
776 
777  /** Resize the length of this array to \a count items. If the resize creates new elements, fill those newly-created
778  * elements with \a val.
779  *
780  * \throws kind_error if the kind is not an array.
781  **/
782  void resize(size_type count, const value& val = value());
783 
784  /** Erase the item at this array's \a position.
785  *
786  * \throws kind_error if the kind is not an array.
787  **/
788  array_iterator erase(const_array_iterator position);
789 
790  /** Erase the range [\a first, \a last) from this array.
791  *
792  * \throws kind_error if the kind is not an array.
793  **/
794  array_iterator erase(const_array_iterator first, const_array_iterator last);
795 
796  /** Get an iterator to the first key-value pair in this object.
797  *
798  * \throws kind_error if the kind is not an object.
799  **/
800  object_iterator begin_object();
801  const_object_iterator begin_object() const;
802 
803  /** Get an iterator to the one past the end of this object.
804  *
805  * \throws kind_error if the kind is not an object.
806  **/
807  object_iterator end_object();
808  const_object_iterator end_object() const;
809 
810  /** View this instance as an object.
811  *
812  * \throws kind_error if the kind is not an object.
813  **/
814  object_view as_object() &;
815  const_object_view as_object() const &;
816  owning_object_view as_object() &&;
817 
818  /** Get the value associated with the given \a key of this object. If the \a key does not exist, it will be created.
819  *
820  * \throws kind_error if the kind is not an object.
821  **/
822  value& operator[](const std::string& key);
823  value& operator[](std::string&& key);
824  value& operator[](const std::wstring& key);
825 
826  /** Get the value associated with the given \a key of this object.
827  *
828  * \throws kind_error if the kind is not an object.
829  * \throws std::out_of_range if the \a key is not in this object.
830  **/
831  value& at(const std::string& key);
832  value& at(const std::wstring& key);
833  const value& at(const std::string& key) const;
834  const value& at(const std::wstring& key) const;
835 
836  /** Check if the given \a key exists in this object.
837  *
838  * \throws kind_error if the kind is not an object.
839  **/
840  size_type count(const std::string& key) const;
841  size_type count(const std::wstring& key) const;
842 
843  /** Attempt to locate a key-value pair with the provided \a key in this object.
844  *
845  * \throws kind_error if the kind is not an object.
846  **/
847  object_iterator find(const std::string& key);
848  object_iterator find(const std::wstring& key);
849  const_object_iterator find(const std::string& key) const;
850  const_object_iterator find(const std::wstring& key) const;
851 
852  /// \{
853  /// Insert \a pair into this object. If \a hint is provided, this insertion could be optimized.
854  ///
855  /// \returns A pair whose \c first refers to the newly-inserted element (or the element which shares the key).
856  /// \throws kind_error if the kind is not an object.
857  std::pair<object_iterator, bool> insert(std::pair<std::string, value> pair);
858  std::pair<object_iterator, bool> insert(std::pair<std::wstring, value> pair);
859  object_iterator insert(const_object_iterator hint, std::pair<std::string, value> pair);
860  object_iterator insert(const_object_iterator hint, std::pair<std::wstring, value> pair);
861 
862  /// Insert range defined by [\a first, \a last) into this object.
863  ///
864  /// \throws kind_error if the kind is not an object.
865  template <typename TForwardIterator>
866  void insert(TForwardIterator first, TForwardIterator last)
867  {
868  for ( ; first != last; ++first)
869  insert(*first);
870  }
871 
872  /// Insert the contents of \a handle. If \a handle is empty, this does nothing.
873  ///
874  /// \returns If \a handle is empty, \c inserted is \c false and \c position is `end_object()`. If the insertion took
875  /// place, \c inserted is \c true and \c position points to the inserted element. If the insertion was attempted
876  /// but failed, \c inserted is \c false and \c position points to an element with a key equivalent to
877  /// `handle.key()`.
878  /// \throws kind_error if the kind is not an object.
880 
881  /// If \a handle is an empty node handle, does nothing and returns \ref end_object. Otherwise, inserts the element
882  /// owned by \a handle into the container, if the container doesn't already contain an element with a key equivalent
883  /// to `handle.key()` and returns the iterator pointing to the element with key equivalent to `handle.key()`. If the
884  /// insertion succeeds, \a handle is moved from, otherwise it retains ownership of the element. The element is
885  /// inserted as close as possible to the position just prior to \a hint.
886  ///
887  /// \returns An iterator pointing to an element with a key equivalent to `handle.key()` if \a handle was not empty.
888  /// If \a handle was empty, `end_object()`.
889  /// \throws kind_error if the kind is not an object.
890  object_iterator insert(const_object_iterator hint, object_node_handle&& handle);
891 
892  /// Insert \a items into this object.
893  ///
894  /// \throws kind_error if the kind is not an object.
895  void insert(std::initializer_list<std::pair<std::string, value>> items);
896  void insert(std::initializer_list<std::pair<std::wstring, value>> items);
897  /// \}
898 
899  /// \{
900  /// Erase the item with the given \a key.
901  ///
902  /// \returns 1 if \a key was erased; 0 if it did not.
903  /// \throws kind_error if the kind is not an object.
904  size_type erase(const std::string& key);
905  size_type erase(const std::wstring& key);
906 
907  /// Erase the item at the given \a position.
908  ///
909  /// \throws kind_error if the kind is not an object.
910  object_iterator erase(const_object_iterator position);
911 
912  /// Erase the range defined by [\a first, \a last).
913  ///
914  /// \throws kind_error if the kind is not an object.
915  object_iterator erase(const_object_iterator first, const_object_iterator last);
916  /// \}
917 
918  /// \{
919  /// Unlinks the node that contains the element pointed to by position and returns a node handle that owns it.
920  ///
921  /// \throws kind_error if the kind is not an object.
922  object_node_handle extract(const_object_iterator position);
923 
924  /// If the container has an element with the given \a key, unlinks the node that contains that element from the
925  /// container and returns a node handle that owns it. Otherwise, returns an empty node handle.
926  ///
927  /// \throws kind_error if the kind is not an object.
928  object_node_handle extract(const std::string& key);
929  object_node_handle extract(const std::wstring& key);
930  /// \}
931 
932  /** Is the underlying structure empty?
933  *
934  * - object: Are there no keys?
935  * - array: Are there no values?
936  * - string: Is the string 0 length?
937  * - null: true (always)
938  * - all other types: false (always)
939  *
940  * \throws nothing
941  **/
942  bool empty() const noexcept;
943 
944  /** Get the number of items in this value.
945  *
946  * - object: The number of key/value pairs.
947  * - array: The number of values.
948  * - string: The number of code points in the string (including \c \\0 values and counting multi-byte encodings as
949  * more than one value).
950  *
951  * \throws kind_error if the kind is not an object, array or string.
952  **/
953  size_type size() const;
954 
955  /** \addtogroup Algorithm
956  * \{
957  **/
958 
959  /** Run a function over the values of this instance. The behavior of this function is different, depending on the
960  * \c kind. For scalar kinds (\c kind::integer, \c kind::null, etc), \a func is called once with the value. If this
961  * is \c kind::array, \c func is called for every value in the array and the output will be an array with each
962  * element transformed by \a func. If this is \c kind::object, the result will be an object with each key
963  * transformed by \a func.
964  *
965  * \param func The function to apply to the element or elements of this instance.
966  **/
967  value map(const std::function<value (const value&)>& func) const&;
968 
969  /** Run a function over the values of this instance. The behavior of this function is different, depending on the
970  * \c kind. For scalar kinds (\c kind::integer, \c kind::null, etc), \a func is called once with the value. If this
971  * is \c kind::array, \c func is called for every value in the array and the output will be an array with each
972  * element transformed by \a func. If this is \c kind::object, the result will be an object with each key
973  * transformed by \a func.
974  *
975  * \param func The function to apply to the element or elements of this instance.
976  *
977  * \note
978  * This version of \c map provides only a basic exception-safety guarantee. If an exception is thrown while
979  * transforming a non-scalar \c kind, there is no rollback action, so \c this is left in a usable, but
980  * \e unpredictable state. If you need a strong exception guarantee, use the constant reference version of \c map.
981  **/
982  value map(const std::function<value (value)>& func) &&;
983 
984  /** \} **/
985 
986 private:
987  friend JSONV_PUBLIC value array();
988  friend JSONV_PUBLIC value object();
989 
990 private:
991  detail::value_storage _data;
992  jsonv::kind _kind;
993 };
994 
995 /** An instance with \c kind::null. This is intended to be used for convenience and readability (as opposed to using the
996  * default constructor of \c value.
997 **/
998 JSONV_PUBLIC extern const value null;
999 
1000 /** A user-defined literal for parsing JSON. Uses the default (non-strict) \c parse_options.
1001  *
1002  * \code
1003  * R"({
1004  * "taco": "cat",
1005  * "burrito": "dog",
1006  * "whatever": [ "goes", "here", 1, 2, 3, 4 ]
1007  * })"_json;
1008  * \endcode
1009 **/
1010 JSONV_PUBLIC value operator"" _json(const char* str, std::size_t len);
1011 
1012 /** Swap the values \a a and \a b. **/
1013 JSONV_PUBLIC void swap(value& a, value& b) noexcept;
1014 
1015 /** Create an empty array value. **/
1017 
1018 /** Create an array value from the given source. **/
1019 JSONV_PUBLIC value array(std::initializer_list<value> source);
1020 
1021 /** Create an array with contents defined by range [\a first, \a last). **/
1022 template <typename TForwardIterator>
1023 value array(TForwardIterator first, TForwardIterator last)
1024 {
1025  value arr = array();
1026  arr.assign(first, last);
1027  return arr;
1028 }
1029 
1030 /** Create an empty object. **/
1032 
1033 /** Create an object with key-value pairs from the given \a source. **/
1034 JSONV_PUBLIC value object(std::initializer_list<std::pair<std::string, value>> source);
1035 JSONV_PUBLIC value object(std::initializer_list<std::pair<std::wstring, value>> source);
1036 
1037 /** Create an object whose contents are defined by range [\a first, \a last). **/
1038 template <typename TForwardIterator>
1039 value object(TForwardIterator first, TForwardIterator last)
1040 {
1041  value obj = object();
1042  obj.insert(first, last);
1043  return obj;
1044 }
1045 
1046 /// A <a href="http://en.cppreference.com/w/cpp/container/node_handle">node handle</a> used when a value is
1047 /// \ref kind::object to access elements of the object in potentially destructive manner. This makes it possible to
1048 /// modify the contents of a node extracted from an object, and then re-insert it without having to copy the element.
1050 {
1051 public:
1052  /// The key type of the object.
1053  using key_type = std::string;
1054 
1055  /// The mapped type of the object.
1057 
1058 public:
1059  explicit object_node_handle() noexcept :
1060  _has_value(false)
1061  { }
1062 
1064 
1065  object_node_handle& operator=(object_node_handle&&) noexcept;
1066 
1067  ~object_node_handle() noexcept;
1068 
1069  /// \returns \c true if the node handle is empty; \c false if otherwise.
1070  bool empty() const noexcept { return !_has_value; }
1071 
1072  /// \returns \c false if the node handle is empty; \c true if otherwise.
1073  explicit operator bool() const noexcept { return _has_value; }
1074 
1075  /// Returns a non-const reference to the \ref key_type member of the element.
1076  ///
1077  /// \throws std::invalid_argument if the node handle is \ref empty.
1078  key_type& key() const;
1079 
1080  /// Returns a non-const reference to the \ref mapped_type member of the element.
1081  ///
1082  /// \throws std::invalid_argument if the node handle is \ref empty.
1083  mapped_type& mapped() const;
1084 
1085 private:
1086  enum class purposeful_construction
1087  { };
1088 
1089  explicit object_node_handle(purposeful_construction, key_type, mapped_type) noexcept;
1090 
1091  friend class value;
1092 
1093 private:
1094  bool _has_value;
1095  mutable key_type _key;
1096  mutable mapped_type _value;
1097 };
1098 
1099 /** \} **/
1100 
1101 }
1102 
1103 namespace std
1104 {
1105 
1106 /** Explicit specialization of \c std::hash for \c jsonv::value types so you can store a \c value in an unordered
1107  * container. Hashing results depend on the \c kind for the provided value -- most kinds directly use the hasher for
1108  * their kind (hashing a \c jsonv::value for integer \c 5 should have the same hash value as directly hashing the same
1109  * integer). For aggregate kinds \c array and \c object, hashing visits every sub-element recursively. This might be
1110  * expensive, but is required when storing multiple values with similar layouts in the a set (which is the most common
1111  * use case).
1112 **/
1113 template <>
1114 struct JSONV_PUBLIC hash<jsonv::value>
1115 {
1116  std::size_t operator()(const jsonv::value& val) const noexcept;
1117 };
1118 
1119 }
1120 
1121 #endif/*__JSONV_VALUE_HPP_INCLUDED__*/
JSONV_PUBLIC std::ostream & operator<<(std::ostream &, const kind &)
Print out the name of the kind.
basic_object_iterator< object_value_type, std::map< std::string, value >::iterator > object_iterator
The object_iterator is applicable when kind is kind::object.
Definition: value.hpp:406
#define JSONV_INTEGER_ALTERNATES_LIST(item)
An item list of types to also consider as an integer.
Definition: config.hpp:148
std::string key_type
The key type of the object.
Definition: value.hpp:1053
Thrown from various value methods when attempting to perform an operation which is not valid for the ...
Definition: value.hpp:92
bool empty() const noexcept
Definition: value.hpp:1070
void assign(TForwardIterator first, TForwardIterator last)
Assign the contents of range [first, last) to this array.
Definition: value.hpp:759
array_iterator insert(const_array_iterator position, value item)
Insert an item into position on this array.
STL namespace.
The base iterator type for iterating over object types.
Definition: value.hpp:292
Copyright (c) 2014-2019 by Travis Gockel.
The base type for iterating over array values.
Definition: value.hpp:139
A form of basic_view that owns the object it is iterating over.
Definition: basic_view.hpp:92
bool inserted
Did the insert operation perform an insert? A value of false indicates there was a key already presen...
Definition: value.hpp:427
JSONV_PUBLIC const value null
An instance with kind::null.
Represents an exact path in some JSON structure.
Definition: path.hpp:82
void assign(size_type count, const value &val)
Assign count elements to this array with val.
void insert(TForwardIterator first, TForwardIterator last)
Insert range defined by [first, last) into this object.
Definition: value.hpp:866
JSONV_PUBLIC value map(const std::function< value(const value &)> &func, const value &input)
Run a function over the values in the input.
JSONV_PUBLIC value array()
Create an empty array value.
jsonv::kind kind() const
Get this value&#39;s kind.
Definition: value.hpp:562
Insert the correct key/value pair as part of serialization.
kind
Describes the kind of data a value holds.
Definition: value.hpp:69
JSONV_PUBLIC void swap(value &a, value &b) noexcept
Swap the values a and b.
JSONV_PUBLIC std::string to_string(const value &)
Get a string representation of the given value.
Type returned from insert operations when this has kind::object.
Definition: value.hpp:420
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:412
Pulls in an implementation of string_view.
int compare(const value &a, const value &b, const TCompareTraits &traits)
Compare the values a and b using the comparison traits.
Definition: algorithm.hpp:124
JSONV_PUBLIC value object()
Create an empty object.
Copyright (c) 2014 by Travis Gockel.
basic_object_iterator(const basic_object_iterator< U, UIterator > &source, typename std::enable_if< std::is_convertible< U *, T * >::value >::type *=0)
This allows assignment from an object_iterator to a const_object_iterator.
Definition: value.hpp:306
basic_array_iterator< value, value > array_iterator
The array_iterator is applicable when kind is kind::array.
Definition: value.hpp:278
const_object_iterator position
The position of the inserted node or node with the duplicate key.
Definition: value.hpp:423
A view template used for array and object views of a value.
Definition: basic_view.hpp:34
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:284
constexpr value()
Default-construct this to null.
Definition: value.hpp:432
T extract(const value &from, const formats &fmts)
Extract a C++ value from from using the provided fmts.
std::pair< const std::string, value > object_value_type
The type of value stored when kind is kind::object.
Definition: value.hpp:401
#define JSONV_PUBLIC
This function or class is part of the public API for JsonVoorhees.
Definition: config.hpp:104
JSONV_STRING_VIEW_TYPE string_view
A non-owning reference to a string.
Definition: string_view.hpp:52
Represents a single JSON value, which can be any one of a potential kind, each behaving slightly diff...
Definition: value.hpp:131
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:739
A node handle used when a value is kind::object to access elements of the object in potentially destr...
Definition: value.hpp:1049