• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /// Json-cpp amalgated header (http://jsoncpp.sourceforge.net/).
2 /// It is intended to be used with #include "json/json.h"
3 
4 // //////////////////////////////////////////////////////////////////////
5 // Beginning of content of file: LICENSE
6 // //////////////////////////////////////////////////////////////////////
7 
8 /*
9 The JsonCpp library's source code, including accompanying documentation,
10 tests and demonstration applications, are licensed under the following
11 conditions...
12 
13 The author (Baptiste Lepilleur) explicitly disclaims copyright in all
14 jurisdictions which recognize such a disclaimer. In such jurisdictions,
15 this software is released into the Public Domain.
16 
17 In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
18 2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
19 released under the terms of the MIT License (see below).
20 
21 In jurisdictions which recognize Public Domain property, the user of this
22 software may choose to accept it either as 1) Public Domain, 2) under the
23 conditions of the MIT License (see below), or 3) under the terms of dual
24 Public Domain/MIT License conditions described here, as they choose.
25 
26 The MIT License is about as close to Public Domain as a license can get, and is
27 described in clear, concise terms at:
28 
29    http://en.wikipedia.org/wiki/MIT_License
30 
31 The full text of the MIT License follows:
32 
33 ========================================================================
34 Copyright (c) 2007-2010 Baptiste Lepilleur
35 
36 Permission is hereby granted, free of charge, to any person
37 obtaining a copy of this software and associated documentation
38 files (the "Software"), to deal in the Software without
39 restriction, including without limitation the rights to use, copy,
40 modify, merge, publish, distribute, sublicense, and/or sell copies
41 of the Software, and to permit persons to whom the Software is
42 furnished to do so, subject to the following conditions:
43 
44 The above copyright notice and this permission notice shall be
45 included in all copies or substantial portions of the Software.
46 
47 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
48 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
49 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
50 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
51 BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
52 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
53 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
54 SOFTWARE.
55 ========================================================================
56 (END LICENSE TEXT)
57 
58 The MIT license is compatible with both the GPL and commercial
59 software, affording one all of the rights of Public Domain with the
60 minor nuisance of being required to keep the above copyright notice
61 and license text in the source code. Note also that by accepting the
62 Public Domain "license" you can re-license your copy using whatever
63 license you like.
64 
65 */
66 
67 // //////////////////////////////////////////////////////////////////////
68 // End of content of file: LICENSE
69 // //////////////////////////////////////////////////////////////////////
70 
71 
72 
73 
74 
75 #ifndef JSON_AMALGATED_H_INCLUDED
76 # define JSON_AMALGATED_H_INCLUDED
77 /// If defined, indicates that the source file is amalgated
78 /// to prevent private header inclusion.
79 #define JSON_IS_AMALGAMATION
80 
81 // //////////////////////////////////////////////////////////////////////
82 // Beginning of content of file: include/json/version.h
83 // //////////////////////////////////////////////////////////////////////
84 
85 // DO NOT EDIT. This file is generated by CMake from  "version"
86 // and "version.h.in" files.
87 // Run CMake configure step to update it.
88 #ifndef JSON_VERSION_H_INCLUDED
89 # define JSON_VERSION_H_INCLUDED
90 
91 # define JSONCPP_VERSION_STRING "1.6.2"
92 # define JSONCPP_VERSION_MAJOR 1
93 # define JSONCPP_VERSION_MINOR 6
94 # define JSONCPP_VERSION_PATCH 2
95 # define JSONCPP_VERSION_QUALIFIER
96 # define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8))
97 
98 #endif // JSON_VERSION_H_INCLUDED
99 
100 // //////////////////////////////////////////////////////////////////////
101 // End of content of file: include/json/version.h
102 // //////////////////////////////////////////////////////////////////////
103 
104 
105 
106 
107 
108 
109 // //////////////////////////////////////////////////////////////////////
110 // Beginning of content of file: include/json/config.h
111 // //////////////////////////////////////////////////////////////////////
112 
113 // Copyright 2007-2010 Baptiste Lepilleur
114 // Distributed under MIT license, or public domain if desired and
115 // recognized in your jurisdiction.
116 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
117 
118 #ifndef JSON_CONFIG_H_INCLUDED
119 #define JSON_CONFIG_H_INCLUDED
120 
121 /// If defined, indicates that json library is embedded in CppTL library.
122 //# define JSON_IN_CPPTL 1
123 
124 /// If defined, indicates that json may leverage CppTL library
125 //#  define JSON_USE_CPPTL 1
126 /// If defined, indicates that cpptl vector based map should be used instead of
127 /// std::map
128 /// as Value container.
129 //#  define JSON_USE_CPPTL_SMALLMAP 1
130 
131 // If non-zero, the library uses exceptions to report bad input instead of C
132 // assertion macros. The default is to use exceptions.
133 #ifndef JSON_USE_EXCEPTION
134 #define JSON_USE_EXCEPTION 1
135 #endif
136 
137 /// If defined, indicates that the source file is amalgated
138 /// to prevent private header inclusion.
139 /// Remarks: it is automatically defined in the generated amalgated header.
140 // #define JSON_IS_AMALGAMATION
141 
142 #ifdef JSON_IN_CPPTL
143 #include <cpptl/config.h>
144 #ifndef JSON_USE_CPPTL
145 #define JSON_USE_CPPTL 1
146 #endif
147 #endif
148 
149 #ifdef JSON_IN_CPPTL
150 #define JSON_API CPPTL_API
151 #elif defined(JSON_DLL_BUILD)
152 #if defined(_MSC_VER)
153 #define JSON_API __declspec(dllexport)
154 #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
155 #endif // if defined(_MSC_VER)
156 #elif defined(JSON_DLL)
157 #if defined(_MSC_VER)
158 #define JSON_API __declspec(dllimport)
159 #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
160 #endif // if defined(_MSC_VER)
161 #endif // ifdef JSON_IN_CPPTL
162 #if !defined(JSON_API)
163 #define JSON_API
164 #endif
165 
166 // If JSON_NO_INT64 is defined, then Json only support C++ "int" type for
167 // integer
168 // Storages, and 64 bits integer support is disabled.
169 // #define JSON_NO_INT64 1
170 
171 #if defined(_MSC_VER) && _MSC_VER <= 1200 // MSVC 6
172 // Microsoft Visual Studio 6 only support conversion from __int64 to double
173 // (no conversion from unsigned __int64).
174 #define JSON_USE_INT64_DOUBLE_CONVERSION 1
175 // Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255'
176 // characters in the debug information)
177 // All projects I've ever seen with VS6 were using this globally (not bothering
178 // with pragma push/pop).
179 #pragma warning(disable : 4786)
180 #endif // if defined(_MSC_VER)  &&  _MSC_VER < 1200 // MSVC 6
181 
182 #if defined(_MSC_VER) && _MSC_VER >= 1500 // MSVC 2008
183 /// Indicates that the following function is deprecated.
184 #define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
185 #elif defined(__clang__) && defined(__has_feature)
186 #if __has_feature(attribute_deprecated_with_message)
187 #define JSONCPP_DEPRECATED(message)  __attribute__ ((deprecated(message)))
188 #endif
189 #elif defined(__GNUC__) &&  (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
190 #define JSONCPP_DEPRECATED(message)  __attribute__ ((deprecated(message)))
191 #elif defined(__GNUC__) &&  (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
192 #define JSONCPP_DEPRECATED(message)  __attribute__((__deprecated__))
193 #endif
194 
195 #if !defined(JSONCPP_DEPRECATED)
196 #define JSONCPP_DEPRECATED(message)
197 #endif // if !defined(JSONCPP_DEPRECATED)
198 
199 namespace Json {
200 typedef int Int;
201 typedef unsigned int UInt;
202 #if defined(JSON_NO_INT64)
203 typedef int LargestInt;
204 typedef unsigned int LargestUInt;
205 #undef JSON_HAS_INT64
206 #else                 // if defined(JSON_NO_INT64)
207 // For Microsoft Visual use specific types as long long is not supported
208 #if defined(_MSC_VER) // Microsoft Visual Studio
209 typedef __int64 Int64;
210 typedef unsigned __int64 UInt64;
211 #else                 // if defined(_MSC_VER) // Other platforms, use long long
212 typedef long long int Int64;
213 typedef unsigned long long int UInt64;
214 #endif // if defined(_MSC_VER)
215 typedef Int64 LargestInt;
216 typedef UInt64 LargestUInt;
217 #define JSON_HAS_INT64
218 #endif // if defined(JSON_NO_INT64)
219 } // end namespace Json
220 
221 #endif // JSON_CONFIG_H_INCLUDED
222 
223 // //////////////////////////////////////////////////////////////////////
224 // End of content of file: include/json/config.h
225 // //////////////////////////////////////////////////////////////////////
226 
227 
228 
229 
230 
231 
232 // //////////////////////////////////////////////////////////////////////
233 // Beginning of content of file: include/json/forwards.h
234 // //////////////////////////////////////////////////////////////////////
235 
236 // Copyright 2007-2010 Baptiste Lepilleur
237 // Distributed under MIT license, or public domain if desired and
238 // recognized in your jurisdiction.
239 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
240 
241 #ifndef JSON_FORWARDS_H_INCLUDED
242 #define JSON_FORWARDS_H_INCLUDED
243 
244 #if !defined(JSON_IS_AMALGAMATION)
245 #include "config.h"
246 #endif // if !defined(JSON_IS_AMALGAMATION)
247 
248 namespace Json {
249 
250 // writer.h
251 class FastWriter;
252 class StyledWriter;
253 
254 // reader.h
255 class Reader;
256 
257 // features.h
258 class Features;
259 
260 // value.h
261 typedef unsigned int ArrayIndex;
262 class StaticString;
263 class Path;
264 class PathArgument;
265 class Value;
266 class ValueIteratorBase;
267 class ValueIterator;
268 class ValueConstIterator;
269 
270 } // namespace Json
271 
272 #endif // JSON_FORWARDS_H_INCLUDED
273 
274 // //////////////////////////////////////////////////////////////////////
275 // End of content of file: include/json/forwards.h
276 // //////////////////////////////////////////////////////////////////////
277 
278 
279 
280 
281 
282 
283 // //////////////////////////////////////////////////////////////////////
284 // Beginning of content of file: include/json/features.h
285 // //////////////////////////////////////////////////////////////////////
286 
287 // Copyright 2007-2010 Baptiste Lepilleur
288 // Distributed under MIT license, or public domain if desired and
289 // recognized in your jurisdiction.
290 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
291 
292 #ifndef CPPTL_JSON_FEATURES_H_INCLUDED
293 #define CPPTL_JSON_FEATURES_H_INCLUDED
294 
295 #if !defined(JSON_IS_AMALGAMATION)
296 #include "forwards.h"
297 #endif // if !defined(JSON_IS_AMALGAMATION)
298 
299 namespace Json {
300 
301 /** \brief Configuration passed to reader and writer.
302  * This configuration object can be used to force the Reader or Writer
303  * to behave in a standard conforming way.
304  */
305 class JSON_API Features {
306 public:
307   /** \brief A configuration that allows all features and assumes all strings
308    * are UTF-8.
309    * - C & C++ comments are allowed
310    * - Root object can be any JSON value
311    * - Assumes Value strings are encoded in UTF-8
312    */
313   static Features all();
314 
315   /** \brief A configuration that is strictly compatible with the JSON
316    * specification.
317    * - Comments are forbidden.
318    * - Root object must be either an array or an object value.
319    * - Assumes Value strings are encoded in UTF-8
320    */
321   static Features strictMode();
322 
323   /** \brief Initialize the configuration like JsonConfig::allFeatures;
324    */
325   Features();
326 
327   /// \c true if comments are allowed. Default: \c true.
328   bool allowComments_;
329 
330   /// \c true if root must be either an array or an object value. Default: \c
331   /// false.
332   bool strictRoot_;
333 
334   /// \c true if dropped null placeholders are allowed. Default: \c false.
335   bool allowDroppedNullPlaceholders_;
336 
337   /// \c true if numeric object key are allowed. Default: \c false.
338   bool allowNumericKeys_;
339 };
340 
341 } // namespace Json
342 
343 #endif // CPPTL_JSON_FEATURES_H_INCLUDED
344 
345 // //////////////////////////////////////////////////////////////////////
346 // End of content of file: include/json/features.h
347 // //////////////////////////////////////////////////////////////////////
348 
349 
350 
351 
352 
353 
354 // //////////////////////////////////////////////////////////////////////
355 // Beginning of content of file: include/json/value.h
356 // //////////////////////////////////////////////////////////////////////
357 
358 // Copyright 2007-2010 Baptiste Lepilleur
359 // Distributed under MIT license, or public domain if desired and
360 // recognized in your jurisdiction.
361 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
362 
363 #ifndef CPPTL_JSON_H_INCLUDED
364 #define CPPTL_JSON_H_INCLUDED
365 
366 #if !defined(JSON_IS_AMALGAMATION)
367 #include "forwards.h"
368 #endif // if !defined(JSON_IS_AMALGAMATION)
369 #include <string>
370 #include <vector>
371 #include <exception>
372 
373 #ifndef JSON_USE_CPPTL_SMALLMAP
374 #include <map>
375 #else
376 #include <cpptl/smallmap.h>
377 #endif
378 #ifdef JSON_USE_CPPTL
379 #include <cpptl/forwards.h>
380 #endif
381 
382 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
383 // be used by...
384 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
385 #pragma warning(push)
386 #pragma warning(disable : 4251)
387 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
388 
389 /** \brief JSON (JavaScript Object Notation).
390  */
391 namespace Json {
392 
393 /** Base class for all exceptions we throw.
394  *
395  * We use nothing but these internally. Of course, STL can throw others.
396  */
397 class JSON_API Exception;
398 /** Exceptions which the user cannot easily avoid.
399  *
400  * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
401  *
402  * \remark derived from Json::Exception
403  */
404 class JSON_API RuntimeError;
405 /** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
406  *
407  * These are precondition-violations (user bugs) and internal errors (our bugs).
408  *
409  * \remark derived from Json::Exception
410  */
411 class JSON_API LogicError;
412 
413 /// used internally
414 void throwRuntimeError(std::string const& msg);
415 /// used internally
416 void throwLogicError(std::string const& msg);
417 
418 /** \brief Type of the value held by a Value object.
419  */
420 enum ValueType {
421   nullValue = 0, ///< 'null' value
422   intValue,      ///< signed integer value
423   uintValue,     ///< unsigned integer value
424   realValue,     ///< double value
425   stringValue,   ///< UTF-8 string value
426   booleanValue,  ///< bool value
427   arrayValue,    ///< array value (ordered list)
428   objectValue    ///< object value (collection of name/value pairs).
429 };
430 
431 enum CommentPlacement {
432   commentBefore = 0,      ///< a comment placed on the line before a value
433   commentAfterOnSameLine, ///< a comment just after a value on the same line
434   commentAfter, ///< a comment on the line after a value (only make sense for
435   /// root value)
436   numberOfCommentPlacement
437 };
438 
439 //# ifdef JSON_USE_CPPTL
440 //   typedef CppTL::AnyEnumerator<const char *> EnumMemberNames;
441 //   typedef CppTL::AnyEnumerator<const Value &> EnumValues;
442 //# endif
443 
444 /** \brief Lightweight wrapper to tag static string.
445  *
446  * Value constructor and objectValue member assignement takes advantage of the
447  * StaticString and avoid the cost of string duplication when storing the
448  * string or the member name.
449  *
450  * Example of usage:
451  * \code
452  * Json::Value aValue( StaticString("some text") );
453  * Json::Value object;
454  * static const StaticString code("code");
455  * object[code] = 1234;
456  * \endcode
457  */
458 class JSON_API StaticString {
459 public:
StaticString(const char * czstring)460   explicit StaticString(const char* czstring) : c_str_(czstring) {}
461 
462   operator const char*() const { return c_str_; }
463 
c_str()464   const char* c_str() const { return c_str_; }
465 
466 private:
467   const char* c_str_;
468 };
469 
470 /** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
471  *
472  * This class is a discriminated union wrapper that can represents a:
473  * - signed integer [range: Value::minInt - Value::maxInt]
474  * - unsigned integer (range: 0 - Value::maxUInt)
475  * - double
476  * - UTF-8 string
477  * - boolean
478  * - 'null'
479  * - an ordered list of Value
480  * - collection of name/value pairs (javascript object)
481  *
482  * The type of the held value is represented by a #ValueType and
483  * can be obtained using type().
484  *
485  * Values of an #objectValue or #arrayValue can be accessed using operator[]()
486  * methods.
487  * Non-const methods will automatically create the a #nullValue element
488  * if it does not exist.
489  * The sequence of an #arrayValue will be automatically resized and initialized
490  * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
491  *
492  * The get() methods can be used to obtain default value in the case the
493  * required element does not exist.
494  *
495  * It is possible to iterate over the list of a #objectValue values using
496  * the getMemberNames() method.
497  *
498  * \note #Value string-length fit in size_t, but keys must be < 2^30.
499  * (The reason is an implementation detail.) A #CharReader will raise an
500  * exception if a bound is exceeded to avoid security holes in your app,
501  * but the Value API does *not* check bounds. That is the responsibility
502  * of the caller.
503  */
504 class JSON_API Value {
505   friend class ValueIteratorBase;
506 public:
507   typedef std::vector<std::string> Members;
508   typedef ValueIterator iterator;
509   typedef ValueConstIterator const_iterator;
510   typedef Json::UInt UInt;
511   typedef Json::Int Int;
512 #if defined(JSON_HAS_INT64)
513   typedef Json::UInt64 UInt64;
514   typedef Json::Int64 Int64;
515 #endif // defined(JSON_HAS_INT64)
516   typedef Json::LargestInt LargestInt;
517   typedef Json::LargestUInt LargestUInt;
518   typedef Json::ArrayIndex ArrayIndex;
519 
520   static const Value& null;  ///< We regret this reference to a global instance; prefer the simpler Value().
521   static const Value& nullRef;  ///< just a kludge for binary-compatibility; same as null
522   /// Minimum signed integer value that can be stored in a Json::Value.
523   static const LargestInt minLargestInt;
524   /// Maximum signed integer value that can be stored in a Json::Value.
525   static const LargestInt maxLargestInt;
526   /// Maximum unsigned integer value that can be stored in a Json::Value.
527   static const LargestUInt maxLargestUInt;
528 
529   /// Minimum signed int value that can be stored in a Json::Value.
530   static const Int minInt;
531   /// Maximum signed int value that can be stored in a Json::Value.
532   static const Int maxInt;
533   /// Maximum unsigned int value that can be stored in a Json::Value.
534   static const UInt maxUInt;
535 
536 #if defined(JSON_HAS_INT64)
537   /// Minimum signed 64 bits int value that can be stored in a Json::Value.
538   static const Int64 minInt64;
539   /// Maximum signed 64 bits int value that can be stored in a Json::Value.
540   static const Int64 maxInt64;
541   /// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
542   static const UInt64 maxUInt64;
543 #endif // defined(JSON_HAS_INT64)
544 
545 private:
546 #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
547   class CZString {
548   public:
549     enum DuplicationPolicy {
550       noDuplication = 0,
551       duplicate,
552       duplicateOnCopy
553     };
554     CZString(ArrayIndex index);
555     CZString(char const* str, unsigned length, DuplicationPolicy allocate);
556     CZString(CZString const& other);
557     ~CZString();
558     CZString& operator=(CZString other);
559     bool operator<(CZString const& other) const;
560     bool operator==(CZString const& other) const;
561     ArrayIndex index() const;
562     //const char* c_str() const; ///< \deprecated
563     char const* data() const;
564     unsigned length() const;
565     bool isStaticString() const;
566 
567   private:
568     void swap(CZString& other);
569 
570     struct StringStorage {
571       unsigned policy_: 2;
572       unsigned length_: 30; // 1GB max
573     };
574 
575     char const* cstr_;  // actually, a prefixed string, unless policy is noDup
576     union {
577       ArrayIndex index_;
578       StringStorage storage_;
579     };
580   };
581 
582 public:
583 #ifndef JSON_USE_CPPTL_SMALLMAP
584   typedef std::map<CZString, Value> ObjectValues;
585 #else
586   typedef CppTL::SmallMap<CZString, Value> ObjectValues;
587 #endif // ifndef JSON_USE_CPPTL_SMALLMAP
588 #endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
589 
590 public:
591   /** \brief Create a default Value of the given type.
592 
593     This is a very useful constructor.
594     To create an empty array, pass arrayValue.
595     To create an empty object, pass objectValue.
596     Another Value can then be set to this one by assignment.
597 This is useful since clear() and resize() will not alter types.
598 
599     Examples:
600 \code
601 Json::Value null_value; // null
602 Json::Value arr_value(Json::arrayValue); // []
603 Json::Value obj_value(Json::objectValue); // {}
604 \endcode
605   */
606   Value(ValueType type = nullValue);
607   Value(Int value);
608   Value(UInt value);
609 #if defined(JSON_HAS_INT64)
610   Value(Int64 value);
611   Value(UInt64 value);
612 #endif // if defined(JSON_HAS_INT64)
613   Value(double value);
614   Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.)
615   Value(const char* beginValue, const char* endValue); ///< Copy all, incl zeroes.
616   /** \brief Constructs a value from a static string.
617 
618    * Like other value string constructor but do not duplicate the string for
619    * internal storage. The given string must remain alive after the call to this
620    * constructor.
621    * \note This works only for null-terminated strings. (We cannot change the
622    *   size of this class, so we have nowhere to store the length,
623    *   which might be computed later for various operations.)
624    *
625    * Example of usage:
626    * \code
627    * static StaticString foo("some text");
628    * Json::Value aValue(foo);
629    * \endcode
630    */
631   Value(const StaticString& value);
632   Value(const std::string& value); ///< Copy data() til size(). Embedded zeroes too.
633 #ifdef JSON_USE_CPPTL
634   Value(const CppTL::ConstString& value);
635 #endif
636   Value(bool value);
637   /// Deep copy.
638   Value(const Value& other);
639   ~Value();
640 
641   /// Deep copy, then swap(other).
642   /// \note Over-write existing comments. To preserve comments, use #swapPayload().
643   Value& operator=(Value other);
644   /// Swap everything.
645   void swap(Value& other);
646   /// Swap values but leave comments and source offsets in place.
647   void swapPayload(Value& other);
648 
649   ValueType type() const;
650 
651   /// Compare payload only, not comments etc.
652   bool operator<(const Value& other) const;
653   bool operator<=(const Value& other) const;
654   bool operator>=(const Value& other) const;
655   bool operator>(const Value& other) const;
656   bool operator==(const Value& other) const;
657   bool operator!=(const Value& other) const;
658   int compare(const Value& other) const;
659 
660   const char* asCString() const; ///< Embedded zeroes could cause you trouble!
661   std::string asString() const; ///< Embedded zeroes are possible.
662   /** Get raw char* of string-value.
663    *  \return false if !string. (Seg-fault if str or end are NULL.)
664    */
665   bool getString(
666       char const** str, char const** end) const;
667 #ifdef JSON_USE_CPPTL
668   CppTL::ConstString asConstString() const;
669 #endif
670   Int asInt() const;
671   UInt asUInt() const;
672 #if defined(JSON_HAS_INT64)
673   Int64 asInt64() const;
674   UInt64 asUInt64() const;
675 #endif // if defined(JSON_HAS_INT64)
676   LargestInt asLargestInt() const;
677   LargestUInt asLargestUInt() const;
678   float asFloat() const;
679   double asDouble() const;
680   bool asBool() const;
681 
682   bool isNull() const;
683   bool isBool() const;
684   bool isInt() const;
685   bool isInt64() const;
686   bool isUInt() const;
687   bool isUInt64() const;
688   bool isIntegral() const;
689   bool isDouble() const;
690   bool isNumeric() const;
691   bool isString() const;
692   bool isArray() const;
693   bool isObject() const;
694 
695   bool isConvertibleTo(ValueType other) const;
696 
697   /// Number of values in array or object
698   ArrayIndex size() const;
699 
700   /// \brief Return true if empty array, empty object, or null;
701   /// otherwise, false.
702   bool empty() const;
703 
704   /// Return isNull()
705   bool operator!() const;
706 
707   /// Remove all object members and array elements.
708   /// \pre type() is arrayValue, objectValue, or nullValue
709   /// \post type() is unchanged
710   void clear();
711 
712   /// Resize the array to size elements.
713   /// New elements are initialized to null.
714   /// May only be called on nullValue or arrayValue.
715   /// \pre type() is arrayValue or nullValue
716   /// \post type() is arrayValue
717   void resize(ArrayIndex size);
718 
719   /// Access an array element (zero based index ).
720   /// If the array contains less than index element, then null value are
721   /// inserted
722   /// in the array so that its size is index+1.
723   /// (You may need to say 'value[0u]' to get your compiler to distinguish
724   ///  this from the operator[] which takes a string.)
725   Value& operator[](ArrayIndex index);
726 
727   /// Access an array element (zero based index ).
728   /// If the array contains less than index element, then null value are
729   /// inserted
730   /// in the array so that its size is index+1.
731   /// (You may need to say 'value[0u]' to get your compiler to distinguish
732   ///  this from the operator[] which takes a string.)
733   Value& operator[](int index);
734 
735   /// Access an array element (zero based index )
736   /// (You may need to say 'value[0u]' to get your compiler to distinguish
737   ///  this from the operator[] which takes a string.)
738   const Value& operator[](ArrayIndex index) const;
739 
740   /// Access an array element (zero based index )
741   /// (You may need to say 'value[0u]' to get your compiler to distinguish
742   ///  this from the operator[] which takes a string.)
743   const Value& operator[](int index) const;
744 
745   /// If the array contains at least index+1 elements, returns the element
746   /// value,
747   /// otherwise returns defaultValue.
748   Value get(ArrayIndex index, const Value& defaultValue) const;
749   /// Return true if index < size().
750   bool isValidIndex(ArrayIndex index) const;
751   /// \brief Append value to array at the end.
752   ///
753   /// Equivalent to jsonvalue[jsonvalue.size()] = value;
754   Value& append(const Value& value);
755 
756   /// Access an object value by name, create a null member if it does not exist.
757   /// \note Because of our implementation, keys are limited to 2^30 -1 chars.
758   ///  Exceeding that will cause an exception.
759   Value& operator[](const char* key);
760   /// Access an object value by name, returns null if there is no member with
761   /// that name.
762   const Value& operator[](const char* key) const;
763   /// Access an object value by name, create a null member if it does not exist.
764   /// \param key may contain embedded nulls.
765   Value& operator[](const std::string& key);
766   /// Access an object value by name, returns null if there is no member with
767   /// that name.
768   /// \param key may contain embedded nulls.
769   const Value& operator[](const std::string& key) const;
770   /** \brief Access an object value by name, create a null member if it does not
771    exist.
772 
773    * If the object has no entry for that name, then the member name used to store
774    * the new entry is not duplicated.
775    * Example of use:
776    * \code
777    * Json::Value object;
778    * static const StaticString code("code");
779    * object[code] = 1234;
780    * \endcode
781    */
782   Value& operator[](const StaticString& key);
783 #ifdef JSON_USE_CPPTL
784   /// Access an object value by name, create a null member if it does not exist.
785   Value& operator[](const CppTL::ConstString& key);
786   /// Access an object value by name, returns null if there is no member with
787   /// that name.
788   const Value& operator[](const CppTL::ConstString& key) const;
789 #endif
790   /// Return the member named key if it exist, defaultValue otherwise.
791   /// \note deep copy
792   Value get(const char* key, const Value& defaultValue) const;
793   /// Return the member named key if it exist, defaultValue otherwise.
794   /// \note deep copy
795   /// \param key may contain embedded nulls.
796   Value get(const char* key, const char* end, const Value& defaultValue) const;
797   /// Return the member named key if it exist, defaultValue otherwise.
798   /// \note deep copy
799   /// \param key may contain embedded nulls.
800   Value get(const std::string& key, const Value& defaultValue) const;
801 #ifdef JSON_USE_CPPTL
802   /// Return the member named key if it exist, defaultValue otherwise.
803   /// \note deep copy
804   Value get(const CppTL::ConstString& key, const Value& defaultValue) const;
805 #endif
806   /// Most general and efficient version of isMember()const, get()const,
807   /// and operator[]const
808   /// \note As stated elsewhere, behavior is undefined if (end-key) >= 2^30
809   Value const* find(char const* key, char const* end) const;
810   /// Most general and efficient version of object-mutators.
811   /// \note As stated elsewhere, behavior is undefined if (end-key) >= 2^30
812   /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
813   Value const* demand(char const* key, char const* end);
814   /// \brief Remove and return the named member.
815   ///
816   /// Do nothing if it did not exist.
817   /// \return the removed Value, or null.
818   /// \pre type() is objectValue or nullValue
819   /// \post type() is unchanged
820   /// \deprecated
821   Value removeMember(const char* key);
822   /// Same as removeMember(const char*)
823   /// \param key may contain embedded nulls.
824   /// \deprecated
825   Value removeMember(const std::string& key);
826   /// Same as removeMember(const char* key, const char* end, Value* removed),
827   /// but 'key' is null-terminated.
828   bool removeMember(const char* key, Value* removed);
829   /** \brief Remove the named map member.
830 
831       Update 'removed' iff removed.
832       \param key may contain embedded nulls.
833       \return true iff removed (no exceptions)
834   */
835   bool removeMember(std::string const& key, Value* removed);
836   /// Same as removeMember(std::string const& key, Value* removed)
837   bool removeMember(const char* key, const char* end, Value* removed);
838   /** \brief Remove the indexed array element.
839 
840       O(n) expensive operations.
841       Update 'removed' iff removed.
842       \return true iff removed (no exceptions)
843   */
844   bool removeIndex(ArrayIndex i, Value* removed);
845 
846   /// Return true if the object has a member named key.
847   /// \note 'key' must be null-terminated.
848   bool isMember(const char* key) const;
849   /// Return true if the object has a member named key.
850   /// \param key may contain embedded nulls.
851   bool isMember(const std::string& key) const;
852   /// Same as isMember(std::string const& key)const
853   bool isMember(const char* key, const char* end) const;
854 #ifdef JSON_USE_CPPTL
855   /// Return true if the object has a member named key.
856   bool isMember(const CppTL::ConstString& key) const;
857 #endif
858 
859   /// \brief Return a list of the member names.
860   ///
861   /// If null, return an empty list.
862   /// \pre type() is objectValue or nullValue
863   /// \post if type() was nullValue, it remains nullValue
864   Members getMemberNames() const;
865 
866   //# ifdef JSON_USE_CPPTL
867   //      EnumMemberNames enumMemberNames() const;
868   //      EnumValues enumValues() const;
869   //# endif
870 
871   /// \deprecated Always pass len.
872   JSONCPP_DEPRECATED("Use setComment(std::string const&) instead.")
873   void setComment(const char* comment, CommentPlacement placement);
874   /// Comments must be //... or /* ... */
875   void setComment(const char* comment, size_t len, CommentPlacement placement);
876   /// Comments must be //... or /* ... */
877   void setComment(const std::string& comment, CommentPlacement placement);
878   bool hasComment(CommentPlacement placement) const;
879   /// Include delimiters and embedded newlines.
880   std::string getComment(CommentPlacement placement) const;
881 
882   std::string toStyledString() const;
883 
884   const_iterator begin() const;
885   const_iterator end() const;
886 
887   iterator begin();
888   iterator end();
889 
890   // Accessors for the [start, limit) range of bytes within the JSON text from
891   // which this value was parsed, if any.
892   void setOffsetStart(size_t start);
893   void setOffsetLimit(size_t limit);
894   size_t getOffsetStart() const;
895   size_t getOffsetLimit() const;
896 
897 private:
898   void initBasic(ValueType type, bool allocated = false);
899 
900   Value& resolveReference(const char* key);
901   Value& resolveReference(const char* key, const char* end);
902 
903   struct CommentInfo {
904     CommentInfo();
905     ~CommentInfo();
906 
907     void setComment(const char* text, size_t len);
908 
909     char* comment_;
910   };
911 
912   // struct MemberNamesTransform
913   //{
914   //   typedef const char *result_type;
915   //   const char *operator()( const CZString &name ) const
916   //   {
917   //      return name.c_str();
918   //   }
919   //};
920 
921   union ValueHolder {
922     LargestInt int_;
923     LargestUInt uint_;
924     double real_;
925     bool bool_;
926     char* string_;  // actually ptr to unsigned, followed by str, unless !allocated_
927     ObjectValues* map_;
928   } value_;
929   ValueType type_ : 8;
930   unsigned int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
931                                // If not allocated_, string_ must be null-terminated.
932   CommentInfo* comments_;
933 
934   // [start, limit) byte offsets in the source JSON text from which this Value
935   // was extracted.
936   size_t start_;
937   size_t limit_;
938 };
939 
940 /** \brief Experimental and untested: represents an element of the "path" to
941  * access a node.
942  */
943 class JSON_API PathArgument {
944 public:
945   friend class Path;
946 
947   PathArgument();
948   PathArgument(ArrayIndex index);
949   PathArgument(const char* key);
950   PathArgument(const std::string& key);
951 
952 private:
953   enum Kind {
954     kindNone = 0,
955     kindIndex,
956     kindKey
957   };
958   std::string key_;
959   ArrayIndex index_;
960   Kind kind_;
961 };
962 
963 /** \brief Experimental and untested: represents a "path" to access a node.
964  *
965  * Syntax:
966  * - "." => root node
967  * - ".[n]" => elements at index 'n' of root node (an array value)
968  * - ".name" => member named 'name' of root node (an object value)
969  * - ".name1.name2.name3"
970  * - ".[0][1][2].name1[3]"
971  * - ".%" => member name is provided as parameter
972  * - ".[%]" => index is provied as parameter
973  */
974 class JSON_API Path {
975 public:
976   Path(const std::string& path,
977        const PathArgument& a1 = PathArgument(),
978        const PathArgument& a2 = PathArgument(),
979        const PathArgument& a3 = PathArgument(),
980        const PathArgument& a4 = PathArgument(),
981        const PathArgument& a5 = PathArgument());
982 
983   const Value& resolve(const Value& root) const;
984   Value resolve(const Value& root, const Value& defaultValue) const;
985   /// Creates the "path" to access the specified node and returns a reference on
986   /// the node.
987   Value& make(Value& root) const;
988 
989 private:
990   typedef std::vector<const PathArgument*> InArgs;
991   typedef std::vector<PathArgument> Args;
992 
993   void makePath(const std::string& path, const InArgs& in);
994   void addPathInArg(const std::string& path,
995                     const InArgs& in,
996                     InArgs::const_iterator& itInArg,
997                     PathArgument::Kind kind);
998   void invalidPath(const std::string& path, int location);
999 
1000   Args args_;
1001 };
1002 
1003 /** \brief base class for Value iterators.
1004  *
1005  */
1006 class JSON_API ValueIteratorBase {
1007 public:
1008   typedef std::bidirectional_iterator_tag iterator_category;
1009   typedef unsigned int size_t;
1010   typedef int difference_type;
1011   typedef ValueIteratorBase SelfType;
1012 
1013   bool operator==(const SelfType& other) const { return isEqual(other); }
1014 
1015   bool operator!=(const SelfType& other) const { return !isEqual(other); }
1016 
1017   difference_type operator-(const SelfType& other) const {
1018     return other.computeDistance(*this);
1019   }
1020 
1021   /// Return either the index or the member name of the referenced value as a
1022   /// Value.
1023   Value key() const;
1024 
1025   /// Return the index of the referenced Value, or -1 if it is not an arrayValue.
1026   UInt index() const;
1027 
1028   /// Return the member name of the referenced Value, or "" if it is not an
1029   /// objectValue.
1030   /// \note Avoid `c_str()` on result, as embedded zeroes are possible.
1031   std::string name() const;
1032 
1033   /// Return the member name of the referenced Value. "" if it is not an
1034   /// objectValue.
1035   /// \deprecated This cannot be used for UTF-8 strings, since there can be embedded nulls.
1036   JSONCPP_DEPRECATED("Use `key = name();` instead.")
1037   char const* memberName() const;
1038   /// Return the member name of the referenced Value, or NULL if it is not an
1039   /// objectValue.
1040   /// \note Better version than memberName(). Allows embedded nulls.
1041   char const* memberName(char const** end) const;
1042 
1043 protected:
1044   Value& deref() const;
1045 
1046   void increment();
1047 
1048   void decrement();
1049 
1050   difference_type computeDistance(const SelfType& other) const;
1051 
1052   bool isEqual(const SelfType& other) const;
1053 
1054   void copy(const SelfType& other);
1055 
1056 private:
1057   Value::ObjectValues::iterator current_;
1058   // Indicates that iterator is for a null value.
1059   bool isNull_;
1060 
1061 public:
1062   // For some reason, BORLAND needs these at the end, rather
1063   // than earlier. No idea why.
1064   ValueIteratorBase();
1065   explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
1066 };
1067 
1068 /** \brief const iterator for object and array value.
1069  *
1070  */
1071 class JSON_API ValueConstIterator : public ValueIteratorBase {
1072   friend class Value;
1073 
1074 public:
1075   typedef const Value value_type;
1076   //typedef unsigned int size_t;
1077   //typedef int difference_type;
1078   typedef const Value& reference;
1079   typedef const Value* pointer;
1080   typedef ValueConstIterator SelfType;
1081 
1082   ValueConstIterator();
1083 
1084 private:
1085 /*! \internal Use by Value to create an iterator.
1086  */
1087   explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
1088 public:
1089   SelfType& operator=(const ValueIteratorBase& other);
1090 
1091   SelfType operator++(int) {
1092     SelfType temp(*this);
1093     ++*this;
1094     return temp;
1095   }
1096 
1097   SelfType operator--(int) {
1098     SelfType temp(*this);
1099     --*this;
1100     return temp;
1101   }
1102 
1103   SelfType& operator--() {
1104     decrement();
1105     return *this;
1106   }
1107 
1108   SelfType& operator++() {
1109     increment();
1110     return *this;
1111   }
1112 
1113   reference operator*() const { return deref(); }
1114 
1115   pointer operator->() const { return &deref(); }
1116 };
1117 
1118 /** \brief Iterator for object and array value.
1119  */
1120 class JSON_API ValueIterator : public ValueIteratorBase {
1121   friend class Value;
1122 
1123 public:
1124   typedef Value value_type;
1125   typedef unsigned int size_t;
1126   typedef int difference_type;
1127   typedef Value& reference;
1128   typedef Value* pointer;
1129   typedef ValueIterator SelfType;
1130 
1131   ValueIterator();
1132   ValueIterator(const ValueConstIterator& other);
1133   ValueIterator(const ValueIterator& other);
1134 
1135 private:
1136 /*! \internal Use by Value to create an iterator.
1137  */
1138   explicit ValueIterator(const Value::ObjectValues::iterator& current);
1139 public:
1140   SelfType& operator=(const SelfType& other);
1141 
1142   SelfType operator++(int) {
1143     SelfType temp(*this);
1144     ++*this;
1145     return temp;
1146   }
1147 
1148   SelfType operator--(int) {
1149     SelfType temp(*this);
1150     --*this;
1151     return temp;
1152   }
1153 
1154   SelfType& operator--() {
1155     decrement();
1156     return *this;
1157   }
1158 
1159   SelfType& operator++() {
1160     increment();
1161     return *this;
1162   }
1163 
1164   reference operator*() const { return deref(); }
1165 
1166   pointer operator->() const { return &deref(); }
1167 };
1168 
1169 } // namespace Json
1170 
1171 
1172 namespace std {
1173 /// Specialize std::swap() for Json::Value.
1174 template<>
swap(Json::Value & a,Json::Value & b)1175 inline void swap(Json::Value& a, Json::Value& b) { a.swap(b); }
1176 }
1177 
1178 
1179 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1180 #pragma warning(pop)
1181 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1182 
1183 #endif // CPPTL_JSON_H_INCLUDED
1184 
1185 // //////////////////////////////////////////////////////////////////////
1186 // End of content of file: include/json/value.h
1187 // //////////////////////////////////////////////////////////////////////
1188 
1189 
1190 
1191 
1192 
1193 
1194 // //////////////////////////////////////////////////////////////////////
1195 // Beginning of content of file: include/json/reader.h
1196 // //////////////////////////////////////////////////////////////////////
1197 
1198 // Copyright 2007-2010 Baptiste Lepilleur
1199 // Distributed under MIT license, or public domain if desired and
1200 // recognized in your jurisdiction.
1201 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1202 
1203 #ifndef CPPTL_JSON_READER_H_INCLUDED
1204 #define CPPTL_JSON_READER_H_INCLUDED
1205 
1206 #if !defined(JSON_IS_AMALGAMATION)
1207 #include "features.h"
1208 #include "value.h"
1209 #endif // if !defined(JSON_IS_AMALGAMATION)
1210 #include <deque>
1211 #include <iosfwd>
1212 #include <stack>
1213 #include <string>
1214 #include <istream>
1215 
1216 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
1217 // be used by...
1218 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1219 #pragma warning(push)
1220 #pragma warning(disable : 4251)
1221 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1222 
1223 namespace Json {
1224 
1225 /** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a
1226  *Value.
1227  *
1228  * \deprecated Use CharReader and CharReaderBuilder.
1229  */
1230 class JSON_API Reader {
1231 public:
1232   typedef char Char;
1233   typedef const Char* Location;
1234 
1235   /** \brief An error tagged with where in the JSON text it was encountered.
1236    *
1237    * The offsets give the [start, limit) range of bytes within the text. Note
1238    * that this is bytes, not codepoints.
1239    *
1240    */
1241   struct StructuredError {
1242     size_t offset_start;
1243     size_t offset_limit;
1244     std::string message;
1245   };
1246 
1247   /** \brief Constructs a Reader allowing all features
1248    * for parsing.
1249    */
1250   Reader();
1251 
1252   /** \brief Constructs a Reader allowing the specified feature set
1253    * for parsing.
1254    */
1255   Reader(const Features& features);
1256 
1257   /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1258    * document.
1259    * \param document UTF-8 encoded string containing the document to read.
1260    * \param root [out] Contains the root value of the document if it was
1261    *             successfully parsed.
1262    * \param collectComments \c true to collect comment and allow writing them
1263    * back during
1264    *                        serialization, \c false to discard comments.
1265    *                        This parameter is ignored if
1266    * Features::allowComments_
1267    *                        is \c false.
1268    * \return \c true if the document was successfully parsed, \c false if an
1269    * error occurred.
1270    */
1271   bool
1272   parse(const std::string& document, Value& root, bool collectComments = true);
1273 
1274   /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1275    document.
1276    * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
1277    document to read.
1278    * \param endDoc Pointer on the end of the UTF-8 encoded string of the
1279    document to read.
1280    *               Must be >= beginDoc.
1281    * \param root [out] Contains the root value of the document if it was
1282    *             successfully parsed.
1283    * \param collectComments \c true to collect comment and allow writing them
1284    back during
1285    *                        serialization, \c false to discard comments.
1286    *                        This parameter is ignored if
1287    Features::allowComments_
1288    *                        is \c false.
1289    * \return \c true if the document was successfully parsed, \c false if an
1290    error occurred.
1291    */
1292   bool parse(const char* beginDoc,
1293              const char* endDoc,
1294              Value& root,
1295              bool collectComments = true);
1296 
1297   /// \brief Parse from input stream.
1298   /// \see Json::operator>>(std::istream&, Json::Value&).
1299   bool parse(std::istream& is, Value& root, bool collectComments = true);
1300 
1301   /** \brief Returns a user friendly string that list errors in the parsed
1302    * document.
1303    * \return Formatted error message with the list of errors with their location
1304    * in
1305    *         the parsed document. An empty string is returned if no error
1306    * occurred
1307    *         during parsing.
1308    * \deprecated Use getFormattedErrorMessages() instead (typo fix).
1309    */
1310   JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.")
1311   std::string getFormatedErrorMessages() const;
1312 
1313   /** \brief Returns a user friendly string that list errors in the parsed
1314    * document.
1315    * \return Formatted error message with the list of errors with their location
1316    * in
1317    *         the parsed document. An empty string is returned if no error
1318    * occurred
1319    *         during parsing.
1320    */
1321   std::string getFormattedErrorMessages() const;
1322 
1323   /** \brief Returns a vector of structured erros encounted while parsing.
1324    * \return A (possibly empty) vector of StructuredError objects. Currently
1325    *         only one error can be returned, but the caller should tolerate
1326    * multiple
1327    *         errors.  This can occur if the parser recovers from a non-fatal
1328    *         parse error and then encounters additional errors.
1329    */
1330   std::vector<StructuredError> getStructuredErrors() const;
1331 
1332   /** \brief Add a semantic error message.
1333    * \param value JSON Value location associated with the error
1334    * \param message The error message.
1335    * \return \c true if the error was successfully added, \c false if the
1336    * Value offset exceeds the document size.
1337    */
1338   bool pushError(const Value& value, const std::string& message);
1339 
1340   /** \brief Add a semantic error message with extra context.
1341    * \param value JSON Value location associated with the error
1342    * \param message The error message.
1343    * \param extra Additional JSON Value location to contextualize the error
1344    * \return \c true if the error was successfully added, \c false if either
1345    * Value offset exceeds the document size.
1346    */
1347   bool pushError(const Value& value, const std::string& message, const Value& extra);
1348 
1349   /** \brief Return whether there are any errors.
1350    * \return \c true if there are no errors to report \c false if
1351    * errors have occurred.
1352    */
1353   bool good() const;
1354 
1355 private:
1356   enum TokenType {
1357     tokenEndOfStream = 0,
1358     tokenObjectBegin,
1359     tokenObjectEnd,
1360     tokenArrayBegin,
1361     tokenArrayEnd,
1362     tokenString,
1363     tokenNumber,
1364     tokenTrue,
1365     tokenFalse,
1366     tokenNull,
1367     tokenArraySeparator,
1368     tokenMemberSeparator,
1369     tokenComment,
1370     tokenError
1371   };
1372 
1373   class Token {
1374   public:
1375     TokenType type_;
1376     Location start_;
1377     Location end_;
1378   };
1379 
1380   class ErrorInfo {
1381   public:
1382     Token token_;
1383     std::string message_;
1384     Location extra_;
1385   };
1386 
1387   typedef std::deque<ErrorInfo> Errors;
1388 
1389   bool readToken(Token& token);
1390   void skipSpaces();
1391   bool match(Location pattern, int patternLength);
1392   bool readComment();
1393   bool readCStyleComment();
1394   bool readCppStyleComment();
1395   bool readString();
1396   void readNumber();
1397   bool readValue();
1398   bool readObject(Token& token);
1399   bool readArray(Token& token);
1400   bool decodeNumber(Token& token);
1401   bool decodeNumber(Token& token, Value& decoded);
1402   bool decodeString(Token& token);
1403   bool decodeString(Token& token, std::string& decoded);
1404   bool decodeDouble(Token& token);
1405   bool decodeDouble(Token& token, Value& decoded);
1406   bool decodeUnicodeCodePoint(Token& token,
1407                               Location& current,
1408                               Location end,
1409                               unsigned int& unicode);
1410   bool decodeUnicodeEscapeSequence(Token& token,
1411                                    Location& current,
1412                                    Location end,
1413                                    unsigned int& unicode);
1414   bool addError(const std::string& message, Token& token, Location extra = 0);
1415   bool recoverFromError(TokenType skipUntilToken);
1416   bool addErrorAndRecover(const std::string& message,
1417                           Token& token,
1418                           TokenType skipUntilToken);
1419   void skipUntilSpace();
1420   Value& currentValue();
1421   Char getNextChar();
1422   void
1423   getLocationLineAndColumn(Location location, int& line, int& column) const;
1424   std::string getLocationLineAndColumn(Location location) const;
1425   void addComment(Location begin, Location end, CommentPlacement placement);
1426   void skipCommentTokens(Token& token);
1427 
1428   typedef std::stack<Value*> Nodes;
1429   Nodes nodes_;
1430   Errors errors_;
1431   std::string document_;
1432   Location begin_;
1433   Location end_;
1434   Location current_;
1435   Location lastValueEnd_;
1436   Value* lastValue_;
1437   std::string commentsBefore_;
1438   Features features_;
1439   bool collectComments_;
1440 };  // Reader
1441 
1442 /** Interface for reading JSON from a char array.
1443  */
1444 class JSON_API CharReader {
1445 public:
~CharReader()1446   virtual ~CharReader() {}
1447   /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1448    document.
1449    * The document must be a UTF-8 encoded string containing the document to read.
1450    *
1451    * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
1452    document to read.
1453    * \param endDoc Pointer on the end of the UTF-8 encoded string of the
1454    document to read.
1455    *        Must be >= beginDoc.
1456    * \param root [out] Contains the root value of the document if it was
1457    *             successfully parsed.
1458    * \param errs [out] Formatted error messages (if not NULL)
1459    *        a user friendly string that lists errors in the parsed
1460    * document.
1461    * \return \c true if the document was successfully parsed, \c false if an
1462    error occurred.
1463    */
1464   virtual bool parse(
1465       char const* beginDoc, char const* endDoc,
1466       Value* root, std::string* errs) = 0;
1467 
1468   class Factory {
1469   public:
~Factory()1470     virtual ~Factory() {}
1471     /** \brief Allocate a CharReader via operator new().
1472      * \throw std::exception if something goes wrong (e.g. invalid settings)
1473      */
1474     virtual CharReader* newCharReader() const = 0;
1475   };  // Factory
1476 };  // CharReader
1477 
1478 /** \brief Build a CharReader implementation.
1479 
1480 Usage:
1481 \code
1482   using namespace Json;
1483   CharReaderBuilder builder;
1484   builder["collectComments"] = false;
1485   Value value;
1486   std::string errs;
1487   bool ok = parseFromStream(builder, std::cin, &value, &errs);
1488 \endcode
1489 */
1490 class JSON_API CharReaderBuilder : public CharReader::Factory {
1491 public:
1492   // Note: We use a Json::Value so that we can add data-members to this class
1493   // without a major version bump.
1494   /** Configuration of this builder.
1495     These are case-sensitive.
1496     Available settings (case-sensitive):
1497     - `"collectComments": false or true`
1498       - true to collect comment and allow writing them
1499         back during serialization, false to discard comments.
1500         This parameter is ignored if allowComments is false.
1501     - `"allowComments": false or true`
1502       - true if comments are allowed.
1503     - `"strictRoot": false or true`
1504       - true if root must be either an array or an object value
1505     - `"allowDroppedNullPlaceholders": false or true`
1506       - true if dropped null placeholders are allowed. (See StreamWriterBuilder.)
1507     - `"allowNumericKeys": false or true`
1508       - true if numeric object keys are allowed.
1509     - `"allowSingleQuotes": false or true`
1510       - true if '' are allowed for strings (both keys and values)
1511     - `"stackLimit": integer`
1512       - Exceeding stackLimit (recursive depth of `readValue()`) will
1513         cause an exception.
1514       - This is a security issue (seg-faults caused by deeply nested JSON),
1515         so the default is low.
1516     - `"failIfExtra": false or true`
1517       - If true, `parse()` returns false when extra non-whitespace trails
1518         the JSON value in the input string.
1519     - `"rejectDupKeys": false or true`
1520       - If true, `parse()` returns false when a key is duplicated within an object.
1521 
1522     You can examine 'settings_` yourself
1523     to see the defaults. You can also write and read them just like any
1524     JSON Value.
1525     \sa setDefaults()
1526     */
1527   Json::Value settings_;
1528 
1529   CharReaderBuilder();
1530   virtual ~CharReaderBuilder();
1531 
1532   virtual CharReader* newCharReader() const;
1533 
1534   /** \return true if 'settings' are legal and consistent;
1535    *   otherwise, indicate bad settings via 'invalid'.
1536    */
1537   bool validate(Json::Value* invalid) const;
1538 
1539   /** A simple way to update a specific setting.
1540    */
1541   Value& operator[](std::string key);
1542 
1543   /** Called by ctor, but you can use this to reset settings_.
1544    * \pre 'settings' != NULL (but Json::null is fine)
1545    * \remark Defaults:
1546    * \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults
1547    */
1548   static void setDefaults(Json::Value* settings);
1549   /** Same as old Features::strictMode().
1550    * \pre 'settings' != NULL (but Json::null is fine)
1551    * \remark Defaults:
1552    * \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode
1553    */
1554   static void strictMode(Json::Value* settings);
1555 };
1556 
1557 /** Consume entire stream and use its begin/end.
1558   * Someday we might have a real StreamReader, but for now this
1559   * is convenient.
1560   */
1561 bool JSON_API parseFromStream(
1562     CharReader::Factory const&,
1563     std::istream&,
1564     Value* root, std::string* errs);
1565 
1566 /** \brief Read from 'sin' into 'root'.
1567 
1568  Always keep comments from the input JSON.
1569 
1570  This can be used to read a file into a particular sub-object.
1571  For example:
1572  \code
1573  Json::Value root;
1574  cin >> root["dir"]["file"];
1575  cout << root;
1576  \endcode
1577  Result:
1578  \verbatim
1579  {
1580  "dir": {
1581      "file": {
1582      // The input stream JSON would be nested here.
1583      }
1584  }
1585  }
1586  \endverbatim
1587  \throw std::exception on parse error.
1588  \see Json::operator<<()
1589 */
1590 JSON_API std::istream& operator>>(std::istream&, Value&);
1591 
1592 } // namespace Json
1593 
1594 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1595 #pragma warning(pop)
1596 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1597 
1598 #endif // CPPTL_JSON_READER_H_INCLUDED
1599 
1600 // //////////////////////////////////////////////////////////////////////
1601 // End of content of file: include/json/reader.h
1602 // //////////////////////////////////////////////////////////////////////
1603 
1604 
1605 
1606 
1607 
1608 
1609 // //////////////////////////////////////////////////////////////////////
1610 // Beginning of content of file: include/json/writer.h
1611 // //////////////////////////////////////////////////////////////////////
1612 
1613 // Copyright 2007-2010 Baptiste Lepilleur
1614 // Distributed under MIT license, or public domain if desired and
1615 // recognized in your jurisdiction.
1616 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1617 
1618 #ifndef JSON_WRITER_H_INCLUDED
1619 #define JSON_WRITER_H_INCLUDED
1620 
1621 #if !defined(JSON_IS_AMALGAMATION)
1622 #include "value.h"
1623 #endif // if !defined(JSON_IS_AMALGAMATION)
1624 #include <vector>
1625 #include <string>
1626 #include <ostream>
1627 
1628 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
1629 // be used by...
1630 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1631 #pragma warning(push)
1632 #pragma warning(disable : 4251)
1633 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1634 
1635 namespace Json {
1636 
1637 class Value;
1638 
1639 /**
1640 
1641 Usage:
1642 \code
1643   using namespace Json;
1644   void writeToStdout(StreamWriter::Factory const& factory, Value const& value) {
1645     std::unique_ptr<StreamWriter> const writer(
1646       factory.newStreamWriter());
1647     writer->write(value, &std::cout);
1648     std::cout << std::endl;  // add lf and flush
1649   }
1650 \endcode
1651 */
1652 class JSON_API StreamWriter {
1653 protected:
1654   std::ostream* sout_;  // not owned; will not delete
1655 public:
1656   StreamWriter();
1657   virtual ~StreamWriter();
1658   /** Write Value into document as configured in sub-class.
1659       Do not take ownership of sout, but maintain a reference during function.
1660       \pre sout != NULL
1661       \return zero on success (For now, we always return zero, so check the stream instead.)
1662       \throw std::exception possibly, depending on configuration
1663    */
1664   virtual int write(Value const& root, std::ostream* sout) = 0;
1665 
1666   /** \brief A simple abstract factory.
1667    */
1668   class JSON_API Factory {
1669   public:
1670     virtual ~Factory();
1671     /** \brief Allocate a CharReader via operator new().
1672      * \throw std::exception if something goes wrong (e.g. invalid settings)
1673      */
1674     virtual StreamWriter* newStreamWriter() const = 0;
1675   };  // Factory
1676 };  // StreamWriter
1677 
1678 /** \brief Write into stringstream, then return string, for convenience.
1679  * A StreamWriter will be created from the factory, used, and then deleted.
1680  */
1681 std::string JSON_API writeString(StreamWriter::Factory const& factory, Value const& root);
1682 
1683 
1684 /** \brief Build a StreamWriter implementation.
1685 
1686 Usage:
1687 \code
1688   using namespace Json;
1689   Value value = ...;
1690   StreamWriterBuilder builder;
1691   builder["commentStyle"] = "None";
1692   builder["indentation"] = "   ";  // or whatever you like
1693   std::unique_ptr<Json::StreamWriter> writer(
1694       builder.newStreamWriter());
1695   writer->write(value, &std::cout);
1696   std::cout << std::endl;  // add lf and flush
1697 \endcode
1698 */
1699 class JSON_API StreamWriterBuilder : public StreamWriter::Factory {
1700 public:
1701   // Note: We use a Json::Value so that we can add data-members to this class
1702   // without a major version bump.
1703   /** Configuration of this builder.
1704     Available settings (case-sensitive):
1705     - "commentStyle": "None" or "All"
1706     - "indentation":  "<anything>"
1707     - "enableYAMLCompatibility": false or true
1708       - slightly change the whitespace around colons
1709     - "dropNullPlaceholders": false or true
1710       - Drop the "null" string from the writer's output for nullValues.
1711         Strictly speaking, this is not valid JSON. But when the output is being
1712         fed to a browser's Javascript, it makes for smaller output and the
1713         browser can handle the output just fine.
1714 
1715     You can examine 'settings_` yourself
1716     to see the defaults. You can also write and read them just like any
1717     JSON Value.
1718     \sa setDefaults()
1719     */
1720   Json::Value settings_;
1721 
1722   StreamWriterBuilder();
1723   virtual ~StreamWriterBuilder();
1724 
1725   /**
1726    * \throw std::exception if something goes wrong (e.g. invalid settings)
1727    */
1728   virtual StreamWriter* newStreamWriter() const;
1729 
1730   /** \return true if 'settings' are legal and consistent;
1731    *   otherwise, indicate bad settings via 'invalid'.
1732    */
1733   bool validate(Json::Value* invalid) const;
1734   /** A simple way to update a specific setting.
1735    */
1736   Value& operator[](std::string key);
1737 
1738   /** Called by ctor, but you can use this to reset settings_.
1739    * \pre 'settings' != NULL (but Json::null is fine)
1740    * \remark Defaults:
1741    * \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults
1742    */
1743   static void setDefaults(Json::Value* settings);
1744 };
1745 
1746 /** \brief Abstract class for writers.
1747  * \deprecated Use StreamWriter. (And really, this is an implementation detail.)
1748  */
1749 class JSON_API Writer {
1750 public:
1751   virtual ~Writer();
1752 
1753   virtual std::string write(const Value& root) = 0;
1754 };
1755 
1756 /** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format
1757  *without formatting (not human friendly).
1758  *
1759  * The JSON document is written in a single line. It is not intended for 'human'
1760  *consumption,
1761  * but may be usefull to support feature such as RPC where bandwith is limited.
1762  * \sa Reader, Value
1763  * \deprecated Use StreamWriterBuilder.
1764  */
1765 class JSON_API FastWriter : public Writer {
1766 
1767 public:
1768   FastWriter();
~FastWriter()1769   virtual ~FastWriter() {}
1770 
1771   void enableYAMLCompatibility();
1772 
1773   /** \brief Drop the "null" string from the writer's output for nullValues.
1774    * Strictly speaking, this is not valid JSON. But when the output is being
1775    * fed to a browser's Javascript, it makes for smaller output and the
1776    * browser can handle the output just fine.
1777    */
1778   void dropNullPlaceholders();
1779 
1780   void omitEndingLineFeed();
1781 
1782 public: // overridden from Writer
1783   virtual std::string write(const Value& root);
1784 
1785 private:
1786   void writeValue(const Value& value);
1787 
1788   std::string document_;
1789   bool yamlCompatiblityEnabled_;
1790   bool dropNullPlaceholders_;
1791   bool omitEndingLineFeed_;
1792 };
1793 
1794 /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
1795  *human friendly way.
1796  *
1797  * The rules for line break and indent are as follow:
1798  * - Object value:
1799  *     - if empty then print {} without indent and line break
1800  *     - if not empty the print '{', line break & indent, print one value per
1801  *line
1802  *       and then unindent and line break and print '}'.
1803  * - Array value:
1804  *     - if empty then print [] without indent and line break
1805  *     - if the array contains no object value, empty array or some other value
1806  *types,
1807  *       and all the values fit on one lines, then print the array on a single
1808  *line.
1809  *     - otherwise, it the values do not fit on one line, or the array contains
1810  *       object or non empty array, then print one value per line.
1811  *
1812  * If the Value have comments then they are outputed according to their
1813  *#CommentPlacement.
1814  *
1815  * \sa Reader, Value, Value::setComment()
1816  * \deprecated Use StreamWriterBuilder.
1817  */
1818 class JSON_API StyledWriter : public Writer {
1819 public:
1820   StyledWriter();
~StyledWriter()1821   virtual ~StyledWriter() {}
1822 
1823 public: // overridden from Writer
1824   /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
1825    * \param root Value to serialize.
1826    * \return String containing the JSON document that represents the root value.
1827    */
1828   virtual std::string write(const Value& root);
1829 
1830 private:
1831   void writeValue(const Value& value);
1832   void writeArrayValue(const Value& value);
1833   bool isMultineArray(const Value& value);
1834   void pushValue(const std::string& value);
1835   void writeIndent();
1836   void writeWithIndent(const std::string& value);
1837   void indent();
1838   void unindent();
1839   void writeCommentBeforeValue(const Value& root);
1840   void writeCommentAfterValueOnSameLine(const Value& root);
1841   bool hasCommentForValue(const Value& value);
1842   static std::string normalizeEOL(const std::string& text);
1843 
1844   typedef std::vector<std::string> ChildValues;
1845 
1846   ChildValues childValues_;
1847   std::string document_;
1848   std::string indentString_;
1849   int rightMargin_;
1850   int indentSize_;
1851   bool addChildValues_;
1852 };
1853 
1854 /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
1855  human friendly way,
1856      to a stream rather than to a string.
1857  *
1858  * The rules for line break and indent are as follow:
1859  * - Object value:
1860  *     - if empty then print {} without indent and line break
1861  *     - if not empty the print '{', line break & indent, print one value per
1862  line
1863  *       and then unindent and line break and print '}'.
1864  * - Array value:
1865  *     - if empty then print [] without indent and line break
1866  *     - if the array contains no object value, empty array or some other value
1867  types,
1868  *       and all the values fit on one lines, then print the array on a single
1869  line.
1870  *     - otherwise, it the values do not fit on one line, or the array contains
1871  *       object or non empty array, then print one value per line.
1872  *
1873  * If the Value have comments then they are outputed according to their
1874  #CommentPlacement.
1875  *
1876  * \param indentation Each level will be indented by this amount extra.
1877  * \sa Reader, Value, Value::setComment()
1878  * \deprecated Use StreamWriterBuilder.
1879  */
1880 class JSON_API StyledStreamWriter {
1881 public:
1882   StyledStreamWriter(std::string indentation = "\t");
~StyledStreamWriter()1883   ~StyledStreamWriter() {}
1884 
1885 public:
1886   /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
1887    * \param out Stream to write to. (Can be ostringstream, e.g.)
1888    * \param root Value to serialize.
1889    * \note There is no point in deriving from Writer, since write() should not
1890    * return a value.
1891    */
1892   void write(std::ostream& out, const Value& root);
1893 
1894 private:
1895   void writeValue(const Value& value);
1896   void writeArrayValue(const Value& value);
1897   bool isMultineArray(const Value& value);
1898   void pushValue(const std::string& value);
1899   void writeIndent();
1900   void writeWithIndent(const std::string& value);
1901   void indent();
1902   void unindent();
1903   void writeCommentBeforeValue(const Value& root);
1904   void writeCommentAfterValueOnSameLine(const Value& root);
1905   bool hasCommentForValue(const Value& value);
1906   static std::string normalizeEOL(const std::string& text);
1907 
1908   typedef std::vector<std::string> ChildValues;
1909 
1910   ChildValues childValues_;
1911   std::ostream* document_;
1912   std::string indentString_;
1913   int rightMargin_;
1914   std::string indentation_;
1915   bool addChildValues_ : 1;
1916   bool indented_ : 1;
1917 };
1918 
1919 #if defined(JSON_HAS_INT64)
1920 std::string JSON_API valueToString(Int value);
1921 std::string JSON_API valueToString(UInt value);
1922 #endif // if defined(JSON_HAS_INT64)
1923 std::string JSON_API valueToString(LargestInt value);
1924 std::string JSON_API valueToString(LargestUInt value);
1925 std::string JSON_API valueToString(double value);
1926 std::string JSON_API valueToString(bool value);
1927 std::string JSON_API valueToQuotedString(const char* value);
1928 
1929 /// \brief Output using the StyledStreamWriter.
1930 /// \see Json::operator>>()
1931 JSON_API std::ostream& operator<<(std::ostream&, const Value& root);
1932 
1933 } // namespace Json
1934 
1935 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1936 #pragma warning(pop)
1937 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1938 
1939 #endif // JSON_WRITER_H_INCLUDED
1940 
1941 // //////////////////////////////////////////////////////////////////////
1942 // End of content of file: include/json/writer.h
1943 // //////////////////////////////////////////////////////////////////////
1944 
1945 
1946 
1947 
1948 
1949 
1950 // //////////////////////////////////////////////////////////////////////
1951 // Beginning of content of file: include/json/assertions.h
1952 // //////////////////////////////////////////////////////////////////////
1953 
1954 // Copyright 2007-2010 Baptiste Lepilleur
1955 // Distributed under MIT license, or public domain if desired and
1956 // recognized in your jurisdiction.
1957 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1958 
1959 #ifndef CPPTL_JSON_ASSERTIONS_H_INCLUDED
1960 #define CPPTL_JSON_ASSERTIONS_H_INCLUDED
1961 
1962 #include <stdlib.h>
1963 #include <sstream>
1964 
1965 #if !defined(JSON_IS_AMALGAMATION)
1966 #include "config.h"
1967 #endif // if !defined(JSON_IS_AMALGAMATION)
1968 
1969 /** It should not be possible for a maliciously designed file to
1970  *  cause an abort() or seg-fault, so these macros are used only
1971  *  for pre-condition violations and internal logic errors.
1972  */
1973 #if JSON_USE_EXCEPTION
1974 
1975 // @todo <= add detail about condition in exception
1976 # define JSON_ASSERT(condition)                                                \
1977   {if (!(condition)) {Json::throwLogicError( "assert json failed" );}}
1978 
1979 # define JSON_FAIL_MESSAGE(message)                                            \
1980   {                                                                            \
1981     std::ostringstream oss; oss << message;                                    \
1982     Json::throwLogicError(oss.str());                                          \
1983     abort();                                                                   \
1984   }
1985 
1986 #else // JSON_USE_EXCEPTION
1987 
1988 # define JSON_ASSERT(condition) assert(condition)
1989 
1990 // The call to assert() will show the failure message in debug builds. In
1991 // release builds we abort, for a core-dump or debugger.
1992 # define JSON_FAIL_MESSAGE(message)                                            \
1993   {                                                                            \
1994     std::ostringstream oss; oss << message;                                    \
1995     assert(false && oss.str().c_str());                                        \
1996     abort();                                                                   \
1997   }
1998 
1999 
2000 #endif
2001 
2002 #define JSON_ASSERT_MESSAGE(condition, message)                                \
2003   if (!(condition)) {                                                          \
2004     JSON_FAIL_MESSAGE(message);                                                \
2005   }
2006 
2007 #endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED
2008 
2009 // //////////////////////////////////////////////////////////////////////
2010 // End of content of file: include/json/assertions.h
2011 // //////////////////////////////////////////////////////////////////////
2012 
2013 
2014 
2015 
2016 
2017 #endif //ifndef JSON_AMALGATED_H_INCLUDED
2018