JsonCpp project page Classes Namespace JsonCpp home page

value.h
Go to the documentation of this file.
1 // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
2 // Distributed under MIT license, or public domain if desired and
3 // recognized in your jurisdiction.
4 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
5 
6 #ifndef CPPTL_JSON_H_INCLUDED
7 #define CPPTL_JSON_H_INCLUDED
8 
9 #if !defined(JSON_IS_AMALGAMATION)
10 #include "forwards.h"
11 #endif // if !defined(JSON_IS_AMALGAMATION)
12 #include <array>
13 #include <exception>
14 #include <memory>
15 #include <string>
16 #include <vector>
17 
18 #ifndef JSON_USE_CPPTL_SMALLMAP
19 #include <map>
20 #else
21 #include <cpptl/smallmap.h>
22 #endif
23 #ifdef JSON_USE_CPPTL
24 #include <cpptl/forwards.h>
25 #endif
26 
27 // Conditional NORETURN attribute on the throw functions would:
28 // a) suppress false positives from static code analysis
29 // b) possibly improve optimization opportunities.
30 #if !defined(JSONCPP_NORETURN)
31 #if defined(_MSC_VER)
32 #define JSONCPP_NORETURN __declspec(noreturn)
33 #elif defined(__GNUC__)
34 #define JSONCPP_NORETURN __attribute__((__noreturn__))
35 #else
36 #define JSONCPP_NORETURN
37 #endif
38 #endif
39 
40 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
41 // be used by...
42 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
43 #pragma warning(push)
44 #pragma warning(disable : 4251)
45 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
46 
47 #pragma pack(push, 8)
48 
51 namespace Json {
52 
53 #if JSON_USE_EXCEPTION
54 
58 class JSON_API Exception : public std::exception {
59 public:
60  Exception(String msg);
61  ~Exception() JSONCPP_NOEXCEPT override;
62  char const* what() const JSONCPP_NOEXCEPT override;
63 
64 protected:
66 };
67 
75 public:
76  RuntimeError(String const& msg);
77 };
78 
85 class JSON_API LogicError : public Exception {
86 public:
87  LogicError(String const& msg);
88 };
89 #endif
90 
92 JSONCPP_NORETURN void throwRuntimeError(String const& msg);
94 JSONCPP_NORETURN void throwLogicError(String const& msg);
95 
98 enum ValueType {
99  nullValue = 0,
107 };
108 
115 };
116 
122 };
123 
124 //# ifdef JSON_USE_CPPTL
125 // typedef CppTL::AnyEnumerator<const char *> EnumMemberNames;
126 // typedef CppTL::AnyEnumerator<const Value &> EnumValues;
127 //# endif
128 
144 public:
145  explicit StaticString(const char* czstring) : c_str_(czstring) {}
146 
147  operator const char*() const { return c_str_; }
148 
149  const char* c_str() const { return c_str_; }
150 
151 private:
152  const char* c_str_;
153 };
154 
190  friend class ValueIteratorBase;
191 
192 public:
193  typedef std::vector<String> Members;
196  typedef Json::UInt UInt;
197  typedef Json::Int Int;
198 #if defined(JSON_HAS_INT64)
201 #endif // defined(JSON_HAS_INT64)
205 
206  // Required for boost integration, e. g. BOOST_TEST
207  typedef std::string value_type;
208 
209  static const Value& null;
210  static const Value& nullRef;
212  static Value const& nullSingleton();
214 
216  static const LargestInt minLargestInt;
218  static const LargestInt maxLargestInt;
221 
223  static const Int minInt;
225  static const Int maxInt;
227  static const UInt maxUInt;
228 
229 #if defined(JSON_HAS_INT64)
230  static const Int64 minInt64;
233  static const Int64 maxInt64;
235  static const UInt64 maxUInt64;
236 #endif // defined(JSON_HAS_INT64)
237 
240 
241 // Workaround for bug in the NVIDIAs CUDA 9.1 nvcc compiler
242 // when using gcc and clang backend compilers. CZString
243 // cannot be defined as private. See issue #486
244 #ifdef __NVCC__
245 public:
246 #else
247 private:
248 #endif
249 #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
250  class CZString {
251  public:
252  enum DuplicationPolicy { noDuplication = 0, duplicate, duplicateOnCopy };
253  CZString(ArrayIndex index);
254  CZString(char const* str, unsigned length, DuplicationPolicy allocate);
255  CZString(CZString const& other);
256  CZString(CZString&& other);
257  ~CZString();
258  CZString& operator=(const CZString& other);
259  CZString& operator=(CZString&& other);
260 
261  bool operator<(CZString const& other) const;
262  bool operator==(CZString const& other) const;
263  ArrayIndex index() const;
264  // const char* c_str() const; ///< \deprecated
265  char const* data() const;
266  unsigned length() const;
267  bool isStaticString() const;
268 
269  private:
270  void swap(CZString& other);
271 
272  struct StringStorage {
273  unsigned policy_ : 2;
274  unsigned length_ : 30; // 1GB max
275  };
276 
277  char const* cstr_; // actually, a prefixed string, unless policy is noDup
278  union {
279  ArrayIndex index_;
280  StringStorage storage_;
281  };
282  };
283 
284 public:
285 #ifndef JSON_USE_CPPTL_SMALLMAP
286  typedef std::map<CZString, Value> ObjectValues;
287 #else
288  typedef CppTL::SmallMap<CZString, Value> ObjectValues;
289 #endif // ifndef JSON_USE_CPPTL_SMALLMAP
290 #endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
291 
292 public:
308  Value(ValueType type = nullValue);
309  Value(Int value);
310  Value(UInt value);
311 #if defined(JSON_HAS_INT64)
312  Value(Int64 value);
313  Value(UInt64 value);
314 #endif // if defined(JSON_HAS_INT64)
315  Value(double value);
316  Value(const char* value);
317  Value(const char* begin, const char* end);
318 
333  Value(const StaticString& value);
334  Value(const String& value);
335 #ifdef JSON_USE_CPPTL
337  Value(const CppTL::ConstString& value);
338 #endif
339  Value(bool value);
340  Value(const Value& other);
341  Value(Value&& other);
342  ~Value();
343 
346  Value& operator=(const Value& other);
347  Value& operator=(Value&& other);
348 
350  void swap(Value& other);
352  void swapPayload(Value& other);
353 
355  void copy(const Value& other);
357  void copyPayload(const Value& other);
358 
359  ValueType type() const;
360 
362  bool operator<(const Value& other) const;
363  bool operator<=(const Value& other) const;
364  bool operator>=(const Value& other) const;
365  bool operator>(const Value& other) const;
366  bool operator==(const Value& other) const;
367  bool operator!=(const Value& other) const;
368  int compare(const Value& other) const;
369 
370  const char* asCString() const;
371 #if JSONCPP_USING_SECURE_MEMORY
372  unsigned getCStringLength() const; // Allows you to understand the length of
373  // the CString
374 #endif
375  String asString() const;
376 
379  bool getString(char const** begin, char const** end) const;
380 #ifdef JSON_USE_CPPTL
381  CppTL::ConstString asConstString() const;
382 #endif
383  Int asInt() const;
384  UInt asUInt() const;
385 #if defined(JSON_HAS_INT64)
386  Int64 asInt64() const;
387  UInt64 asUInt64() const;
388 #endif // if defined(JSON_HAS_INT64)
389  LargestInt asLargestInt() const;
390  LargestUInt asLargestUInt() const;
391  float asFloat() const;
392  double asDouble() const;
393  bool asBool() const;
394 
395  bool isNull() const;
396  bool isBool() const;
397  bool isInt() const;
398  bool isInt64() const;
399  bool isUInt() const;
400  bool isUInt64() const;
401  bool isIntegral() const;
402  bool isDouble() const;
403  bool isNumeric() const;
404  bool isString() const;
405  bool isArray() const;
406  bool isObject() const;
407 
408  bool isConvertibleTo(ValueType other) const;
409 
411  ArrayIndex size() const;
412 
415  bool empty() const;
416 
418  JSONCPP_OP_EXPLICIT operator bool() const;
419 
423  void clear();
424 
430  void resize(ArrayIndex newSize);
431 
438  Value& operator[](ArrayIndex index);
439 
446  Value& operator[](int index);
447 
451  const Value& operator[](ArrayIndex index) const;
452 
456  const Value& operator[](int index) const;
457 
461  Value get(ArrayIndex index, const Value& defaultValue) const;
463  bool isValidIndex(ArrayIndex index) const;
467  Value& append(const Value& value);
468  Value& append(Value&& value);
469 
473  Value& operator[](const char* key);
476  const Value& operator[](const char* key) const;
479  Value& operator[](const String& key);
483  const Value& operator[](const String& key) const;
497  Value& operator[](const StaticString& key);
498 #ifdef JSON_USE_CPPTL
499  Value& operator[](const CppTL::ConstString& key);
503  const Value& operator[](const CppTL::ConstString& key) const;
504 #endif
505  Value get(const char* key, const Value& defaultValue) const;
511  Value
512  get(const char* begin, const char* end, const Value& defaultValue) const;
516  Value get(const String& key, const Value& defaultValue) const;
517 #ifdef JSON_USE_CPPTL
518  Value get(const CppTL::ConstString& key, const Value& defaultValue) const;
521 #endif
522  Value const* find(char const* begin, char const* end) const;
529  Value* demand(char const* begin, char const* end);
535  void removeMember(const char* key);
538  void removeMember(const String& key);
541  bool removeMember(const char* key, Value* removed);
548  bool removeMember(String const& key, Value* removed);
550  bool removeMember(const char* begin, const char* end, Value* removed);
557  bool removeIndex(ArrayIndex index, Value* removed);
558 
561  bool isMember(const char* key) const;
564  bool isMember(const String& key) const;
566  bool isMember(const char* begin, const char* end) const;
567 #ifdef JSON_USE_CPPTL
568  bool isMember(const CppTL::ConstString& key) const;
570 #endif
571 
577  Members getMemberNames() const;
578 
579  //# ifdef JSON_USE_CPPTL
580  // EnumMemberNames enumMemberNames() const;
581  // EnumValues enumValues() const;
582  //# endif
583 
585  JSONCPP_DEPRECATED("Use setComment(String const&) instead.")
586  void setComment(const char* comment, CommentPlacement placement) {
587  setComment(String(comment, strlen(comment)), placement);
588  }
590  void setComment(const char* comment, size_t len, CommentPlacement placement) {
591  setComment(String(comment, len), placement);
592  }
594  void setComment(String comment, CommentPlacement placement);
595  bool hasComment(CommentPlacement placement) const;
597  String getComment(CommentPlacement placement) const;
598 
599  String toStyledString() const;
600 
601  const_iterator begin() const;
602  const_iterator end() const;
603 
604  iterator begin();
605  iterator end();
606 
607  // Accessors for the [start, limit) range of bytes within the JSON text from
608  // which this value was parsed, if any.
609  void setOffsetStart(ptrdiff_t start);
610  void setOffsetLimit(ptrdiff_t limit);
611  ptrdiff_t getOffsetStart() const;
612  ptrdiff_t getOffsetLimit() const;
613 
614 private:
615  void setType(ValueType v) {
616  bits_.value_type_ = static_cast<unsigned char>(v);
617  }
618  bool isAllocated() const { return bits_.allocated_; }
619  void setIsAllocated(bool v) { bits_.allocated_ = v; }
620 
621  void initBasic(ValueType type, bool allocated = false);
622  void dupPayload(const Value& other);
623  void releasePayload();
624  void dupMeta(const Value& other);
625 
626  Value& resolveReference(const char* key);
627  Value& resolveReference(const char* key, const char* end);
628 
629  // struct MemberNamesTransform
630  //{
631  // typedef const char *result_type;
632  // const char *operator()( const CZString &name ) const
633  // {
634  // return name.c_str();
635  // }
636  //};
637 
638  union ValueHolder {
639  LargestInt int_;
640  LargestUInt uint_;
641  double real_;
642  bool bool_;
643  char* string_; // if allocated_, ptr to { unsigned, char[] }.
644  ObjectValues* map_;
645  } value_;
646 
647  struct {
648  // Really a ValueType, but types should agree for bitfield packing.
649  unsigned int value_type_ : 8;
650  // Unless allocated_, string_ must be null-terminated.
651  unsigned int allocated_ : 1;
652  } bits_;
653 
654  class Comments {
655  public:
656  Comments() = default;
657  Comments(const Comments& that);
658  Comments(Comments&& that);
659  Comments& operator=(const Comments& that);
660  Comments& operator=(Comments&& that);
661  bool has(CommentPlacement slot) const;
662  String get(CommentPlacement slot) const;
663  void set(CommentPlacement slot, String s);
664 
665  private:
666  using Array = std::array<String, numberOfCommentPlacement>;
667  std::unique_ptr<Array> ptr_;
668  };
669  Comments comments_;
670 
671  // [start, limit) byte offsets in the source JSON text from which this Value
672  // was extracted.
673  ptrdiff_t start_;
674  ptrdiff_t limit_;
675 };
676 
681 public:
682  friend class Path;
683 
684  PathArgument();
685  PathArgument(ArrayIndex index);
686  PathArgument(const char* key);
687  PathArgument(const String& key);
688 
689 private:
690  enum Kind { kindNone = 0, kindIndex, kindKey };
691  String key_;
692  ArrayIndex index_{};
693  Kind kind_{kindNone};
694 };
695 
707 class JSON_API Path {
708 public:
709  Path(const String& path,
710  const PathArgument& a1 = PathArgument(),
711  const PathArgument& a2 = PathArgument(),
712  const PathArgument& a3 = PathArgument(),
713  const PathArgument& a4 = PathArgument(),
714  const PathArgument& a5 = PathArgument());
715 
716  const Value& resolve(const Value& root) const;
717  Value resolve(const Value& root, const Value& defaultValue) const;
720  Value& make(Value& root) const;
721 
722 private:
723  typedef std::vector<const PathArgument*> InArgs;
724  typedef std::vector<PathArgument> Args;
725 
726  void makePath(const String& path, const InArgs& in);
727  void addPathInArg(const String& path,
728  const InArgs& in,
729  InArgs::const_iterator& itInArg,
730  PathArgument::Kind kind);
731  static void invalidPath(const String& path, int location);
732 
733  Args args_;
734 };
735 
740 public:
741  typedef std::bidirectional_iterator_tag iterator_category;
742  typedef unsigned int size_t;
743  typedef int difference_type;
745 
746  bool operator==(const SelfType& other) const { return isEqual(other); }
747 
748  bool operator!=(const SelfType& other) const { return !isEqual(other); }
749 
750  difference_type operator-(const SelfType& other) const {
751  return other.computeDistance(*this);
752  }
753 
756  Value key() const;
757 
760  UInt index() const;
761 
765  String name() const;
766 
771  JSONCPP_DEPRECATED("Use `key = name();` instead.")
772  char const* memberName() const;
776  char const* memberName(char const** end) const;
777 
778 protected:
779  Value& deref() const;
780 
781  void increment();
782 
783  void decrement();
784 
785  difference_type computeDistance(const SelfType& other) const;
786 
787  bool isEqual(const SelfType& other) const;
788 
789  void copy(const SelfType& other);
790 
791 private:
792  Value::ObjectValues::iterator current_;
793  // Indicates that iterator is for a null value.
794  bool isNull_{true};
795 
796 public:
797  // For some reason, BORLAND needs these at the end, rather
798  // than earlier. No idea why.
799  ValueIteratorBase();
800  explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
801 };
802 
807  friend class Value;
808 
809 public:
810  typedef const Value value_type;
811  // typedef unsigned int size_t;
812  // typedef int difference_type;
813  typedef const Value& reference;
814  typedef const Value* pointer;
816 
818  ValueConstIterator(ValueIterator const& other);
819 
820 private:
823  explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
824 
825 public:
826  SelfType& operator=(const ValueIteratorBase& other);
827 
829  SelfType temp(*this);
830  ++*this;
831  return temp;
832  }
833 
835  SelfType temp(*this);
836  --*this;
837  return temp;
838  }
839 
841  decrement();
842  return *this;
843  }
844 
846  increment();
847  return *this;
848  }
849 
850  reference operator*() const { return deref(); }
851 
852  pointer operator->() const { return &deref(); }
853 };
854 
858  friend class Value;
859 
860 public:
861  typedef Value value_type;
862  typedef unsigned int size_t;
863  typedef int difference_type;
864  typedef Value& reference;
865  typedef Value* pointer;
867 
868  ValueIterator();
869  explicit ValueIterator(const ValueConstIterator& other);
870  ValueIterator(const ValueIterator& other);
871 
872 private:
875  explicit ValueIterator(const Value::ObjectValues::iterator& current);
876 
877 public:
878  SelfType& operator=(const SelfType& other);
879 
881  SelfType temp(*this);
882  ++*this;
883  return temp;
884  }
885 
887  SelfType temp(*this);
888  --*this;
889  return temp;
890  }
891 
893  decrement();
894  return *this;
895  }
896 
898  increment();
899  return *this;
900  }
901 
902  reference operator*() const { return deref(); }
903 
904  pointer operator->() const { return &deref(); }
905 };
906 
907 inline void swap(Value& a, Value& b) { a.swap(b); }
908 
909 } // namespace Json
910 
911 #pragma pack(pop)
912 
913 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
914 #pragma warning(pop)
915 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
916 
917 #endif // CPPTL_JSON_H_INCLUDED
#define JSONCPP_DEPRECATED(message)
Definition: config.h:114
Int64 LargestInt
Definition: config.h:148
std::vector< String > Members
Definition: value.h:193
difference_type computeDistance(const SelfType &other) const
#define JSON_API
If defined, indicates that the source file is amalgamated to prevent private header inclusion...
Definition: config.h:61
static const Int64 maxInt64
Maximum signed 64 bits int value that can be stored in a Json::Value.
Definition: value.h:233
unsigned int ArrayIndex
Definition: forwards.h:29
bool operator!=(const SelfType &other) const
Definition: value.h:748
PrecisionType
Type of precision for formatting of real values.
Definition: value.h:119
base class for Value iterators.
Definition: value.h:739
array value (ordered list)
Definition: value.h:105
unsigned __int64 UInt64
Definition: config.h:143
reference operator*() const
Definition: value.h:850
unsigned integer value
Definition: value.h:101
bool operator==(const SelfType &other) const
Definition: value.h:746
Json::ArrayIndex ArrayIndex
Definition: value.h:204
Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
Definition: value.h:85
void setComment(const char *comment, size_t len, CommentPlacement placement)
Comments must be //... or /* ... */.
Definition: value.h:590
const Value value_type
Definition: value.h:810
object value (collection of name/value pairs).
Definition: value.h:106
static const Int maxInt
Maximum signed int value that can be stored in a Json::Value.
Definition: value.h:225
static const Value & null
We regret this reference to a global instance; prefer the simpler Value().
Definition: value.h:209
Lightweight wrapper to tag static string.
Definition: value.h:143
static const UInt maxUInt
Maximum unsigned int value that can be stored in a Json::Value.
Definition: value.h:227
pointer operator->() const
Definition: value.h:852
Json::LargestUInt LargestUInt
Definition: value.h:203
pointer operator->() const
Definition: value.h:904
const iterator for object and array value.
Definition: value.h:806
unsigned int size_t
Definition: value.h:862
#define JSONCPP_NORETURN
Definition: value.h:32
Experimental and untested: represents an element of the "path" to access a node.
Definition: value.h:680
static const LargestInt minLargestInt
Minimum signed integer value that can be stored in a Json::Value.
Definition: value.h:216
SelfType & operator--()
Definition: value.h:840
&#39;null&#39; value
Definition: value.h:99
CommentPlacement
Definition: value.h:109
SelfType & operator--()
Definition: value.h:892
Value value_type
Definition: value.h:861
StaticString(const char *czstring)
Definition: value.h:145
#define JSONCPP_NOEXCEPT
Definition: config.h:92
std::string value_type
Definition: value.h:207
ValueConstIterator SelfType
Definition: value.h:815
UInt64 LargestUInt
Definition: config.h:149
void swap(Value &a, Value &b)
Definition: value.h:907
unsigned int value_type_
Definition: value.h:649
ValueConstIterator const_iterator
Definition: value.h:195
JSON (JavaScript Object Notation).
Definition: allocator.h:14
ValueIteratorBase SelfType
Definition: value.h:744
bool operator==(const SecureAllocator< T > &, const SecureAllocator< U > &)
Definition: allocator.h:76
Json::Int64 Int64
Definition: value.h:200
ValueIterator SelfType
Definition: value.h:866
we set max number of digits after "." in string
Definition: value.h:121
void swap(Value &other)
Swap everything.
Definition: json_value.cpp:496
Experimental and untested: represents a "path" to access a node.
Definition: value.h:707
SelfType operator--(int)
Definition: value.h:834
Json::LargestInt LargestInt
Definition: value.h:202
static const UInt64 maxUInt64
Maximum unsigned 64 bits int value that can be stored in a Json::Value.
Definition: value.h:235
const char * c_str() const
Definition: value.h:149
double value
Definition: value.h:102
SelfType operator--(int)
Definition: value.h:886
Json::UInt UInt
Definition: value.h:196
SelfType & operator++()
Definition: value.h:897
Json::UInt64 UInt64
Definition: value.h:199
Json::Int Int
Definition: value.h:197
Value * pointer
Definition: value.h:865
Represents a JSON value.
Definition: value.h:189
std::bidirectional_iterator_tag iterator_category
Definition: value.h:741
reference operator*() const
Definition: value.h:902
ValueIterator iterator
Definition: value.h:194
const Value * pointer
Definition: value.h:814
static const Int minInt
Minimum signed int value that can be stored in a Json::Value.
Definition: value.h:223
static const UInt defaultRealPrecision
Default precision for real value for string representation.
Definition: value.h:239
Exceptions which the user cannot easily avoid.
Definition: value.h:74
const Value & reference
Definition: value.h:813
a comment on the line after a value (only make sense for
Definition: value.h:112
unsigned int UInt
Definition: config.h:134
we set max number of significant digits in string
Definition: value.h:120
Iterator for object and array value.
Definition: value.h:857
SelfType & operator++()
Definition: value.h:845
#define JSONCPP_OP_EXPLICIT
Definition: config.h:93
__int64 Int64
Definition: config.h:142
SelfType operator++(int)
Definition: value.h:828
difference_type operator-(const SelfType &other) const
Definition: value.h:750
ValueType
Type of the value held by a Value object.
Definition: value.h:98
bool value
Definition: value.h:104
signed integer value
Definition: value.h:100
String msg_
Definition: value.h:65
SelfType operator++(int)
Definition: value.h:880
unsigned int size_t
Definition: value.h:742
bool operator!=(const SecureAllocator< T > &, const SecureAllocator< U > &)
Definition: allocator.h:81
int Int
Definition: config.h:133
a comment placed on the line before a value
Definition: value.h:110
UTF-8 string value.
Definition: value.h:103
a comment just after a value on the same line
Definition: value.h:111
unsigned int allocated_
Definition: value.h:651
Base class for all exceptions we throw.
Definition: value.h:58
Value & reference
Definition: value.h:864
std::basic_string< char, std::char_traits< char >, Allocator< char > > String
Definition: config.h:157
static const LargestInt maxLargestInt
Maximum signed integer value that can be stored in a Json::Value.
Definition: value.h:218
static const LargestUInt maxLargestUInt
Maximum unsigned integer value that can be stored in a Json::Value.
Definition: value.h:220