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