ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/cbrown/Development/Plotting/Modules/JSON/json.h
Revision: 1.1
Committed: Tue Oct 30 14:56:59 2012 UTC (12 years, 6 months ago) by buchmann
Content type: text/plain
Branch: MAIN
CVS Tags: HEAD
Log Message:
Added development version of sample loading from JSON file. Not ready for prime time, but getting there. Uses amalgamated version of jsoncpp

File Contents

# User Rev Content
1 buchmann 1.1 /// Json-cpp amalgated header (http://jsoncpp.sourceforge.net/).
2     /// It is intented 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/config.h
83     // //////////////////////////////////////////////////////////////////////
84    
85     // Copyright 2007-2010 Baptiste Lepilleur
86     // Distributed under MIT license, or public domain if desired and
87     // recognized in your jurisdiction.
88     // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
89    
90     #ifndef JSON_CONFIG_H_INCLUDED
91     # define JSON_CONFIG_H_INCLUDED
92    
93     /// If defined, indicates that json library is embedded in CppTL library.
94     //# define JSON_IN_CPPTL 1
95    
96     /// If defined, indicates that json may leverage CppTL library
97     //# define JSON_USE_CPPTL 1
98     /// If defined, indicates that cpptl vector based map should be used instead of std::map
99     /// as Value container.
100     //# define JSON_USE_CPPTL_SMALLMAP 1
101     /// If defined, indicates that Json specific container should be used
102     /// (hash table & simple deque container with customizable allocator).
103     /// THIS FEATURE IS STILL EXPERIMENTAL! There is know bugs: See #3177332
104     //# define JSON_VALUE_USE_INTERNAL_MAP 1
105     /// Force usage of standard new/malloc based allocator instead of memory pool based allocator.
106     /// The memory pools allocator used optimization (initializing Value and ValueInternalLink
107     /// as if it was a POD) that may cause some validation tool to report errors.
108     /// Only has effects if JSON_VALUE_USE_INTERNAL_MAP is defined.
109     //# define JSON_USE_SIMPLE_INTERNAL_ALLOCATOR 1
110    
111     // If non-zero, the library uses exceptions to report bad input instead of C
112     // assertion macros. The default is to use exceptions.
113     # ifndef JSON_USE_EXCEPTION
114     # define JSON_USE_EXCEPTION 1
115     # endif
116    
117     /// If defined, indicates that the source file is amalgated
118     /// to prevent private header inclusion.
119     /// Remarks: it is automatically defined in the generated amalgated header.
120     // #define JSON_IS_AMALGAMATION
121    
122    
123     # ifdef JSON_IN_CPPTL
124     # include <cpptl/config.h>
125     # ifndef JSON_USE_CPPTL
126     # define JSON_USE_CPPTL 1
127     # endif
128     # endif
129    
130     # ifdef JSON_IN_CPPTL
131     # define JSON_API CPPTL_API
132     # elif defined(JSON_DLL_BUILD)
133     # define JSON_API __declspec(dllexport)
134     # elif defined(JSON_DLL)
135     # define JSON_API __declspec(dllimport)
136     # else
137     # define JSON_API
138     # endif
139    
140     // If JSON_NO_INT64 is defined, then Json only support C++ "int" type for integer
141     // Storages, and 64 bits integer support is disabled.
142     // #define JSON_NO_INT64 1
143    
144     #if defined(_MSC_VER) && _MSC_VER <= 1200 // MSVC 6
145     // Microsoft Visual Studio 6 only support conversion from __int64 to double
146     // (no conversion from unsigned __int64).
147     #define JSON_USE_INT64_DOUBLE_CONVERSION 1
148     #endif // if defined(_MSC_VER) && _MSC_VER < 1200 // MSVC 6
149    
150     #if defined(_MSC_VER) && _MSC_VER >= 1500 // MSVC 2008
151     /// Indicates that the following function is deprecated.
152     # define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
153     #endif
154    
155     #if !defined(JSONCPP_DEPRECATED)
156     # define JSONCPP_DEPRECATED(message)
157     #endif // if !defined(JSONCPP_DEPRECATED)
158    
159     namespace Json {
160     typedef int Int;
161     typedef unsigned int UInt;
162     # if defined(JSON_NO_INT64)
163     typedef int LargestInt;
164     typedef unsigned int LargestUInt;
165     # undef JSON_HAS_INT64
166     # else // if defined(JSON_NO_INT64)
167     // For Microsoft Visual use specific types as long long is not supported
168     # if defined(_MSC_VER) // Microsoft Visual Studio
169     typedef __int64 Int64;
170     typedef unsigned __int64 UInt64;
171     # else // if defined(_MSC_VER) // Other platforms, use long long
172     typedef long long int Int64;
173     typedef unsigned long long int UInt64;
174     # endif // if defined(_MSC_VER)
175     typedef Int64 LargestInt;
176     typedef UInt64 LargestUInt;
177     # define JSON_HAS_INT64
178     # endif // if defined(JSON_NO_INT64)
179     } // end namespace Json
180    
181    
182     #endif // JSON_CONFIG_H_INCLUDED
183    
184     // //////////////////////////////////////////////////////////////////////
185     // End of content of file: include/json/config.h
186     // //////////////////////////////////////////////////////////////////////
187    
188    
189    
190    
191    
192    
193     // //////////////////////////////////////////////////////////////////////
194     // Beginning of content of file: include/json/forwards.h
195     // //////////////////////////////////////////////////////////////////////
196    
197     // Copyright 2007-2010 Baptiste Lepilleur
198     // Distributed under MIT license, or public domain if desired and
199     // recognized in your jurisdiction.
200     // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
201    
202     #ifndef JSON_FORWARDS_H_INCLUDED
203     # define JSON_FORWARDS_H_INCLUDED
204    
205     #if !defined(JSON_IS_AMALGAMATION)
206     # include "config.h"
207     #endif // if !defined(JSON_IS_AMALGAMATION)
208    
209     namespace Json {
210    
211     // writer.h
212     class FastWriter;
213     class StyledWriter;
214    
215     // reader.h
216     class Reader;
217    
218     // features.h
219     class Features;
220    
221     // value.h
222     typedef unsigned int ArrayIndex;
223     class StaticString;
224     class Path;
225     class PathArgument;
226     class Value;
227     class ValueIteratorBase;
228     class ValueIterator;
229     class ValueConstIterator;
230     #ifdef JSON_VALUE_USE_INTERNAL_MAP
231     class ValueMapAllocator;
232     class ValueInternalLink;
233     class ValueInternalArray;
234     class ValueInternalMap;
235     #endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP
236    
237     } // namespace Json
238    
239    
240     #endif // JSON_FORWARDS_H_INCLUDED
241    
242     // //////////////////////////////////////////////////////////////////////
243     // End of content of file: include/json/forwards.h
244     // //////////////////////////////////////////////////////////////////////
245    
246    
247    
248    
249    
250    
251     // //////////////////////////////////////////////////////////////////////
252     // Beginning of content of file: include/json/features.h
253     // //////////////////////////////////////////////////////////////////////
254    
255     // Copyright 2007-2010 Baptiste Lepilleur
256     // Distributed under MIT license, or public domain if desired and
257     // recognized in your jurisdiction.
258     // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
259    
260     #ifndef CPPTL_JSON_FEATURES_H_INCLUDED
261     # define CPPTL_JSON_FEATURES_H_INCLUDED
262    
263     #if !defined(JSON_IS_AMALGAMATION)
264     # include "forwards.h"
265     #endif // if !defined(JSON_IS_AMALGAMATION)
266    
267     namespace Json {
268    
269     /** \brief Configuration passed to reader and writer.
270     * This configuration object can be used to force the Reader or Writer
271     * to behave in a standard conforming way.
272     */
273     class JSON_API Features
274     {
275     public:
276     /** \brief A configuration that allows all features and assumes all strings are UTF-8.
277     * - C & C++ comments are allowed
278     * - Root object can be any JSON value
279     * - Assumes Value strings are encoded in UTF-8
280     */
281     static Features all();
282    
283     /** \brief A configuration that is strictly compatible with the JSON specification.
284     * - Comments are forbidden.
285     * - Root object must be either an array or an object value.
286     * - Assumes Value strings are encoded in UTF-8
287     */
288     static Features strictMode();
289    
290     /** \brief Initialize the configuration like JsonConfig::allFeatures;
291     */
292     Features();
293    
294     /// \c true if comments are allowed. Default: \c true.
295     bool allowComments_;
296    
297     /// \c true if root must be either an array or an object value. Default: \c false.
298     bool strictRoot_;
299     };
300    
301     } // namespace Json
302    
303     #endif // CPPTL_JSON_FEATURES_H_INCLUDED
304    
305     // //////////////////////////////////////////////////////////////////////
306     // End of content of file: include/json/features.h
307     // //////////////////////////////////////////////////////////////////////
308    
309    
310    
311    
312    
313    
314     // //////////////////////////////////////////////////////////////////////
315     // Beginning of content of file: include/json/value.h
316     // //////////////////////////////////////////////////////////////////////
317    
318     // Copyright 2007-2010 Baptiste Lepilleur
319     // Distributed under MIT license, or public domain if desired and
320     // recognized in your jurisdiction.
321     // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
322    
323     #ifndef CPPTL_JSON_H_INCLUDED
324     # define CPPTL_JSON_H_INCLUDED
325    
326     #if !defined(JSON_IS_AMALGAMATION)
327     # include "forwards.h"
328     #endif // if !defined(JSON_IS_AMALGAMATION)
329     # include <string>
330     # include <vector>
331    
332     # ifndef JSON_USE_CPPTL_SMALLMAP
333     # include <map>
334     # else
335     # include <cpptl/smallmap.h>
336     # endif
337     # ifdef JSON_USE_CPPTL
338     # include <cpptl/forwards.h>
339     # endif
340    
341     /** \brief JSON (JavaScript Object Notation).
342     */
343     namespace Json {
344    
345     /** \brief Type of the value held by a Value object.
346     */
347     enum ValueType
348     {
349     nullValue = 0, ///< 'null' value
350     intValue, ///< signed integer value
351     uintValue, ///< unsigned integer value
352     realValue, ///< double value
353     stringValue, ///< UTF-8 string value
354     booleanValue, ///< bool value
355     arrayValue, ///< array value (ordered list)
356     objectValue ///< object value (collection of name/value pairs).
357     };
358    
359     enum CommentPlacement
360     {
361     commentBefore = 0, ///< a comment placed on the line before a value
362     commentAfterOnSameLine, ///< a comment just after a value on the same line
363     commentAfter, ///< a comment on the line after a value (only make sense for root value)
364     numberOfCommentPlacement
365     };
366    
367     //# ifdef JSON_USE_CPPTL
368     // typedef CppTL::AnyEnumerator<const char *> EnumMemberNames;
369     // typedef CppTL::AnyEnumerator<const Value &> EnumValues;
370     //# endif
371    
372     /** \brief Lightweight wrapper to tag static string.
373     *
374     * Value constructor and objectValue member assignement takes advantage of the
375     * StaticString and avoid the cost of string duplication when storing the
376     * string or the member name.
377     *
378     * Example of usage:
379     * \code
380     * Json::Value aValue( StaticString("some text") );
381     * Json::Value object;
382     * static const StaticString code("code");
383     * object[code] = 1234;
384     * \endcode
385     */
386     class JSON_API StaticString
387     {
388     public:
389     explicit StaticString( const char *czstring )
390     : str_( czstring )
391     {
392     }
393    
394     operator const char *() const
395     {
396     return str_;
397     }
398    
399     const char *c_str() const
400     {
401     return str_;
402     }
403    
404     private:
405     const char *str_;
406     };
407    
408     /** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
409     *
410     * This class is a discriminated union wrapper that can represents a:
411     * - signed integer [range: Value::minInt - Value::maxInt]
412     * - unsigned integer (range: 0 - Value::maxUInt)
413     * - double
414     * - UTF-8 string
415     * - boolean
416     * - 'null'
417     * - an ordered list of Value
418     * - collection of name/value pairs (javascript object)
419     *
420     * The type of the held value is represented by a #ValueType and
421     * can be obtained using type().
422     *
423     * values of an #objectValue or #arrayValue can be accessed using operator[]() methods.
424     * Non const methods will automatically create the a #nullValue element
425     * if it does not exist.
426     * The sequence of an #arrayValue will be automatically resize and initialized
427     * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
428     *
429     * The get() methods can be used to obtanis default value in the case the required element
430     * does not exist.
431     *
432     * It is possible to iterate over the list of a #objectValue values using
433     * the getMemberNames() method.
434     */
435     class JSON_API Value
436     {
437     friend class ValueIteratorBase;
438     # ifdef JSON_VALUE_USE_INTERNAL_MAP
439     friend class ValueInternalLink;
440     friend class ValueInternalMap;
441     # endif
442     public:
443     typedef std::vector<std::string> Members;
444     typedef ValueIterator iterator;
445     typedef ValueConstIterator const_iterator;
446     typedef Json::UInt UInt;
447     typedef Json::Int Int;
448     # if defined(JSON_HAS_INT64)
449     typedef Json::UInt64 UInt64;
450     typedef Json::Int64 Int64;
451     #endif // defined(JSON_HAS_INT64)
452     typedef Json::LargestInt LargestInt;
453     typedef Json::LargestUInt LargestUInt;
454     typedef Json::ArrayIndex ArrayIndex;
455    
456     static const Value null;
457     /// Minimum signed integer value that can be stored in a Json::Value.
458     static const LargestInt minLargestInt;
459     /// Maximum signed integer value that can be stored in a Json::Value.
460     static const LargestInt maxLargestInt;
461     /// Maximum unsigned integer value that can be stored in a Json::Value.
462     static const LargestUInt maxLargestUInt;
463    
464     /// Minimum signed int value that can be stored in a Json::Value.
465     static const Int minInt;
466     /// Maximum signed int value that can be stored in a Json::Value.
467     static const Int maxInt;
468     /// Maximum unsigned int value that can be stored in a Json::Value.
469     static const UInt maxUInt;
470    
471     # if defined(JSON_HAS_INT64)
472     /// Minimum signed 64 bits int value that can be stored in a Json::Value.
473     static const Int64 minInt64;
474     /// Maximum signed 64 bits int value that can be stored in a Json::Value.
475     static const Int64 maxInt64;
476     /// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
477     static const UInt64 maxUInt64;
478     #endif // defined(JSON_HAS_INT64)
479    
480     private:
481     #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
482     # ifndef JSON_VALUE_USE_INTERNAL_MAP
483     class CZString
484     {
485     public:
486     enum DuplicationPolicy
487     {
488     noDuplication = 0,
489     duplicate,
490     duplicateOnCopy
491     };
492     CZString( ArrayIndex index );
493     CZString( const char *cstr, DuplicationPolicy allocate );
494     CZString( const CZString &other );
495     ~CZString();
496     CZString &operator =( const CZString &other );
497     bool operator<( const CZString &other ) const;
498     bool operator==( const CZString &other ) const;
499     ArrayIndex index() const;
500     const char *c_str() const;
501     bool isStaticString() const;
502     private:
503     void swap( CZString &other );
504     const char *cstr_;
505     ArrayIndex index_;
506     };
507    
508     public:
509     # ifndef JSON_USE_CPPTL_SMALLMAP
510     typedef std::map<CZString, Value> ObjectValues;
511     # else
512     typedef CppTL::SmallMap<CZString, Value> ObjectValues;
513     # endif // ifndef JSON_USE_CPPTL_SMALLMAP
514     # endif // ifndef JSON_VALUE_USE_INTERNAL_MAP
515     #endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
516    
517     public:
518     /** \brief Create a default Value of the given type.
519    
520     This is a very useful constructor.
521     To create an empty array, pass arrayValue.
522     To create an empty object, pass objectValue.
523     Another Value can then be set to this one by assignment.
524     This is useful since clear() and resize() will not alter types.
525    
526     Examples:
527     \code
528     Json::Value null_value; // null
529     Json::Value arr_value(Json::arrayValue); // []
530     Json::Value obj_value(Json::objectValue); // {}
531     \endcode
532     */
533     Value( ValueType type = nullValue );
534     Value( Int value );
535     Value( UInt value );
536     #if defined(JSON_HAS_INT64)
537     Value( Int64 value );
538     Value( UInt64 value );
539     #endif // if defined(JSON_HAS_INT64)
540     Value( double value );
541     Value( const char *value );
542     Value( const char *beginValue, const char *endValue );
543     /** \brief Constructs a value from a static string.
544    
545     * Like other value string constructor but do not duplicate the string for
546     * internal storage. The given string must remain alive after the call to this
547     * constructor.
548     * Example of usage:
549     * \code
550     * Json::Value aValue( StaticString("some text") );
551     * \endcode
552     */
553     Value( const StaticString &value );
554     Value( const std::string &value );
555     # ifdef JSON_USE_CPPTL
556     Value( const CppTL::ConstString &value );
557     # endif
558     Value( bool value );
559     Value( const Value &other );
560     ~Value();
561    
562     Value &operator=( const Value &other );
563     /// Swap values.
564     /// \note Currently, comments are intentionally not swapped, for
565     /// both logic and efficiency.
566     void swap( Value &other );
567    
568     ValueType type() const;
569    
570     bool operator <( const Value &other ) const;
571     bool operator <=( const Value &other ) const;
572     bool operator >=( const Value &other ) const;
573     bool operator >( const Value &other ) const;
574    
575     bool operator ==( const Value &other ) const;
576     bool operator !=( const Value &other ) const;
577    
578     int compare( const Value &other ) const;
579    
580     const char *asCString() const;
581     std::string asString() const;
582     # ifdef JSON_USE_CPPTL
583     CppTL::ConstString asConstString() const;
584     # endif
585     Int asInt() const;
586     UInt asUInt() const;
587     #if defined(JSON_HAS_INT64)
588     Int64 asInt64() const;
589     UInt64 asUInt64() const;
590     #endif // if defined(JSON_HAS_INT64)
591     LargestInt asLargestInt() const;
592     LargestUInt asLargestUInt() const;
593     float asFloat() const;
594     double asDouble() const;
595     bool asBool() const;
596    
597     bool isNull() const;
598     bool isBool() const;
599     bool isInt() const;
600     bool isInt64() const;
601     bool isUInt() const;
602     bool isUInt64() const;
603     bool isIntegral() const;
604     bool isDouble() const;
605     bool isNumeric() const;
606     bool isString() const;
607     bool isArray() const;
608     bool isObject() const;
609    
610     bool isConvertibleTo( ValueType other ) const;
611    
612     /// Number of values in array or object
613     ArrayIndex size() const;
614    
615     /// \brief Return true if empty array, empty object, or null;
616     /// otherwise, false.
617     bool empty() const;
618    
619     /// Return isNull()
620     bool operator!() const;
621    
622     /// Remove all object members and array elements.
623     /// \pre type() is arrayValue, objectValue, or nullValue
624     /// \post type() is unchanged
625     void clear();
626    
627     /// Resize the array to size elements.
628     /// New elements are initialized to null.
629     /// May only be called on nullValue or arrayValue.
630     /// \pre type() is arrayValue or nullValue
631     /// \post type() is arrayValue
632     void resize( ArrayIndex size );
633    
634     /// Access an array element (zero based index ).
635     /// If the array contains less than index element, then null value are inserted
636     /// in the array so that its size is index+1.
637     /// (You may need to say 'value[0u]' to get your compiler to distinguish
638     /// this from the operator[] which takes a string.)
639     Value &operator[]( ArrayIndex index );
640    
641     /// Access an array element (zero based index ).
642     /// If the array contains less than index element, then null value are inserted
643     /// in the array so that its size is index+1.
644     /// (You may need to say 'value[0u]' to get your compiler to distinguish
645     /// this from the operator[] which takes a string.)
646     Value &operator[]( int index );
647    
648     /// Access an array element (zero based index )
649     /// (You may need to say 'value[0u]' to get your compiler to distinguish
650     /// this from the operator[] which takes a string.)
651     const Value &operator[]( ArrayIndex index ) const;
652    
653     /// Access an array element (zero based index )
654     /// (You may need to say 'value[0u]' to get your compiler to distinguish
655     /// this from the operator[] which takes a string.)
656     const Value &operator[]( int index ) const;
657    
658     /// If the array contains at least index+1 elements, returns the element value,
659     /// otherwise returns defaultValue.
660     Value get( ArrayIndex index,
661     const Value &defaultValue ) const;
662     /// Return true if index < size().
663     bool isValidIndex( ArrayIndex index ) const;
664     /// \brief Append value to array at the end.
665     ///
666     /// Equivalent to jsonvalue[jsonvalue.size()] = value;
667     Value &append( const Value &value );
668    
669     /// Access an object value by name, create a null member if it does not exist.
670     Value &operator[]( const char *key );
671     /// Access an object value by name, returns null if there is no member with that name.
672     const Value &operator[]( const char *key ) const;
673     /// Access an object value by name, create a null member if it does not exist.
674     Value &operator[]( const std::string &key );
675     /// Access an object value by name, returns null if there is no member with that name.
676     const Value &operator[]( const std::string &key ) const;
677     /** \brief Access an object value by name, create a null member if it does not exist.
678    
679     * If the object as no entry for that name, then the member name used to store
680     * the new entry is not duplicated.
681     * Example of use:
682     * \code
683     * Json::Value object;
684     * static const StaticString code("code");
685     * object[code] = 1234;
686     * \endcode
687     */
688     Value &operator[]( const StaticString &key );
689     # ifdef JSON_USE_CPPTL
690     /// Access an object value by name, create a null member if it does not exist.
691     Value &operator[]( const CppTL::ConstString &key );
692     /// Access an object value by name, returns null if there is no member with that name.
693     const Value &operator[]( const CppTL::ConstString &key ) const;
694     # endif
695     /// Return the member named key if it exist, defaultValue otherwise.
696     Value get( const char *key,
697     const Value &defaultValue ) const;
698     /// Return the member named key if it exist, defaultValue otherwise.
699     Value get( const std::string &key,
700     const Value &defaultValue ) const;
701     # ifdef JSON_USE_CPPTL
702     /// Return the member named key if it exist, defaultValue otherwise.
703     Value get( const CppTL::ConstString &key,
704     const Value &defaultValue ) const;
705     # endif
706     /// \brief Remove and return the named member.
707     ///
708     /// Do nothing if it did not exist.
709     /// \return the removed Value, or null.
710     /// \pre type() is objectValue or nullValue
711     /// \post type() is unchanged
712     Value removeMember( const char* key );
713     /// Same as removeMember(const char*)
714     Value removeMember( const std::string &key );
715    
716     /// Return true if the object has a member named key.
717     bool isMember( const char *key ) const;
718     /// Return true if the object has a member named key.
719     bool isMember( const std::string &key ) const;
720     # ifdef JSON_USE_CPPTL
721     /// Return true if the object has a member named key.
722     bool isMember( const CppTL::ConstString &key ) const;
723     # endif
724    
725     /// \brief Return a list of the member names.
726     ///
727     /// If null, return an empty list.
728     /// \pre type() is objectValue or nullValue
729     /// \post if type() was nullValue, it remains nullValue
730     Members getMemberNames() const;
731    
732     //# ifdef JSON_USE_CPPTL
733     // EnumMemberNames enumMemberNames() const;
734     // EnumValues enumValues() const;
735     //# endif
736    
737     /// Comments must be //... or /* ... */
738     void setComment( const char *comment,
739     CommentPlacement placement );
740     /// Comments must be //... or /* ... */
741     void setComment( const std::string &comment,
742     CommentPlacement placement );
743     bool hasComment( CommentPlacement placement ) const;
744     /// Include delimiters and embedded newlines.
745     std::string getComment( CommentPlacement placement ) const;
746    
747     std::string toStyledString() const;
748    
749     const_iterator begin() const;
750     const_iterator end() const;
751    
752     iterator begin();
753     iterator end();
754    
755     private:
756     Value &resolveReference( const char *key,
757     bool isStatic );
758    
759     # ifdef JSON_VALUE_USE_INTERNAL_MAP
760     inline bool isItemAvailable() const
761     {
762     return itemIsUsed_ == 0;
763     }
764    
765     inline void setItemUsed( bool isUsed = true )
766     {
767     itemIsUsed_ = isUsed ? 1 : 0;
768     }
769    
770     inline bool isMemberNameStatic() const
771     {
772     return memberNameIsStatic_ == 0;
773     }
774    
775     inline void setMemberNameIsStatic( bool isStatic )
776     {
777     memberNameIsStatic_ = isStatic ? 1 : 0;
778     }
779     # endif // # ifdef JSON_VALUE_USE_INTERNAL_MAP
780    
781     private:
782     struct CommentInfo
783     {
784     CommentInfo();
785     ~CommentInfo();
786    
787     void setComment( const char *text );
788    
789     char *comment_;
790     };
791    
792     //struct MemberNamesTransform
793     //{
794     // typedef const char *result_type;
795     // const char *operator()( const CZString &name ) const
796     // {
797     // return name.c_str();
798     // }
799     //};
800    
801     union ValueHolder
802     {
803     LargestInt int_;
804     LargestUInt uint_;
805     double real_;
806     bool bool_;
807     char *string_;
808     # ifdef JSON_VALUE_USE_INTERNAL_MAP
809     ValueInternalArray *array_;
810     ValueInternalMap *map_;
811     #else
812     ObjectValues *map_;
813     # endif
814     } value_;
815     ValueType type_ : 8;
816     int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
817     # ifdef JSON_VALUE_USE_INTERNAL_MAP
818     unsigned int itemIsUsed_ : 1; // used by the ValueInternalMap container.
819     int memberNameIsStatic_ : 1; // used by the ValueInternalMap container.
820     # endif
821     CommentInfo *comments_;
822     };
823    
824    
825     /** \brief Experimental and untested: represents an element of the "path" to access a node.
826     */
827     class PathArgument
828     {
829     public:
830     friend class Path;
831    
832     PathArgument();
833     PathArgument( ArrayIndex index );
834     PathArgument( const char *key );
835     PathArgument( const std::string &key );
836    
837     private:
838     enum Kind
839     {
840     kindNone = 0,
841     kindIndex,
842     kindKey
843     };
844     std::string key_;
845     ArrayIndex index_;
846     Kind kind_;
847     };
848    
849     /** \brief Experimental and untested: represents a "path" to access a node.
850     *
851     * Syntax:
852     * - "." => root node
853     * - ".[n]" => elements at index 'n' of root node (an array value)
854     * - ".name" => member named 'name' of root node (an object value)
855     * - ".name1.name2.name3"
856     * - ".[0][1][2].name1[3]"
857     * - ".%" => member name is provided as parameter
858     * - ".[%]" => index is provied as parameter
859     */
860     class Path
861     {
862     public:
863     Path( const std::string &path,
864     const PathArgument &a1 = PathArgument(),
865     const PathArgument &a2 = PathArgument(),
866     const PathArgument &a3 = PathArgument(),
867     const PathArgument &a4 = PathArgument(),
868     const PathArgument &a5 = PathArgument() );
869    
870     const Value &resolve( const Value &root ) const;
871     Value resolve( const Value &root,
872     const Value &defaultValue ) const;
873     /// Creates the "path" to access the specified node and returns a reference on the node.
874     Value &make( Value &root ) const;
875    
876     private:
877     typedef std::vector<const PathArgument *> InArgs;
878     typedef std::vector<PathArgument> Args;
879    
880     void makePath( const std::string &path,
881     const InArgs &in );
882     void addPathInArg( const std::string &path,
883     const InArgs &in,
884     InArgs::const_iterator &itInArg,
885     PathArgument::Kind kind );
886     void invalidPath( const std::string &path,
887     int location );
888    
889     Args args_;
890     };
891    
892    
893    
894     #ifdef JSON_VALUE_USE_INTERNAL_MAP
895     /** \brief Allocator to customize Value internal map.
896     * Below is an example of a simple implementation (default implementation actually
897     * use memory pool for speed).
898     * \code
899     class DefaultValueMapAllocator : public ValueMapAllocator
900     {
901     public: // overridden from ValueMapAllocator
902     virtual ValueInternalMap *newMap()
903     {
904     return new ValueInternalMap();
905     }
906    
907     virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other )
908     {
909     return new ValueInternalMap( other );
910     }
911    
912     virtual void destructMap( ValueInternalMap *map )
913     {
914     delete map;
915     }
916    
917     virtual ValueInternalLink *allocateMapBuckets( unsigned int size )
918     {
919     return new ValueInternalLink[size];
920     }
921    
922     virtual void releaseMapBuckets( ValueInternalLink *links )
923     {
924     delete [] links;
925     }
926    
927     virtual ValueInternalLink *allocateMapLink()
928     {
929     return new ValueInternalLink();
930     }
931    
932     virtual void releaseMapLink( ValueInternalLink *link )
933     {
934     delete link;
935     }
936     };
937     * \endcode
938     */
939     class JSON_API ValueMapAllocator
940     {
941     public:
942     virtual ~ValueMapAllocator();
943     virtual ValueInternalMap *newMap() = 0;
944     virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other ) = 0;
945     virtual void destructMap( ValueInternalMap *map ) = 0;
946     virtual ValueInternalLink *allocateMapBuckets( unsigned int size ) = 0;
947     virtual void releaseMapBuckets( ValueInternalLink *links ) = 0;
948     virtual ValueInternalLink *allocateMapLink() = 0;
949     virtual void releaseMapLink( ValueInternalLink *link ) = 0;
950     };
951    
952     /** \brief ValueInternalMap hash-map bucket chain link (for internal use only).
953     * \internal previous_ & next_ allows for bidirectional traversal.
954     */
955     class JSON_API ValueInternalLink
956     {
957     public:
958     enum { itemPerLink = 6 }; // sizeof(ValueInternalLink) = 128 on 32 bits architecture.
959     enum InternalFlags {
960     flagAvailable = 0,
961     flagUsed = 1
962     };
963    
964     ValueInternalLink();
965    
966     ~ValueInternalLink();
967    
968     Value items_[itemPerLink];
969     char *keys_[itemPerLink];
970     ValueInternalLink *previous_;
971     ValueInternalLink *next_;
972     };
973    
974    
975     /** \brief A linked page based hash-table implementation used internally by Value.
976     * \internal ValueInternalMap is a tradional bucket based hash-table, with a linked
977     * list in each bucket to handle collision. There is an addional twist in that
978     * each node of the collision linked list is a page containing a fixed amount of
979     * value. This provides a better compromise between memory usage and speed.
980     *
981     * Each bucket is made up of a chained list of ValueInternalLink. The last
982     * link of a given bucket can be found in the 'previous_' field of the following bucket.
983     * The last link of the last bucket is stored in tailLink_ as it has no following bucket.
984     * Only the last link of a bucket may contains 'available' item. The last link always
985     * contains at least one element unless is it the bucket one very first link.
986     */
987     class JSON_API ValueInternalMap
988     {
989     friend class ValueIteratorBase;
990     friend class Value;
991     public:
992     typedef unsigned int HashKey;
993     typedef unsigned int BucketIndex;
994    
995     # ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
996     struct IteratorState
997     {
998     IteratorState()
999     : map_(0)
1000     , link_(0)
1001     , itemIndex_(0)
1002     , bucketIndex_(0)
1003     {
1004     }
1005     ValueInternalMap *map_;
1006     ValueInternalLink *link_;
1007     BucketIndex itemIndex_;
1008     BucketIndex bucketIndex_;
1009     };
1010     # endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
1011    
1012     ValueInternalMap();
1013     ValueInternalMap( const ValueInternalMap &other );
1014     ValueInternalMap &operator =( const ValueInternalMap &other );
1015     ~ValueInternalMap();
1016    
1017     void swap( ValueInternalMap &other );
1018    
1019     BucketIndex size() const;
1020    
1021     void clear();
1022    
1023     bool reserveDelta( BucketIndex growth );
1024    
1025     bool reserve( BucketIndex newItemCount );
1026    
1027     const Value *find( const char *key ) const;
1028    
1029     Value *find( const char *key );
1030    
1031     Value &resolveReference( const char *key,
1032     bool isStatic );
1033    
1034     void remove( const char *key );
1035    
1036     void doActualRemove( ValueInternalLink *link,
1037     BucketIndex index,
1038     BucketIndex bucketIndex );
1039    
1040     ValueInternalLink *&getLastLinkInBucket( BucketIndex bucketIndex );
1041    
1042     Value &setNewItem( const char *key,
1043     bool isStatic,
1044     ValueInternalLink *link,
1045     BucketIndex index );
1046    
1047     Value &unsafeAdd( const char *key,
1048     bool isStatic,
1049     HashKey hashedKey );
1050    
1051     HashKey hash( const char *key ) const;
1052    
1053     int compare( const ValueInternalMap &other ) const;
1054    
1055     private:
1056     void makeBeginIterator( IteratorState &it ) const;
1057     void makeEndIterator( IteratorState &it ) const;
1058     static bool equals( const IteratorState &x, const IteratorState &other );
1059     static void increment( IteratorState &iterator );
1060     static void incrementBucket( IteratorState &iterator );
1061     static void decrement( IteratorState &iterator );
1062     static const char *key( const IteratorState &iterator );
1063     static const char *key( const IteratorState &iterator, bool &isStatic );
1064     static Value &value( const IteratorState &iterator );
1065     static int distance( const IteratorState &x, const IteratorState &y );
1066    
1067     private:
1068     ValueInternalLink *buckets_;
1069     ValueInternalLink *tailLink_;
1070     BucketIndex bucketsSize_;
1071     BucketIndex itemCount_;
1072     };
1073    
1074     /** \brief A simplified deque implementation used internally by Value.
1075     * \internal
1076     * It is based on a list of fixed "page", each page contains a fixed number of items.
1077     * Instead of using a linked-list, a array of pointer is used for fast item look-up.
1078     * Look-up for an element is as follow:
1079     * - compute page index: pageIndex = itemIndex / itemsPerPage
1080     * - look-up item in page: pages_[pageIndex][itemIndex % itemsPerPage]
1081     *
1082     * Insertion is amortized constant time (only the array containing the index of pointers
1083     * need to be reallocated when items are appended).
1084     */
1085     class JSON_API ValueInternalArray
1086     {
1087     friend class Value;
1088     friend class ValueIteratorBase;
1089     public:
1090     enum { itemsPerPage = 8 }; // should be a power of 2 for fast divide and modulo.
1091     typedef Value::ArrayIndex ArrayIndex;
1092     typedef unsigned int PageIndex;
1093    
1094     # ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
1095     struct IteratorState // Must be a POD
1096     {
1097     IteratorState()
1098     : array_(0)
1099     , currentPageIndex_(0)
1100     , currentItemIndex_(0)
1101     {
1102     }
1103     ValueInternalArray *array_;
1104     Value **currentPageIndex_;
1105     unsigned int currentItemIndex_;
1106     };
1107     # endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
1108    
1109     ValueInternalArray();
1110     ValueInternalArray( const ValueInternalArray &other );
1111     ValueInternalArray &operator =( const ValueInternalArray &other );
1112     ~ValueInternalArray();
1113     void swap( ValueInternalArray &other );
1114    
1115     void clear();
1116     void resize( ArrayIndex newSize );
1117    
1118     Value &resolveReference( ArrayIndex index );
1119    
1120     Value *find( ArrayIndex index ) const;
1121    
1122     ArrayIndex size() const;
1123    
1124     int compare( const ValueInternalArray &other ) const;
1125    
1126     private:
1127     static bool equals( const IteratorState &x, const IteratorState &other );
1128     static void increment( IteratorState &iterator );
1129     static void decrement( IteratorState &iterator );
1130     static Value &dereference( const IteratorState &iterator );
1131     static Value &unsafeDereference( const IteratorState &iterator );
1132     static int distance( const IteratorState &x, const IteratorState &y );
1133     static ArrayIndex indexOf( const IteratorState &iterator );
1134     void makeBeginIterator( IteratorState &it ) const;
1135     void makeEndIterator( IteratorState &it ) const;
1136     void makeIterator( IteratorState &it, ArrayIndex index ) const;
1137    
1138     void makeIndexValid( ArrayIndex index );
1139    
1140     Value **pages_;
1141     ArrayIndex size_;
1142     PageIndex pageCount_;
1143     };
1144    
1145     /** \brief Experimental: do not use. Allocator to customize Value internal array.
1146     * Below is an example of a simple implementation (actual implementation use
1147     * memory pool).
1148     \code
1149     class DefaultValueArrayAllocator : public ValueArrayAllocator
1150     {
1151     public: // overridden from ValueArrayAllocator
1152     virtual ~DefaultValueArrayAllocator()
1153     {
1154     }
1155    
1156     virtual ValueInternalArray *newArray()
1157     {
1158     return new ValueInternalArray();
1159     }
1160    
1161     virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other )
1162     {
1163     return new ValueInternalArray( other );
1164     }
1165    
1166     virtual void destruct( ValueInternalArray *array )
1167     {
1168     delete array;
1169     }
1170    
1171     virtual void reallocateArrayPageIndex( Value **&indexes,
1172     ValueInternalArray::PageIndex &indexCount,
1173     ValueInternalArray::PageIndex minNewIndexCount )
1174     {
1175     ValueInternalArray::PageIndex newIndexCount = (indexCount*3)/2 + 1;
1176     if ( minNewIndexCount > newIndexCount )
1177     newIndexCount = minNewIndexCount;
1178     void *newIndexes = realloc( indexes, sizeof(Value*) * newIndexCount );
1179     if ( !newIndexes )
1180     throw std::bad_alloc();
1181     indexCount = newIndexCount;
1182     indexes = static_cast<Value **>( newIndexes );
1183     }
1184     virtual void releaseArrayPageIndex( Value **indexes,
1185     ValueInternalArray::PageIndex indexCount )
1186     {
1187     if ( indexes )
1188     free( indexes );
1189     }
1190    
1191     virtual Value *allocateArrayPage()
1192     {
1193     return static_cast<Value *>( malloc( sizeof(Value) * ValueInternalArray::itemsPerPage ) );
1194     }
1195    
1196     virtual void releaseArrayPage( Value *value )
1197     {
1198     if ( value )
1199     free( value );
1200     }
1201     };
1202     \endcode
1203     */
1204     class JSON_API ValueArrayAllocator
1205     {
1206     public:
1207     virtual ~ValueArrayAllocator();
1208     virtual ValueInternalArray *newArray() = 0;
1209     virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other ) = 0;
1210     virtual void destructArray( ValueInternalArray *array ) = 0;
1211     /** \brief Reallocate array page index.
1212     * Reallocates an array of pointer on each page.
1213     * \param indexes [input] pointer on the current index. May be \c NULL.
1214     * [output] pointer on the new index of at least
1215     * \a minNewIndexCount pages.
1216     * \param indexCount [input] current number of pages in the index.
1217     * [output] number of page the reallocated index can handle.
1218     * \b MUST be >= \a minNewIndexCount.
1219     * \param minNewIndexCount Minimum number of page the new index must be able to
1220     * handle.
1221     */
1222     virtual void reallocateArrayPageIndex( Value **&indexes,
1223     ValueInternalArray::PageIndex &indexCount,
1224     ValueInternalArray::PageIndex minNewIndexCount ) = 0;
1225     virtual void releaseArrayPageIndex( Value **indexes,
1226     ValueInternalArray::PageIndex indexCount ) = 0;
1227     virtual Value *allocateArrayPage() = 0;
1228     virtual void releaseArrayPage( Value *value ) = 0;
1229     };
1230     #endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP
1231    
1232    
1233     /** \brief base class for Value iterators.
1234     *
1235     */
1236     class ValueIteratorBase
1237     {
1238     public:
1239     typedef unsigned int size_t;
1240     typedef int difference_type;
1241     typedef ValueIteratorBase SelfType;
1242    
1243     ValueIteratorBase();
1244     #ifndef JSON_VALUE_USE_INTERNAL_MAP
1245     explicit ValueIteratorBase( const Value::ObjectValues::iterator &current );
1246     #else
1247     ValueIteratorBase( const ValueInternalArray::IteratorState &state );
1248     ValueIteratorBase( const ValueInternalMap::IteratorState &state );
1249     #endif
1250    
1251     bool operator ==( const SelfType &other ) const
1252     {
1253     return isEqual( other );
1254     }
1255    
1256     bool operator !=( const SelfType &other ) const
1257     {
1258     return !isEqual( other );
1259     }
1260    
1261     difference_type operator -( const SelfType &other ) const
1262     {
1263     return computeDistance( other );
1264     }
1265    
1266     /// Return either the index or the member name of the referenced value as a Value.
1267     Value key() const;
1268    
1269     /// Return the index of the referenced Value. -1 if it is not an arrayValue.
1270     UInt index() const;
1271    
1272     /// Return the member name of the referenced Value. "" if it is not an objectValue.
1273     const char *memberName() const;
1274    
1275     protected:
1276     Value &deref() const;
1277    
1278     void increment();
1279    
1280     void decrement();
1281    
1282     difference_type computeDistance( const SelfType &other ) const;
1283    
1284     bool isEqual( const SelfType &other ) const;
1285    
1286     void copy( const SelfType &other );
1287    
1288     private:
1289     #ifndef JSON_VALUE_USE_INTERNAL_MAP
1290     Value::ObjectValues::iterator current_;
1291     // Indicates that iterator is for a null value.
1292     bool isNull_;
1293     #else
1294     union
1295     {
1296     ValueInternalArray::IteratorState array_;
1297     ValueInternalMap::IteratorState map_;
1298     } iterator_;
1299     bool isArray_;
1300     #endif
1301     };
1302    
1303     /** \brief const iterator for object and array value.
1304     *
1305     */
1306     class ValueConstIterator : public ValueIteratorBase
1307     {
1308     friend class Value;
1309     public:
1310     typedef unsigned int size_t;
1311     typedef int difference_type;
1312     typedef const Value &reference;
1313     typedef const Value *pointer;
1314     typedef ValueConstIterator SelfType;
1315    
1316     ValueConstIterator();
1317     private:
1318     /*! \internal Use by Value to create an iterator.
1319     */
1320     #ifndef JSON_VALUE_USE_INTERNAL_MAP
1321     explicit ValueConstIterator( const Value::ObjectValues::iterator &current );
1322     #else
1323     ValueConstIterator( const ValueInternalArray::IteratorState &state );
1324     ValueConstIterator( const ValueInternalMap::IteratorState &state );
1325     #endif
1326     public:
1327     SelfType &operator =( const ValueIteratorBase &other );
1328    
1329     SelfType operator++( int )
1330     {
1331     SelfType temp( *this );
1332     ++*this;
1333     return temp;
1334     }
1335    
1336     SelfType operator--( int )
1337     {
1338     SelfType temp( *this );
1339     --*this;
1340     return temp;
1341     }
1342    
1343     SelfType &operator--()
1344     {
1345     decrement();
1346     return *this;
1347     }
1348    
1349     SelfType &operator++()
1350     {
1351     increment();
1352     return *this;
1353     }
1354    
1355     reference operator *() const
1356     {
1357     return deref();
1358     }
1359     };
1360    
1361    
1362     /** \brief Iterator for object and array value.
1363     */
1364     class ValueIterator : public ValueIteratorBase
1365     {
1366     friend class Value;
1367     public:
1368     typedef unsigned int size_t;
1369     typedef int difference_type;
1370     typedef Value &reference;
1371     typedef Value *pointer;
1372     typedef ValueIterator SelfType;
1373    
1374     ValueIterator();
1375     ValueIterator( const ValueConstIterator &other );
1376     ValueIterator( const ValueIterator &other );
1377     private:
1378     /*! \internal Use by Value to create an iterator.
1379     */
1380     #ifndef JSON_VALUE_USE_INTERNAL_MAP
1381     explicit ValueIterator( const Value::ObjectValues::iterator &current );
1382     #else
1383     ValueIterator( const ValueInternalArray::IteratorState &state );
1384     ValueIterator( const ValueInternalMap::IteratorState &state );
1385     #endif
1386     public:
1387    
1388     SelfType &operator =( const SelfType &other );
1389    
1390     SelfType operator++( int )
1391     {
1392     SelfType temp( *this );
1393     ++*this;
1394     return temp;
1395     }
1396    
1397     SelfType operator--( int )
1398     {
1399     SelfType temp( *this );
1400     --*this;
1401     return temp;
1402     }
1403    
1404     SelfType &operator--()
1405     {
1406     decrement();
1407     return *this;
1408     }
1409    
1410     SelfType &operator++()
1411     {
1412     increment();
1413     return *this;
1414     }
1415    
1416     reference operator *() const
1417     {
1418     return deref();
1419     }
1420     };
1421    
1422    
1423     } // namespace Json
1424    
1425    
1426     #endif // CPPTL_JSON_H_INCLUDED
1427    
1428     // //////////////////////////////////////////////////////////////////////
1429     // End of content of file: include/json/value.h
1430     // //////////////////////////////////////////////////////////////////////
1431    
1432    
1433    
1434    
1435    
1436    
1437     // //////////////////////////////////////////////////////////////////////
1438     // Beginning of content of file: include/json/reader.h
1439     // //////////////////////////////////////////////////////////////////////
1440    
1441     // Copyright 2007-2010 Baptiste Lepilleur
1442     // Distributed under MIT license, or public domain if desired and
1443     // recognized in your jurisdiction.
1444     // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1445    
1446     #ifndef CPPTL_JSON_READER_H_INCLUDED
1447     # define CPPTL_JSON_READER_H_INCLUDED
1448    
1449     #if !defined(JSON_IS_AMALGAMATION)
1450     # include "features.h"
1451     # include "value.h"
1452     #endif // if !defined(JSON_IS_AMALGAMATION)
1453     # include <deque>
1454     # include <stack>
1455     # include <string>
1456    
1457     namespace Json {
1458    
1459     /** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a Value.
1460     *
1461     */
1462     class JSON_API Reader
1463     {
1464     public:
1465     typedef char Char;
1466     typedef const Char *Location;
1467    
1468     /** \brief Constructs a Reader allowing all features
1469     * for parsing.
1470     */
1471     Reader();
1472    
1473     /** \brief Constructs a Reader allowing the specified feature set
1474     * for parsing.
1475     */
1476     Reader( const Features &features );
1477    
1478     /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a> document.
1479     * \param document UTF-8 encoded string containing the document to read.
1480     * \param root [out] Contains the root value of the document if it was
1481     * successfully parsed.
1482     * \param collectComments \c true to collect comment and allow writing them back during
1483     * serialization, \c false to discard comments.
1484     * This parameter is ignored if Features::allowComments_
1485     * is \c false.
1486     * \return \c true if the document was successfully parsed, \c false if an error occurred.
1487     */
1488     bool parse( const std::string &document,
1489     Value &root,
1490     bool collectComments = true );
1491    
1492     /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a> document.
1493     * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the document to read.
1494     * \param endDoc Pointer on the end of the UTF-8 encoded string of the document to read.
1495     \ Must be >= beginDoc.
1496     * \param root [out] Contains the root value of the document if it was
1497     * successfully parsed.
1498     * \param collectComments \c true to collect comment and allow writing them back during
1499     * serialization, \c false to discard comments.
1500     * This parameter is ignored if Features::allowComments_
1501     * is \c false.
1502     * \return \c true if the document was successfully parsed, \c false if an error occurred.
1503     */
1504     bool parse( const char *beginDoc, const char *endDoc,
1505     Value &root,
1506     bool collectComments = true );
1507    
1508     /// \brief Parse from input stream.
1509     /// \see Json::operator>>(std::istream&, Json::Value&).
1510     bool parse( std::istream &is,
1511     Value &root,
1512     bool collectComments = true );
1513    
1514     /** \brief Returns a user friendly string that list errors in the parsed document.
1515     * \return Formatted error message with the list of errors with their location in
1516     * the parsed document. An empty string is returned if no error occurred
1517     * during parsing.
1518     * \deprecated Use getFormattedErrorMessages() instead (typo fix).
1519     */
1520     JSONCPP_DEPRECATED("Use getFormattedErrorMessages instead")
1521     std::string getFormatedErrorMessages() const;
1522    
1523     /** \brief Returns a user friendly string that list errors in the parsed document.
1524     * \return Formatted error message with the list of errors with their location in
1525     * the parsed document. An empty string is returned if no error occurred
1526     * during parsing.
1527     */
1528     std::string getFormattedErrorMessages() const;
1529    
1530     private:
1531     enum TokenType
1532     {
1533     tokenEndOfStream = 0,
1534     tokenObjectBegin,
1535     tokenObjectEnd,
1536     tokenArrayBegin,
1537     tokenArrayEnd,
1538     tokenString,
1539     tokenNumber,
1540     tokenTrue,
1541     tokenFalse,
1542     tokenNull,
1543     tokenArraySeparator,
1544     tokenMemberSeparator,
1545     tokenComment,
1546     tokenError
1547     };
1548    
1549     class Token
1550     {
1551     public:
1552     TokenType type_;
1553     Location start_;
1554     Location end_;
1555     };
1556    
1557     class ErrorInfo
1558     {
1559     public:
1560     Token token_;
1561     std::string message_;
1562     Location extra_;
1563     };
1564    
1565     typedef std::deque<ErrorInfo> Errors;
1566    
1567     bool expectToken( TokenType type, Token &token, const char *message );
1568     bool readToken( Token &token );
1569     void skipSpaces();
1570     bool match( Location pattern,
1571     int patternLength );
1572     bool readComment();
1573     bool readCStyleComment();
1574     bool readCppStyleComment();
1575     bool readString();
1576     void readNumber();
1577     bool readValue();
1578     bool readObject( Token &token );
1579     bool readArray( Token &token );
1580     bool decodeNumber( Token &token );
1581     bool decodeString( Token &token );
1582     bool decodeString( Token &token, std::string &decoded );
1583     bool decodeDouble( Token &token );
1584     bool decodeUnicodeCodePoint( Token &token,
1585     Location &current,
1586     Location end,
1587     unsigned int &unicode );
1588     bool decodeUnicodeEscapeSequence( Token &token,
1589     Location &current,
1590     Location end,
1591     unsigned int &unicode );
1592     bool addError( const std::string &message,
1593     Token &token,
1594     Location extra = 0 );
1595     bool recoverFromError( TokenType skipUntilToken );
1596     bool addErrorAndRecover( const std::string &message,
1597     Token &token,
1598     TokenType skipUntilToken );
1599     void skipUntilSpace();
1600     Value &currentValue();
1601     Char getNextChar();
1602     void getLocationLineAndColumn( Location location,
1603     int &line,
1604     int &column ) const;
1605     std::string getLocationLineAndColumn( Location location ) const;
1606     void addComment( Location begin,
1607     Location end,
1608     CommentPlacement placement );
1609     void skipCommentTokens( Token &token );
1610    
1611     typedef std::stack<Value *> Nodes;
1612     Nodes nodes_;
1613     Errors errors_;
1614     std::string document_;
1615     Location begin_;
1616     Location end_;
1617     Location current_;
1618     Location lastValueEnd_;
1619     Value *lastValue_;
1620     std::string commentsBefore_;
1621     Features features_;
1622     bool collectComments_;
1623     };
1624    
1625     /** \brief Read from 'sin' into 'root'.
1626    
1627     Always keep comments from the input JSON.
1628    
1629     This can be used to read a file into a particular sub-object.
1630     For example:
1631     \code
1632     Json::Value root;
1633     cin >> root["dir"]["file"];
1634     cout << root;
1635     \endcode
1636     Result:
1637     \verbatim
1638     {
1639     "dir": {
1640     "file": {
1641     // The input stream JSON would be nested here.
1642     }
1643     }
1644     }
1645     \endverbatim
1646     \throw std::exception on parse error.
1647     \see Json::operator<<()
1648     */
1649     std::istream& operator>>( std::istream&, Value& );
1650    
1651     } // namespace Json
1652    
1653     #endif // CPPTL_JSON_READER_H_INCLUDED
1654    
1655     // //////////////////////////////////////////////////////////////////////
1656     // End of content of file: include/json/reader.h
1657     // //////////////////////////////////////////////////////////////////////
1658    
1659    
1660    
1661    
1662    
1663    
1664     // //////////////////////////////////////////////////////////////////////
1665     // Beginning of content of file: include/json/writer.h
1666     // //////////////////////////////////////////////////////////////////////
1667    
1668     // Copyright 2007-2010 Baptiste Lepilleur
1669     // Distributed under MIT license, or public domain if desired and
1670     // recognized in your jurisdiction.
1671     // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1672    
1673     #ifndef JSON_WRITER_H_INCLUDED
1674     # define JSON_WRITER_H_INCLUDED
1675    
1676     #if !defined(JSON_IS_AMALGAMATION)
1677     # include "value.h"
1678     #endif // if !defined(JSON_IS_AMALGAMATION)
1679     # include <vector>
1680     # include <string>
1681    
1682     namespace Json {
1683    
1684     class Value;
1685    
1686     /** \brief Abstract class for writers.
1687     */
1688     class JSON_API Writer
1689     {
1690     public:
1691     virtual ~Writer();
1692    
1693     virtual std::string write( const Value &root ) = 0;
1694     };
1695    
1696     /** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format without formatting (not human friendly).
1697     *
1698     * The JSON document is written in a single line. It is not intended for 'human' consumption,
1699     * but may be usefull to support feature such as RPC where bandwith is limited.
1700     * \sa Reader, Value
1701     */
1702     class JSON_API FastWriter : public Writer
1703     {
1704     public:
1705     FastWriter();
1706     virtual ~FastWriter(){}
1707    
1708     void enableYAMLCompatibility();
1709    
1710     /** \brief 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     void dropNullPlaceholders();
1716    
1717     public: // overridden from Writer
1718     virtual std::string write( const Value &root );
1719    
1720     private:
1721     void writeValue( const Value &value );
1722    
1723     std::string document_;
1724     bool yamlCompatiblityEnabled_;
1725     bool dropNullPlaceholders_;
1726     };
1727    
1728     /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a human friendly way.
1729     *
1730     * The rules for line break and indent are as follow:
1731     * - Object value:
1732     * - if empty then print {} without indent and line break
1733     * - if not empty the print '{', line break & indent, print one value per line
1734     * and then unindent and line break and print '}'.
1735     * - Array value:
1736     * - if empty then print [] without indent and line break
1737     * - if the array contains no object value, empty array or some other value types,
1738     * and all the values fit on one lines, then print the array on a single line.
1739     * - otherwise, it the values do not fit on one line, or the array contains
1740     * object or non empty array, then print one value per line.
1741     *
1742     * If the Value have comments then they are outputed according to their #CommentPlacement.
1743     *
1744     * \sa Reader, Value, Value::setComment()
1745     */
1746     class JSON_API StyledWriter: public Writer
1747     {
1748     public:
1749     StyledWriter();
1750     virtual ~StyledWriter(){}
1751    
1752     public: // overridden from Writer
1753     /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
1754     * \param root Value to serialize.
1755     * \return String containing the JSON document that represents the root value.
1756     */
1757     virtual std::string write( const Value &root );
1758    
1759     private:
1760     void writeValue( const Value &value );
1761     void writeArrayValue( const Value &value );
1762     bool isMultineArray( const Value &value );
1763     void pushValue( const std::string &value );
1764     void writeIndent();
1765     void writeWithIndent( const std::string &value );
1766     void indent();
1767     void unindent();
1768     void writeCommentBeforeValue( const Value &root );
1769     void writeCommentAfterValueOnSameLine( const Value &root );
1770     bool hasCommentForValue( const Value &value );
1771     static std::string normalizeEOL( const std::string &text );
1772    
1773     typedef std::vector<std::string> ChildValues;
1774    
1775     ChildValues childValues_;
1776     std::string document_;
1777     std::string indentString_;
1778     int rightMargin_;
1779     int indentSize_;
1780     bool addChildValues_;
1781     };
1782    
1783     /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a human friendly way,
1784     to a stream rather than to a string.
1785     *
1786     * The rules for line break and indent are as follow:
1787     * - Object value:
1788     * - if empty then print {} without indent and line break
1789     * - if not empty the print '{', line break & indent, print one value per line
1790     * and then unindent and line break and print '}'.
1791     * - Array value:
1792     * - if empty then print [] without indent and line break
1793     * - if the array contains no object value, empty array or some other value types,
1794     * and all the values fit on one lines, then print the array on a single line.
1795     * - otherwise, it the values do not fit on one line, or the array contains
1796     * object or non empty array, then print one value per line.
1797     *
1798     * If the Value have comments then they are outputed according to their #CommentPlacement.
1799     *
1800     * \param indentation Each level will be indented by this amount extra.
1801     * \sa Reader, Value, Value::setComment()
1802     */
1803     class JSON_API StyledStreamWriter
1804     {
1805     public:
1806     StyledStreamWriter( std::string indentation="\t" );
1807     ~StyledStreamWriter(){}
1808    
1809     public:
1810     /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
1811     * \param out Stream to write to. (Can be ostringstream, e.g.)
1812     * \param root Value to serialize.
1813     * \note There is no point in deriving from Writer, since write() should not return a value.
1814     */
1815     void write( std::ostream &out, const Value &root );
1816    
1817     private:
1818     void writeValue( const Value &value );
1819     void writeArrayValue( const Value &value );
1820     bool isMultineArray( const Value &value );
1821     void pushValue( const std::string &value );
1822     void writeIndent();
1823     void writeWithIndent( const std::string &value );
1824     void indent();
1825     void unindent();
1826     void writeCommentBeforeValue( const Value &root );
1827     void writeCommentAfterValueOnSameLine( const Value &root );
1828     bool hasCommentForValue( const Value &value );
1829     static std::string normalizeEOL( const std::string &text );
1830    
1831     typedef std::vector<std::string> ChildValues;
1832    
1833     ChildValues childValues_;
1834     std::ostream* document_;
1835     std::string indentString_;
1836     int rightMargin_;
1837     std::string indentation_;
1838     bool addChildValues_;
1839     };
1840    
1841     # if defined(JSON_HAS_INT64)
1842     std::string JSON_API valueToString( Int value );
1843     std::string JSON_API valueToString( UInt value );
1844     # endif // if defined(JSON_HAS_INT64)
1845     std::string JSON_API valueToString( LargestInt value );
1846     std::string JSON_API valueToString( LargestUInt value );
1847     std::string JSON_API valueToString( double value );
1848     std::string JSON_API valueToString( bool value );
1849     std::string JSON_API valueToQuotedString( const char *value );
1850    
1851     /// \brief Output using the StyledStreamWriter.
1852     /// \see Json::operator>>()
1853     std::ostream& operator<<( std::ostream&, const Value &root );
1854    
1855     } // namespace Json
1856    
1857    
1858    
1859     #endif // JSON_WRITER_H_INCLUDED
1860    
1861     // //////////////////////////////////////////////////////////////////////
1862     // End of content of file: include/json/writer.h
1863     // //////////////////////////////////////////////////////////////////////
1864    
1865    
1866    
1867    
1868    
1869    
1870     // //////////////////////////////////////////////////////////////////////
1871     // Beginning of content of file: include/json/assertions.h
1872     // //////////////////////////////////////////////////////////////////////
1873    
1874     // Copyright 2007-2010 Baptiste Lepilleur
1875     // Distributed under MIT license, or public domain if desired and
1876     // recognized in your jurisdiction.
1877     // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1878    
1879     #ifndef CPPTL_JSON_ASSERTIONS_H_INCLUDED
1880     # define CPPTL_JSON_ASSERTIONS_H_INCLUDED
1881    
1882     #include <stdlib.h>
1883    
1884     #if !defined(JSON_IS_AMALGAMATION)
1885     # include <json/config.h>
1886     #endif // if !defined(JSON_IS_AMALGAMATION)
1887    
1888     #if JSON_USE_EXCEPTION
1889     #define JSON_ASSERT( condition ) assert( condition ); // @todo <= change this into an exception throw
1890     #define JSON_FAIL_MESSAGE( message ) throw std::runtime_error( message );
1891     #else // JSON_USE_EXCEPTION
1892     #define JSON_ASSERT( condition ) assert( condition );
1893    
1894     // The call to assert() will show the failure message in debug builds. In
1895     // release bugs we write to invalid memory in order to crash hard, so that a
1896     // debugger or crash reporter gets the chance to take over. We still call exit()
1897     // afterward in order to tell the compiler that this macro doesn't return.
1898     #define JSON_FAIL_MESSAGE( message ) { assert(false && message); strcpy(reinterpret_cast<char*>(666), message); exit(123); }
1899    
1900     #endif
1901    
1902     #define JSON_ASSERT_MESSAGE( condition, message ) if (!( condition )) { JSON_FAIL_MESSAGE( message ) }
1903    
1904     #endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED
1905    
1906     // //////////////////////////////////////////////////////////////////////
1907     // End of content of file: include/json/assertions.h
1908     // //////////////////////////////////////////////////////////////////////
1909    
1910    
1911    
1912    
1913    
1914     #endif //ifndef JSON_AMALGATED_H_INCLUDED