• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 JSON_H_INCLUDED
7 #define JSON_H_INCLUDED
8 
9 #if !defined(JSON_IS_AMALGAMATION)
10 #include "forwards.h"
11 #endif // if !defined(JSON_IS_AMALGAMATION)
12 
13 // Conditional NORETURN attribute on the throw functions would:
14 // a) suppress false positives from static code analysis
15 // b) possibly improve optimization opportunities.
16 // For compatibility, [[noreturn]] is not used
17 #if !defined(JSONCPP_NORETURN)
18 #if defined(_MSC_VER)
19 #define JSONCPP_NORETURN __declspec(noreturn)
20 #elif defined(__GNUC__) || defined(__clang__)
21 #define JSONCPP_NORETURN __attribute__((noreturn))
22 #else
23 #define JSONCPP_NORETURN
24 #endif
25 #endif // if !defined(JSONCPP_NORETURN)
26 
27 // Support for '= delete' with template declarations was a late addition
28 // to the c++11 standard and is rejected by clang 3.8 and Apple clang 8.2
29 // even though these declare themselves to be c++11 compilers.
30 #if !defined(JSONCPP_TEMPLATE_DELETE)
31 #if defined(__clang__) && defined(__apple_build_version__)
32 #if __apple_build_version__ <= 8000042
33 #define JSONCPP_TEMPLATE_DELETE
34 #endif
35 #elif defined(__clang__)
36 #if __clang_major__ == 3 && __clang_minor__ <= 8
37 #define JSONCPP_TEMPLATE_DELETE
38 #endif
39 #endif
40 #if !defined(JSONCPP_TEMPLATE_DELETE)
41 #define JSONCPP_TEMPLATE_DELETE = delete
42 #endif
43 #endif
44 
45 #if JSONCPP_CXX_STD_11
46 #else
47 #undef JSONCPP_TEMPLATE_DELETE
48 #define JSONCPP_TEMPLATE_DELETE
49 #include <string.h>
50 #endif
51 
52 #include <exception>
53 #include <map>
54 #include <string>
55 #include <vector>
56 
57 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
58 // be used by...
59 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
60 #pragma warning(push)
61 #pragma warning(disable : 4251)
62 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
63 
64 #pragma pack(push, 8)
65 
66 /** \brief JSON (JavaScript Object Notation).
67  */
68 namespace Json {
69 
70 #if JSON_USE_EXCEPTION
71 /** Base class for all exceptions we throw.
72  *
73  * We use nothing but these internally. Of course, STL can throw others.
74  */
75 class JSON_API Exception : public std::exception {
76 public:
77   Exception(String msg);
78   ~Exception() JSONCPP_NOEXCEPT JSONCPP_OVERRIDE;
79   char const* what() const JSONCPP_NOEXCEPT JSONCPP_OVERRIDE;
80 
81 protected:
82   String msg_;
83 };
84 
85 /** Exceptions which the user cannot easily avoid.
86  *
87  * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
88  *
89  * \remark derived from Json::Exception
90  */
91 class JSON_API RuntimeError : public Exception {
92 public:
93   RuntimeError(String const& msg);
94 };
95 
96 /** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
97  *
98  * These are precondition-violations (user bugs) and internal errors (our bugs).
99  *
100  * \remark derived from Json::Exception
101  */
102 class JSON_API LogicError : public Exception {
103 public:
104   LogicError(String const& msg);
105 };
106 #endif
107 
108 /// used internally
109 JSONCPP_NORETURN void throwRuntimeError(String const& msg);
110 /// used internally
111 JSONCPP_NORETURN void throwLogicError(String const& msg);
112 
113 /** \brief Type of the value held by a Value object.
114  */
115 enum ValueType {
116   nullValue = 0, ///< 'null' value
117   intValue,      ///< signed integer value
118   uintValue,     ///< unsigned integer value
119   realValue,     ///< double value
120   stringValue,   ///< UTF-8 string value
121   booleanValue,  ///< bool value
122   arrayValue,    ///< array value (ordered list)
123   objectValue    ///< object value (collection of name/value pairs).
124 };
125 
126 enum CommentPlacement {
127   commentBefore = 0,      ///< a comment placed on the line before a value
128   commentAfterOnSameLine, ///< a comment just after a value on the same line
129   commentAfter, ///< a comment on the line after a value (only make sense for
130   /// root value)
131   numberOfCommentPlacement
132 };
133 
134 /** \brief Type of precision for formatting of real values.
135  */
136 enum PrecisionType {
137   significantDigits = 0, ///< we set max number of significant digits in string
138   decimalPlaces          ///< we set max number of digits after "." in string
139 };
140 
141 /** \brief Lightweight wrapper to tag static string.
142  *
143  * Value constructor and objectValue member assignment takes advantage of the
144  * StaticString and avoid the cost of string duplication when storing the
145  * string or the member name.
146  *
147  * Example of usage:
148  * \code
149  * Json::Value aValue( StaticString("some text") );
150  * Json::Value object;
151  * static const StaticString code("code");
152  * object[code] = 1234;
153  * \endcode
154  */
155 class JSON_API StaticString {
156 public:
StaticString(const char * czstring)157   JSONCPP_OP_EXPLICIT StaticString(const char* czstring) : c_str_(czstring) {}
158 
159   operator const char*() const { return c_str_; }
160 
c_str()161   const char* c_str() const { return c_str_; }
162 
163 private:
164   const char* c_str_;
165 };
166 
167 /** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
168  *
169  * This class is a discriminated union wrapper that can represents a:
170  * - signed integer [range: Value::minInt - Value::maxInt]
171  * - unsigned integer (range: 0 - Value::maxUInt)
172  * - double
173  * - UTF-8 string
174  * - boolean
175  * - 'null'
176  * - an ordered list of Value
177  * - collection of name/value pairs (javascript object)
178  *
179  * The type of the held value is represented by a #ValueType and
180  * can be obtained using type().
181  *
182  * Values of an #objectValue or #arrayValue can be accessed using operator[]()
183  * methods.
184  * Non-const methods will automatically create the a #nullValue element
185  * if it does not exist.
186  * The sequence of an #arrayValue will be automatically resized and initialized
187  * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
188  *
189  * The get() methods can be used to obtain default value in the case the
190  * required element does not exist.
191  *
192  * It is possible to iterate over the list of member keys of an object using
193  * the getMemberNames() method.
194  *
195  * \note #Value string-length fit in size_t, but keys must be < 2^30.
196  * (The reason is an implementation detail.) A #CharReader will raise an
197  * exception if a bound is exceeded to avoid security holes in your app,
198  * but the Value API does *not* check bounds. That is the responsibility
199  * of the caller.
200  */
201 class JSON_API Value {
202   friend class ValueIteratorBase;
203 
204 public:
205   typedef std::vector<String> Members;
206   typedef ValueIterator iterator;
207   typedef ValueConstIterator const_iterator;
208   typedef Json::UInt UInt;
209   typedef Json::Int Int;
210 #if defined(JSON_HAS_INT64)
211   typedef Json::UInt64 UInt64;
212   typedef Json::Int64 Int64;
213 #endif // defined(JSON_HAS_INT64)
214   typedef Json::LargestInt LargestInt;
215   typedef Json::LargestUInt LargestUInt;
216   typedef Json::ArrayIndex ArrayIndex;
217 
218   // Required for boost integration, e. g. BOOST_TEST
219   typedef std::string value_type;
220 
221 #if JSON_USE_NULLREF
222   // Binary compatibility kludges, do not use.
223   static const Value& null;
224   static const Value& nullRef;
225 #endif
226 
227   // null and nullRef are deprecated, use this instead.
228   static Value const& nullSingleton();
229 
230   /// Minimum signed integer value that can be stored in a Json::Value.
231   static JSONCPP_CONST LargestInt minLargestInt =
232       LargestInt(~(LargestUInt(-1) / 2));
233   /// Maximum signed integer value that can be stored in a Json::Value.
234   static JSONCPP_CONST LargestInt maxLargestInt =
235       LargestInt(LargestUInt(-1) / 2);
236   /// Maximum unsigned integer value that can be stored in a Json::Value.
237   static JSONCPP_CONST LargestUInt maxLargestUInt = LargestUInt(-1);
238 
239   /// Minimum signed int value that can be stored in a Json::Value.
240   static JSONCPP_CONST Int minInt = Int(~(UInt(-1) / 2));
241   /// Maximum signed int value that can be stored in a Json::Value.
242   static JSONCPP_CONST Int maxInt = Int(UInt(-1) / 2);
243   /// Maximum unsigned int value that can be stored in a Json::Value.
244   static JSONCPP_CONST UInt maxUInt = UInt(-1);
245 
246 #if defined(JSON_HAS_INT64)
247   /// Minimum signed 64 bits int value that can be stored in a Json::Value.
248   static JSONCPP_CONST Int64 minInt64 = Int64(~(UInt64(-1) / 2));
249   /// Maximum signed 64 bits int value that can be stored in a Json::Value.
250   static JSONCPP_CONST Int64 maxInt64 = Int64(UInt64(-1) / 2);
251   /// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
252   static JSONCPP_CONST UInt64 maxUInt64 = UInt64(-1);
253 #endif // defined(JSON_HAS_INT64)
254   /// Default precision for real value for string representation.
255   static JSONCPP_CONST UInt defaultRealPrecision = 17;
256   // The constant is hard-coded because some compiler have trouble
257   // converting Value::maxUInt64 to a double correctly (AIX/xlC).
258   // Assumes that UInt64 is a 64 bits integer.
259   static JSONCPP_CONST double maxUInt64AsDouble = 18446744073709551615.0;
260 // Workaround for bug in the NVIDIAs CUDA 9.1 nvcc compiler
261 // when using gcc and clang backend compilers.  CZString
262 // cannot be defined as private.  See issue #486
263 #ifdef __NVCC__
264 public:
265 #else
266 private:
267 #endif
268 #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
269   class CZString {
270   public:
271     enum DuplicationPolicy { noDuplication = 0, duplicate, duplicateOnCopy };
272     CZString(ArrayIndex index);
273     CZString(char const* str, unsigned length, DuplicationPolicy allocate);
274     CZString(CZString const& other);
275 #if JSONCPP_CXX_STD_11
276     CZString(CZString&& other);
277 #endif
278     ~CZString();
279     CZString& operator=(const CZString& other);
280 #if JSONCPP_CXX_STD_11
281     CZString& operator=(CZString&& other);
282 #endif
283     bool operator<(CZString const& other) const;
284     bool operator==(CZString const& other) const;
285     ArrayIndex index() const;
286     // const char* c_str() const; ///< \deprecated
287     char const* data() const;
288     unsigned length() const;
289     bool isStaticString() const;
290 
291   private:
292     void swap(CZString& other);
293 
294     struct StringStorage {
295       unsigned policy_ : 2;
296       unsigned length_ : 30; // 1GB max
297     };
298 
299     char const* cstr_; // actually, a prefixed string, unless policy is noDup
300     union {
301       ArrayIndex index_;
302       StringStorage storage_;
303     };
304   };
305 
306 public:
307   typedef std::map<CZString, Value> ObjectValues;
308 #endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
309 
310 public:
311   /**
312    * \brief Create a default Value of the given type.
313    *
314    * This is a very useful constructor.
315    * To create an empty array, pass arrayValue.
316    * To create an empty object, pass objectValue.
317    * Another Value can then be set to this one by assignment.
318    * This is useful since clear() and resize() will not alter types.
319    *
320    * Examples:
321    *   \code
322    *   Json::Value null_value; // null
323    *   Json::Value arr_value(Json::arrayValue); // []
324    *   Json::Value obj_value(Json::objectValue); // {}
325    *   \endcode
326    */
327   Value(ValueType type = nullValue);
328   Value(Int value);
329   Value(UInt value);
330 #if defined(JSON_HAS_INT64)
331   Value(Int64 value);
332   Value(UInt64 value);
333 #endif // if defined(JSON_HAS_INT64)
334   Value(double value);
335   Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.)
336   Value(const char* begin, const char* end); ///< Copy all, incl zeroes.
337   /**
338    * \brief Constructs a value from a static string.
339    *
340    * Like other value string constructor but do not duplicate the string for
341    * internal storage. The given string must remain alive after the call to
342    * this constructor.
343    *
344    * \note This works only for null-terminated strings. (We cannot change the
345    * size of this class, so we have nowhere to store the length, which might be
346    * computed later for various operations.)
347    *
348    * Example of usage:
349    *   \code
350    *   static StaticString foo("some text");
351    *   Json::Value aValue(foo);
352    *   \endcode
353    */
354   Value(const StaticString& value);
355   Value(const String& value);
356   Value(bool value);
357   Value(const Value& other);
358 #if JSONCPP_CXX_STD_11
359   Value(Value&& other);
360 #endif
361   ~Value();
362 
363   /// \note Overwrite existing comments. To preserve comments, use
364   /// #swapPayload().
365   Value& operator=(const Value& other);
366 #if JSONCPP_CXX_STD_11
367   Value& operator=(Value&& other);
368 #endif
369 
370   /// Swap everything.
371   void swap(Value& other);
372   /// Swap values but leave comments and source offsets in place.
373   void swapPayload(Value& other);
374 
375   /// copy everything.
376   void copy(const Value& other);
377   /// copy values but leave comments and source offsets in place.
378   void copyPayload(const Value& other);
379 
380   ValueType type() const;
381 
382   /// Compare payload only, not comments etc.
383   bool operator<(const Value& other) const;
384   bool operator<=(const Value& other) const;
385   bool operator>=(const Value& other) const;
386   bool operator>(const Value& other) const;
387   bool operator==(const Value& other) const;
388   bool operator!=(const Value& other) const;
389   int compare(const Value& other) const;
390 
391   const char* asCString() const; ///< Embedded zeroes could cause you trouble!
392 #if JSONCPP_USING_SECURE_MEMORY
393   unsigned getCStringLength() const; // Allows you to understand the length of
394                                      // the CString
395 #endif
396   String asString() const; ///< Embedded zeroes are possible.
397   /** Get raw char* of string-value.
398    *  \return false if !string. (Seg-fault if str or end are NULL.)
399    */
400   bool getString(char const** begin, char const** end) const;
401   Int asInt() const;
402   UInt asUInt() const;
403 #if defined(JSON_HAS_INT64)
404   Int64 asInt64() const;
405   UInt64 asUInt64() const;
406 #endif // if defined(JSON_HAS_INT64)
407   LargestInt asLargestInt() const;
408   LargestUInt asLargestUInt() const;
409   float asFloat() const;
410   double asDouble() const;
411   bool asBool() const;
412 
413   bool isNull() const;
414   bool isBool() const;
415   bool isInt() const;
416   bool isInt64() const;
417   bool isUInt() const;
418   bool isUInt64() const;
419   bool isIntegral() const;
420   bool isDouble() const;
421   bool isNumeric() const;
422   bool isString() const;
423   bool isArray() const;
424   bool isObject() const;
425 
426   /// The `as<T>` and `is<T>` member function templates and specializations.
427   template <typename T> T as() const JSONCPP_TEMPLATE_DELETE;
428   template <typename T> bool is() const JSONCPP_TEMPLATE_DELETE;
429 
430   bool isConvertibleTo(ValueType other) const;
431 
432   /// Number of values in array or object
433   ArrayIndex size() const;
434 
435   /// \brief Return true if empty array, empty object, or null;
436   /// otherwise, false.
437   bool empty() const;
438 
439   /// Return !isNull()
440   JSONCPP_OP_EXPLICIT operator bool() const;
441 
442   /// Remove all object members and array elements.
443   /// \pre type() is arrayValue, objectValue, or nullValue
444   /// \post type() is unchanged
445   void clear();
446 
447   /// Resize the array to newSize elements.
448   /// New elements are initialized to null.
449   /// May only be called on nullValue or arrayValue.
450   /// \pre type() is arrayValue or nullValue
451   /// \post type() is arrayValue
452   void resize(ArrayIndex newSize);
453 
454   //@{
455   /// Access an array element (zero based index). If the array contains less
456   /// than index element, then null value are inserted in the array so that
457   /// its size is index+1.
458   /// (You may need to say 'value[0u]' to get your compiler to distinguish
459   /// this from the operator[] which takes a string.)
460   Value& operator[](ArrayIndex index);
461   Value& operator[](int index);
462   //@}
463 
464   //@{
465   /// Access an array element (zero based index).
466   /// (You may need to say 'value[0u]' to get your compiler to distinguish
467   /// this from the operator[] which takes a string.)
468   const Value& operator[](ArrayIndex index) const;
469   const Value& operator[](int index) const;
470   //@}
471 
472   /// If the array contains at least index+1 elements, returns the element
473   /// value, otherwise returns defaultValue.
474   Value get(ArrayIndex index, const Value& defaultValue) const;
475   /// Return true if index < size().
476   bool isValidIndex(ArrayIndex index) const;
477   /// \brief Append value to array at the end.
478   ///
479   /// Equivalent to jsonvalue[jsonvalue.size()] = value;
480   Value& append(const Value& value);
481 #if JSONCPP_CXX_STD_11
482   Value& append(Value&& value);
483 #endif
484 
485   /// \brief Insert value in array at specific index
486   bool insert(ArrayIndex index, const Value& newValue);
487 #if JSONCPP_CXX_STD_11
488   bool insert(ArrayIndex index, Value&& newValue);
489 #endif
490 
491   /// Access an object value by name, create a null member if it does not exist.
492   /// \note Because of our implementation, keys are limited to 2^30 -1 chars.
493   /// Exceeding that will cause an exception.
494   Value& operator[](const char* key);
495   /// Access an object value by name, returns null if there is no member with
496   /// that name.
497   const Value& operator[](const char* key) const;
498   /// Access an object value by name, create a null member if it does not exist.
499   /// \param key may contain embedded nulls.
500   Value& operator[](const String& key);
501   /// Access an object value by name, returns null if there is no member with
502   /// that name.
503   /// \param key may contain embedded nulls.
504   const Value& operator[](const String& key) const;
505   /** \brief Access an object value by name, create a null member if it does not
506    * exist.
507    *
508    * If the object has no entry for that name, then the member name used to
509    * store the new entry is not duplicated.
510    * Example of use:
511    *   \code
512    *   Json::Value object;
513    *   static const StaticString code("code");
514    *   object[code] = 1234;
515    *   \endcode
516    */
517   Value& operator[](const StaticString& key);
518   /// Return the member named key if it exist, defaultValue otherwise.
519   /// \note deep copy
520   Value get(const char* key, const Value& defaultValue) const;
521   /// Return the member named key if it exist, defaultValue otherwise.
522   /// \note deep copy
523   /// \note key may contain embedded nulls.
524   Value get(const char* begin, const char* end,
525             const Value& defaultValue) const;
526   /// Return the member named key if it exist, defaultValue otherwise.
527   /// \note deep copy
528   /// \param key may contain embedded nulls.
529   Value get(const String& key, const Value& defaultValue) const;
530   /// Most general and efficient version of isMember()const, get()const,
531   /// and operator[]const
532   /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
533   Value const* find(char const* begin, char const* end) const;
534   /// Most general and efficient version of object-mutators.
535   /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
536   /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
537   Value* demand(char const* begin, char const* end);
538   /// \brief Remove and return the named member.
539   ///
540   /// Do nothing if it did not exist.
541   /// \pre type() is objectValue or nullValue
542   /// \post type() is unchanged
543   void removeMember(const char* key);
544   /// Same as removeMember(const char*)
545   /// \param key may contain embedded nulls.
546   void removeMember(const String& key);
547   /// Same as removeMember(const char* begin, const char* end, Value* removed),
548   /// but 'key' is null-terminated.
549   bool removeMember(const char* key, Value* removed);
550   /** \brief Remove the named map member.
551    *
552    *  Update 'removed' iff removed.
553    *  \param key may contain embedded nulls.
554    *  \return true iff removed (no exceptions)
555    */
556   bool removeMember(String const& key, Value* removed);
557   /// Same as removeMember(String const& key, Value* removed)
558   bool removeMember(const char* begin, const char* end, Value* removed);
559   /** \brief Remove the indexed array element.
560    *
561    *  O(n) expensive operations.
562    *  Update 'removed' iff removed.
563    *  \return true if removed (no exceptions)
564    */
565   bool removeIndex(ArrayIndex index, Value* removed);
566 
567   /// Return true if the object has a member named key.
568   /// \note 'key' must be null-terminated.
569   bool isMember(const char* key) const;
570   /// Return true if the object has a member named key.
571   /// \param key may contain embedded nulls.
572   bool isMember(const String& key) const;
573   /// Same as isMember(String const& key)const
574   bool isMember(const char* begin, const char* end) const;
575 
576   /// \brief Return a list of the member names.
577   ///
578   /// If null, return an empty list.
579   /// \pre type() is objectValue or nullValue
580   /// \post if type() was nullValue, it remains nullValue
581   Members getMemberNames() const;
582 
583   /// \deprecated Always pass len.
584   JSONCPP_DEPRECATED("Use setComment(String const&) instead.")
585   void setComment(const char* comment, CommentPlacement placement);
586   /// Comments must be //... or /* ... */
587   void setComment(const char* comment, size_t len, CommentPlacement placement);
588   /// Comments must be //... or /* ... */
589   void setComment(const String& comment, CommentPlacement placement);
590   bool hasComment(CommentPlacement placement) const;
591   /// Include delimiters and embedded newlines.
592   String getComment(CommentPlacement placement) const;
593 
594   String toStyledString() const;
595 
596   const_iterator begin() const;
597   const_iterator end() const;
598 
599   iterator begin();
600   iterator end();
601 
602   // Accessors for the [start, limit) range of bytes within the JSON text from
603   // which this value was parsed, if any.
604   void setOffsetStart(ptrdiff_t start);
605   void setOffsetLimit(ptrdiff_t limit);
606   ptrdiff_t getOffsetStart() const;
607   ptrdiff_t getOffsetLimit() const;
608 
609 private:
setType(ValueType v)610   void setType(ValueType v) {
611     bits_.value_type_ = static_cast<unsigned char>(v);
612   }
isAllocated()613   bool isAllocated() const { return bits_.allocated_; }
setIsAllocated(bool v)614   void setIsAllocated(bool v) { bits_.allocated_ = v; }
615 
616   void initBasic(ValueType type, bool allocated = false);
617   void dupPayload(const Value& other);
618   void releasePayload();
619   void dupMeta(const Value& other);
620 
621   Value& resolveReference(const char* key);
622   Value& resolveReference(const char* key, const char* end);
623 
624   // struct MemberNamesTransform
625   //{
626   //   typedef const char *result_type;
627   //   const char *operator()( const CZString &name ) const
628   //   {
629   //      return name.c_str();
630   //   }
631   //};
632 
633   union ValueHolder {
634     LargestInt int_;
635     LargestUInt uint_;
636     double real_;
637     bool bool_;
638     char* string_; // if allocated_, ptr to { unsigned, char[] }.
639     ObjectValues* map_;
640   } value_;
641 
642   struct {
643     // Really a ValueType, but types should agree for bitfield packing.
644     unsigned int value_type_ : 8;
645     // Unless allocated_, string_ must be null-terminated.
646     unsigned int allocated_ : 1;
647   } bits_;
648 
649   class Comments {
650   public:
Comments()651     Comments() {}
652     Comments(const Comments& that);
653     Comments& operator=(const Comments& that);
654     bool has(CommentPlacement slot) const;
655     String get(CommentPlacement slot) const;
656     void set(CommentPlacement slot, String s);
657 
658   private:
659     String ptr_[numberOfCommentPlacement];
660   };
661   Comments comments_;
662 
663   // [start, limit) byte offsets in the source JSON text from which this Value
664   // was extracted.
665   ptrdiff_t start_;
666   ptrdiff_t limit_;
667 };
668 
669 template <> inline bool Value::as<bool>() const { return asBool(); }
670 template <> inline bool Value::is<bool>() const { return isBool(); }
671 
672 template <> inline Int Value::as<Int>() const { return asInt(); }
673 template <> inline bool Value::is<Int>() const { return isInt(); }
674 
675 template <> inline UInt Value::as<UInt>() const { return asUInt(); }
676 template <> inline bool Value::is<UInt>() const { return isUInt(); }
677 
678 #if defined(JSON_HAS_INT64)
679 template <> inline Int64 Value::as<Int64>() const { return asInt64(); }
680 template <> inline bool Value::is<Int64>() const { return isInt64(); }
681 
682 template <> inline UInt64 Value::as<UInt64>() const { return asUInt64(); }
683 template <> inline bool Value::is<UInt64>() const { return isUInt64(); }
684 #endif
685 
686 template <> inline double Value::as<double>() const { return asDouble(); }
687 template <> inline bool Value::is<double>() const { return isDouble(); }
688 
689 template <> inline String Value::as<String>() const { return asString(); }
690 template <> inline bool Value::is<String>() const { return isString(); }
691 
692 /// These `as` specializations are type conversions, and do not have a
693 /// corresponding `is`.
694 template <> inline float Value::as<float>() const { return asFloat(); }
695 template <> inline const char* Value::as<const char*>() const {
696   return asCString();
697 }
698 
699 /** \brief Experimental and untested: represents an element of the "path" to
700  * access a node.
701  */
702 class JSON_API PathArgument {
703 public:
704   friend class Path;
705 
706   PathArgument();
707   PathArgument(ArrayIndex index);
708   PathArgument(const char* key);
709   PathArgument(String key);
710 
711 private:
712   enum Kind { kindNone = 0, kindIndex, kindKey };
713   String key_;
714   ArrayIndex index_;
715   Kind kind_;
716 };
717 
718 /** \brief Experimental and untested: represents a "path" to access a node.
719  *
720  * Syntax:
721  * - "." => root node
722  * - ".[n]" => elements at index 'n' of root node (an array value)
723  * - ".name" => member named 'name' of root node (an object value)
724  * - ".name1.name2.name3"
725  * - ".[0][1][2].name1[3]"
726  * - ".%" => member name is provided as parameter
727  * - ".[%]" => index is provided as parameter
728  */
729 class JSON_API Path {
730 public:
731   Path(const String& path, const PathArgument& a1 = PathArgument(),
732        const PathArgument& a2 = PathArgument(),
733        const PathArgument& a3 = PathArgument(),
734        const PathArgument& a4 = PathArgument(),
735        const PathArgument& a5 = PathArgument());
736 
737   const Value& resolve(const Value& root) const;
738   Value resolve(const Value& root, const Value& defaultValue) const;
739   /// Creates the "path" to access the specified node and returns a reference on
740   /// the node.
741   Value& make(Value& root) const;
742 
743 private:
744   typedef std::vector<const PathArgument*> InArgs;
745   typedef std::vector<PathArgument> Args;
746 
747   void makePath(const String& path, const InArgs& in);
748   void addPathInArg(const String& path, const InArgs& in,
749                     InArgs::const_iterator& itInArg, PathArgument::Kind kind);
750   static void invalidPath(const String& path, int location);
751 
752   Args args_;
753 };
754 
755 /** \brief base class for Value iterators.
756  *
757  */
758 class JSON_API ValueIteratorBase {
759 public:
760   typedef std::bidirectional_iterator_tag iterator_category;
761   typedef unsigned int size_t;
762   typedef int difference_type;
763   typedef ValueIteratorBase SelfType;
764 
765   bool operator==(const SelfType& other) const { return isEqual(other); }
766 
767   bool operator!=(const SelfType& other) const { return !isEqual(other); }
768 
769   difference_type operator-(const SelfType& other) const {
770     return other.computeDistance(*this);
771   }
772 
773   /// Return either the index or the member name of the referenced value as a
774   /// Value.
775   Value key() const;
776 
777   /// Return the index of the referenced Value, or -1 if it is not an
778   /// arrayValue.
779   UInt index() const;
780 
781   /// Return the member name of the referenced Value, or "" if it is not an
782   /// objectValue.
783   /// \note Avoid `c_str()` on result, as embedded zeroes are possible.
784   String name() const;
785 
786   /// Return the member name of the referenced Value. "" if it is not an
787   /// objectValue.
788   /// \deprecated This cannot be used for UTF-8 strings, since there can be
789   /// embedded nulls.
790   JSONCPP_DEPRECATED("Use `key = name();` instead.")
791   char const* memberName() const;
792   /// Return the member name of the referenced Value, or NULL if it is not an
793   /// objectValue.
794   /// \note Better version than memberName(). Allows embedded nulls.
795   char const* memberName(char const** end) const;
796 
797 protected:
798   /*! Internal utility functions to assist with implementing
799    *   other iterator functions. The const and non-const versions
800    *   of the "deref" protected methods expose the protected
801    *   current_ member variable in a way that can often be
802    *   optimized away by the compiler.
803    */
804   const Value& deref() const;
805   Value& deref();
806 
807   void increment();
808 
809   void decrement();
810 
811   difference_type computeDistance(const SelfType& other) const;
812 
813   bool isEqual(const SelfType& other) const;
814 
815   void copy(const SelfType& other);
816 
817 private:
818   Value::ObjectValues::iterator current_;
819   // Indicates that iterator is for a null value.
820   bool isNull_;
821 
822 public:
823   // For some reason, BORLAND needs these at the end, rather
824   // than earlier. No idea why.
825   ValueIteratorBase();
826   JSONCPP_OP_EXPLICIT
827   ValueIteratorBase(const Value::ObjectValues::iterator& current);
828 };
829 
830 /** \brief const iterator for object and array value.
831  *
832  */
833 class JSON_API ValueConstIterator : public ValueIteratorBase {
834   friend class Value;
835 
836 public:
837   typedef const Value value_type;
838   // typedef unsigned int size_t;
839   // typedef int difference_type;
840   typedef const Value& reference;
841   typedef const Value* pointer;
842   typedef ValueConstIterator SelfType;
843 
844   ValueConstIterator();
845   ValueConstIterator(ValueIterator const& other);
846 
847 private:
848   /*! \internal Use by Value to create an iterator.
849    */
850   JSONCPP_OP_EXPLICIT
851   ValueConstIterator(const Value::ObjectValues::iterator& current);
852 
853 public:
854   SelfType& operator=(const ValueIteratorBase& other);
855 
856   SelfType operator++(int) {
857     SelfType temp(*this);
858     ++*this;
859     return temp;
860   }
861 
862   SelfType operator--(int) {
863     SelfType temp(*this);
864     --*this;
865     return temp;
866   }
867 
868   SelfType& operator--() {
869     decrement();
870     return *this;
871   }
872 
873   SelfType& operator++() {
874     increment();
875     return *this;
876   }
877 
878   reference operator*() const { return deref(); }
879 
880   pointer operator->() const { return &deref(); }
881 };
882 
883 /** \brief Iterator for object and array value.
884  */
885 class JSON_API ValueIterator : public ValueIteratorBase {
886   friend class Value;
887 
888 public:
889   typedef Value value_type;
890   typedef unsigned int size_t;
891   typedef int difference_type;
892   typedef Value& reference;
893   typedef Value* pointer;
894   typedef ValueIterator SelfType;
895 
896   ValueIterator();
897   JSONCPP_OP_EXPLICIT ValueIterator(const ValueConstIterator& other);
898   ValueIterator(const ValueIterator& other);
899 
900 private:
901   /*! \internal Use by Value to create an iterator.
902    */
903   JSONCPP_OP_EXPLICIT
904   ValueIterator(const Value::ObjectValues::iterator& current);
905 
906 public:
907   SelfType& operator=(const SelfType& other);
908 
909   SelfType operator++(int) {
910     SelfType temp(*this);
911     ++*this;
912     return temp;
913   }
914 
915   SelfType operator--(int) {
916     SelfType temp(*this);
917     --*this;
918     return temp;
919   }
920 
921   SelfType& operator--() {
922     decrement();
923     return *this;
924   }
925 
926   SelfType& operator++() {
927     increment();
928     return *this;
929   }
930 
931   /*! The return value of non-const iterators can be
932    *  changed, so the these functions are not const
933    *  because the returned references/pointers can be used
934    *  to change state of the base class.
935    */
936   reference operator*() { return deref(); }
937   pointer operator->() { return &deref(); }
938 };
939 
swap(Value & a,Value & b)940 inline void swap(Value& a, Value& b) { a.swap(b); }
941 
942 } // namespace Json
943 
944 #pragma pack(pop)
945 
946 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
947 #pragma warning(pop)
948 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
949 
950 #endif // JSON_H_INCLUDED
951