blob: 376b495c7a581c94ad524cf1aedca038233c537f [file] [log] [blame]
Baptiste Lepilleur4cd8bae2007-03-15 22:11:38 +00001#ifndef CPPTL_JSON_H_INCLUDED
2# define CPPTL_JSON_H_INCLUDED
3
4# include "forwards.h"
5# include <string>
6# include <vector>
7
8# ifndef JSON_USE_CPPTL_SMALLMAP
9# include <map>
10# else
11# include <cpptl/smallmap.h>
12# endif
13# ifdef JSON_USE_CPPTL
14# include <cpptl/forwards.h>
15# endif
16
17/** \brief JSON (JavaScript Object Notation).
18 */
19namespace Json {
20
21 /** \brief Type of the value held by a Value object.
22 */
23 enum ValueType
24 {
25 nullValue = 0, ///< 'null' value
26 intValue, ///< signed integer value
27 uintValue, ///< unsigned integer value
28 realValue, ///< double value
29 stringValue, ///< UTF-8 string value
30 booleanValue, ///< bool value
31 arrayValue, ///< array value (ordered list)
32 objectValue ///< object value (collection of name/value pairs).
33 };
34
35 enum CommentPlacement
36 {
37 commentBefore = 0, ///< a comment placed on the line before a value
38 commentAfterOnSameLine, ///< a comment just after a value on the same line
39 commentAfter, ///< a comment on the line after a value (only make sense for root value)
40 numberOfCommentPlacement
41 };
42
43//# ifdef JSON_USE_CPPTL
44// typedef CppTL::AnyEnumerator<const char *> EnumMemberNames;
45// typedef CppTL::AnyEnumerator<const Value &> EnumValues;
46//# endif
47
48 /** \brief Lightweight wrapper to tag static string.
49 *
50 * Value constructor and objectValue member assignement takes advantage of the
51 * StaticString and avoid the cost of string duplication when storing the
52 * string or the member name.
53 *
54 * Example of usage:
55 * \code
56 * Json::Value aValue( StaticString("some text") );
57 * Json::Value object;
58 * static const StaticString code("code");
59 * object[code] = 1234;
60 * \endcode
61 */
62 class JSON_API StaticString
63 {
64 public:
65 explicit StaticString( const char *czstring )
66 : str_( czstring )
67 {
68 }
69
70 operator const char *() const
71 {
72 return str_;
73 }
74
75 const char *c_str() const
76 {
77 return str_;
78 }
79
80 private:
81 const char *str_;
82 };
83
84 /** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
85 *
86 * This class is a discriminated union wrapper that can represents a:
87 * - signed integer [range: Value::minInt - Value::maxInt]
88 * - unsigned integer (range: 0 - Value::maxUInt)
89 * - double
90 * - UTF-8 string
91 * - boolean
92 * - 'null'
93 * - an ordered list of Value
94 * - collection of name/value pairs (javascript object)
95 *
96 * The type of the held value is represented by a #ValueType and
97 * can be obtained using type().
98 *
99 * values of an #objectValue or #arrayValue can be accessed using operator[]() methods.
100 * Non const methods will automatically create the a #nullValue element
101 * if it does not exist.
102 * The sequence of an #arrayValue will be automatically resize and initialized
103 * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
104 *
105 * The get() methods can be used to obtanis default value in the case the required element
106 * does not exist.
107 *
108 * It is possible to iterate over the list of a #objectValue values using
109 * the getMemberNames() method.
110 */
111 class JSON_API Value
112 {
113 friend class ValueIteratorBase;
114# ifdef JSON_VALUE_USE_INTERNAL_MAP
115 friend class ValueInternalLink;
116 friend class ValueInternalMap;
117# endif
118 public:
119 typedef std::vector<std::string> Members;
120 typedef int Int;
121 typedef unsigned int UInt;
122 typedef ValueIterator iterator;
123 typedef ValueConstIterator const_iterator;
124 typedef UInt ArrayIndex;
125
126 static const Value null;
127 static const Int minInt;
128 static const Int maxInt;
129 static const UInt maxUInt;
130
131 private:
132#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
133# ifndef JSON_VALUE_USE_INTERNAL_MAP
134 class CZString
135 {
136 public:
137 enum DuplicationPolicy
138 {
139 noDuplication = 0,
140 duplicate,
141 duplicateOnCopy
142 };
143 CZString( int index );
144 CZString( const char *cstr, DuplicationPolicy allocate );
145 CZString( const CZString &other );
146 ~CZString();
147 CZString &operator =( const CZString &other );
148 bool operator<( const CZString &other ) const;
149 bool operator==( const CZString &other ) const;
150 int index() const;
151 const char *c_str() const;
152 bool isStaticString() const;
153 private:
154 void swap( CZString &other );
155 const char *cstr_;
156 int index_;
157 };
158
159 public:
160# ifndef JSON_USE_CPPTL_SMALLMAP
161 typedef std::map<CZString, Value> ObjectValues;
162# else
163 typedef CppTL::SmallMap<CZString, Value> ObjectValues;
164# endif // ifndef JSON_USE_CPPTL_SMALLMAP
165# endif // ifndef JSON_VALUE_USE_INTERNAL_MAP
166#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
167
168 public:
Christopher Dunn8386d3e2007-03-23 06:38:29 +0000169 /** \brief Create a default Value of the given type.
Christopher Dunn02ff7162007-03-23 07:28:19 +0000170
Christopher Dunn8386d3e2007-03-23 06:38:29 +0000171 This is a very useful constructor.
172 To create an empty array, pass arrayValue.
173 To create an empty object, pass objectValue.
174 Another Value can then be set to this one by assignment.
175 This is useful since clear() and resize() will not alter types.
Christopher Dunn02ff7162007-03-23 07:28:19 +0000176
177 Examples:
178 \code
179 Json::Value null_value; // null
180 Json::Value arr_value(Json::arrayValue); // []
181 Json::Value obj_value(Json::objectValue); // {}
182 \endcode
Christopher Dunn8386d3e2007-03-23 06:38:29 +0000183 */
Baptiste Lepilleur4cd8bae2007-03-15 22:11:38 +0000184 Value( ValueType type = nullValue );
185 Value( Int value );
186 Value( UInt value );
187 Value( double value );
188 Value( const char *value );
189 /** \brief Constructs a value from a static string.
Christopher Dunn02ff7162007-03-23 07:28:19 +0000190
Baptiste Lepilleur4cd8bae2007-03-15 22:11:38 +0000191 * Like other value string constructor but do not duplicate the string for
192 * internal storage. The given string must remain alive after the call to this
193 * constructor.
194 * Example of usage:
195 * \code
196 * Json::Value aValue( StaticString("some text") );
197 * \endcode
198 */
199 Value( const StaticString &value );
200 Value( const std::string &value );
201# ifdef JSON_USE_CPPTL
202 Value( const CppTL::ConstString &value );
203# endif
204 Value( bool value );
205 Value( const Value &other );
206 ~Value();
207
208 Value &operator=( const Value &other );
Christopher Dunn02ff7162007-03-23 07:28:19 +0000209 /// Swap values.
210 /// \note Currently, comments are intentionally not swapped, for
211 /// both logic and efficiency.
Baptiste Lepilleur4cd8bae2007-03-15 22:11:38 +0000212 void swap( Value &other );
213
214 ValueType type() const;
215
216 bool operator <( const Value &other ) const;
217 bool operator <=( const Value &other ) const;
218 bool operator >=( const Value &other ) const;
219 bool operator >( const Value &other ) const;
220
221 bool operator ==( const Value &other ) const;
222 bool operator !=( const Value &other ) const;
223
224 int compare( const Value &other );
225
226 const char *asCString() const;
227 std::string asString() const;
228# ifdef JSON_USE_CPPTL
229 CppTL::ConstString asConstString() const;
230# endif
231 Int asInt() const;
232 UInt asUInt() const;
233 double asDouble() const;
234 bool asBool() const;
235
236 bool isBool() const;
237 bool isInt() const;
238 bool isUInt() const;
239 bool isIntegral() const;
240 bool isDouble() const;
241 bool isNumeric() const;
242 bool isString() const;
243 bool isArray() const;
244 bool isObject() const;
245
246 bool isConvertibleTo( ValueType other ) const;
247
248 /// Number of values in array or object
249 UInt size() const;
250
251 /// Removes all object members and array elements.
Christopher Dunn02ff7162007-03-23 07:28:19 +0000252 /// \pre type() is arrayValue, objectValue, or nullValue
253 /// \post type() is unchanged
Baptiste Lepilleur4cd8bae2007-03-15 22:11:38 +0000254 void clear();
255
256 /// Resize the array to size elements.
257 /// New elements are initialized to null.
258 /// May only be called on nullValue or arrayValue.
Christopher Dunn02ff7162007-03-23 07:28:19 +0000259 /// \pre type() is arrayValue or nullValue
260 /// \post type() is arrayValue
Baptiste Lepilleur4cd8bae2007-03-15 22:11:38 +0000261 void resize( UInt size );
262
263 /// Access an array element (zero based index ).
264 /// If the array contains less than index element, then null value are inserted
265 /// in the array so that its size is index+1.
266 Value &operator[]( UInt index );
267 /// Access an array element (zero based index )
268 const Value &operator[]( UInt index ) const;
269 /// If the array contains at least index+1 elements, returns the element value,
270 /// otherwise returns defaultValue.
271 Value get( UInt index,
272 const Value &defaultValue ) const;
273 /// Returns true if index < size().
274 bool isValidIndex( UInt index ) const;
275 /// Append value to array at the end.
276 /// Equivalent to jsonvalue[jsonvalue.size()] = value;
277 Value &append( const Value &value );
278
279 /// Access an object value by name, create a null member if it does not exist.
280 Value &operator[]( const char *key );
281 /// Access an object value by name, returns null if there is no member with that name.
282 const Value &operator[]( const char *key ) const;
283 /// Access an object value by name, create a null member if it does not exist.
284 Value &operator[]( const std::string &key );
285 /// Access an object value by name, returns null if there is no member with that name.
286 const Value &operator[]( const std::string &key ) const;
287 /** \brief Access an object value by name, create a null member if it does not exist.
Christopher Dunn02ff7162007-03-23 07:28:19 +0000288
Baptiste Lepilleur4cd8bae2007-03-15 22:11:38 +0000289 * If the object as no entry for that name, then the member name used to store
290 * the new entry is not duplicated.
291 * Example of use:
292 * \code
293 * Json::Value object;
294 * static const StaticString code("code");
295 * object[code] = 1234;
296 * \endcode
297 */
298 Value &operator[]( const StaticString &key );
299# ifdef JSON_USE_CPPTL
300 /// Access an object value by name, create a null member if it does not exist.
301 Value &operator[]( const CppTL::ConstString &key );
302 /// Access an object value by name, returns null if there is no member with that name.
303 const Value &operator[]( const CppTL::ConstString &key ) const;
304# endif
305 /// Returns the member named key if it exist, defaultValue otherwise.
306 Value get( const char *key,
307 const Value &defaultValue ) const;
308 /// Returns the member named key if it exist, defaultValue otherwise.
309 Value get( const std::string &key,
310 const Value &defaultValue ) const;
311# ifdef JSON_USE_CPPTL
312 /// Returns the member named key if it exist, defaultValue otherwise.
313 Value get( const CppTL::ConstString &key,
314 const Value &defaultValue ) const;
315# endif
316 /// Returns true if the object has a member named key.
317 bool isMember( const char *key ) const;
318 /// Returns true if the object has a member named key.
319 bool isMember( const std::string &key ) const;
320# ifdef JSON_USE_CPPTL
321 /// Returns true if the object has a member named key.
322 bool isMember( const CppTL::ConstString &key ) const;
323# endif
324
325 // Returns a list of the member names.
326 Members getMemberNames() const;
327
328//# ifdef JSON_USE_CPPTL
329// EnumMemberNames enumMemberNames() const;
330// EnumValues enumValues() const;
331//# endif
332
Christopher Dunnca212562007-03-23 07:05:19 +0000333 /// Comments must be //... or /* ... */
Baptiste Lepilleur4cd8bae2007-03-15 22:11:38 +0000334 void setComment( const char *comment,
335 CommentPlacement placement );
Christopher Dunnca212562007-03-23 07:05:19 +0000336 /// Comments must be //... or /* ... */
Baptiste Lepilleur4cd8bae2007-03-15 22:11:38 +0000337 void setComment( const std::string &comment,
338 CommentPlacement placement );
339 bool hasComment( CommentPlacement placement ) const;
340 std::string getComment( CommentPlacement placement ) const;
341
342 std::string toStyledString() const;
343
344 const_iterator begin() const;
345 const_iterator end() const;
346
347 iterator begin();
348 iterator end();
349
350 private:
351 Value &resolveReference( const char *key,
352 bool isStatic );
353
354# ifdef JSON_VALUE_USE_INTERNAL_MAP
355 inline bool isItemAvailable() const
356 {
357 return itemIsUsed_ == 0;
358 }
359
360 inline void setItemUsed( bool isUsed = true )
361 {
362 itemIsUsed_ = isUsed ? 1 : 0;
363 }
364
365 inline bool isMemberNameStatic() const
366 {
367 return memberNameIsStatic_ == 0;
368 }
369
370 inline void setMemberNameIsStatic( bool isStatic )
371 {
372 memberNameIsStatic_ = isStatic ? 1 : 0;
373 }
374# endif // # ifdef JSON_VALUE_USE_INTERNAL_MAP
375
376 private:
377 struct CommentInfo
378 {
379 CommentInfo();
380 ~CommentInfo();
381
382 void setComment( const char *text );
383
384 char *comment_;
385 };
386
387 //struct MemberNamesTransform
388 //{
389 // typedef const char *result_type;
390 // const char *operator()( const CZString &name ) const
391 // {
392 // return name.c_str();
393 // }
394 //};
395
396 union ValueHolder
397 {
398 Int int_;
399 UInt uint_;
400 double real_;
401 bool bool_;
402 char *string_;
403# ifdef JSON_VALUE_USE_INTERNAL_MAP
404 ValueInternalArray *array_;
405 ValueInternalMap *map_;
406#else
407 ObjectValues *map_;
408# endif
409 } value_;
410 ValueType type_ : 8;
411 int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
412# ifdef JSON_VALUE_USE_INTERNAL_MAP
413 unsigned int itemIsUsed_ : 1; // used by the ValueInternalMap container.
414 int memberNameIsStatic_ : 1; // used by the ValueInternalMap container.
415# endif
416 CommentInfo *comments_;
417 };
418
419
420 /** \brief Experimental and untested: represents an element of the "path" to access a node.
421 */
422 class PathArgument
423 {
424 public:
425 friend class Path;
426
427 PathArgument();
428 PathArgument( Value::UInt index );
429 PathArgument( const char *key );
430 PathArgument( const std::string &key );
431
432 private:
433 enum Kind
434 {
435 kindNone = 0,
436 kindIndex,
437 kindKey
438 };
439 std::string key_;
440 Value::UInt index_;
441 Kind kind_;
442 };
443
444 /** \brief Experimental and untested: represents a "path" to access a node.
445 *
446 * Syntax:
447 * - "." => root node
448 * - ".[n]" => elements at index 'n' of root node (an array value)
449 * - ".name" => member named 'name' of root node (an object value)
450 * - ".name1.name2.name3"
451 * - ".[0][1][2].name1[3]"
452 * - ".%" => member name is provided as parameter
453 * - ".[%]" => index is provied as parameter
454 */
455 class Path
456 {
457 public:
458 Path( const std::string &path,
459 const PathArgument &a1 = PathArgument(),
460 const PathArgument &a2 = PathArgument(),
461 const PathArgument &a3 = PathArgument(),
462 const PathArgument &a4 = PathArgument(),
463 const PathArgument &a5 = PathArgument() );
464
465 const Value &resolve( const Value &root ) const;
466 Value resolve( const Value &root,
467 const Value &defaultValue ) const;
468 /// Creates the "path" to access the specified node and returns a reference on the node.
469 Value &make( Value &root ) const;
470
471 private:
472 typedef std::vector<const PathArgument *> InArgs;
473 typedef std::vector<PathArgument> Args;
474
475 void makePath( const std::string &path,
476 const InArgs &in );
477 void addPathInArg( const std::string &path,
478 const InArgs &in,
479 InArgs::const_iterator &itInArg,
480 PathArgument::Kind kind );
481 void invalidPath( const std::string &path,
482 int location );
483
484 Args args_;
485 };
486
487 /** \brief Allocator to customize member name and string value memory management done by Value.
488 *
489 * - makeMemberName() and releaseMemberName() are called to respectively duplicate and
490 * free an Json::objectValue member name.
491 * - duplicateStringValue() and releaseStringValue() are called similarly to
492 * duplicate and free a Json::stringValue value.
493 */
494 class ValueAllocator
495 {
496 public:
497 enum { unknown = -1 };
498
499 virtual ~ValueAllocator();
500
501 virtual char *makeMemberName( const char *memberName ) = 0;
502 virtual void releaseMemberName( char *memberName ) = 0;
503 virtual char *duplicateStringValue( const char *value,
504 unsigned int length = unknown ) = 0;
505 virtual void releaseStringValue( char *value ) = 0;
506 };
507
508#ifdef JSON_VALUE_USE_INTERNAL_MAP
509 /** \brief Allocator to customize Value internal map.
510 * Below is an example of a simple implementation (default implementation actually
511 * use memory pool for speed).
512 * \code
513 class DefaultValueMapAllocator : public ValueMapAllocator
514 {
515 public: // overridden from ValueMapAllocator
516 virtual ValueInternalMap *newMap()
517 {
518 return new ValueInternalMap();
519 }
520
521 virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other )
522 {
523 return new ValueInternalMap( other );
524 }
525
526 virtual void destructMap( ValueInternalMap *map )
527 {
528 delete map;
529 }
530
531 virtual ValueInternalLink *allocateMapBuckets( unsigned int size )
532 {
533 return new ValueInternalLink[size];
534 }
535
536 virtual void releaseMapBuckets( ValueInternalLink *links )
537 {
538 delete [] links;
539 }
540
541 virtual ValueInternalLink *allocateMapLink()
542 {
543 return new ValueInternalLink();
544 }
545
546 virtual void releaseMapLink( ValueInternalLink *link )
547 {
548 delete link;
549 }
550 };
551 * \endcode
552 */
553 class JSON_API ValueMapAllocator
554 {
555 public:
556 virtual ~ValueMapAllocator();
557 virtual ValueInternalMap *newMap() = 0;
558 virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other ) = 0;
559 virtual void destructMap( ValueInternalMap *map ) = 0;
560 virtual ValueInternalLink *allocateMapBuckets( unsigned int size ) = 0;
561 virtual void releaseMapBuckets( ValueInternalLink *links ) = 0;
562 virtual ValueInternalLink *allocateMapLink() = 0;
563 virtual void releaseMapLink( ValueInternalLink *link ) = 0;
564 };
565
566 /** \brief ValueInternalMap hash-map bucket chain link (for internal use only).
567 * \internal previous_ & next_ allows for bidirectional traversal.
568 */
569 class JSON_API ValueInternalLink
570 {
571 public:
572 enum { itemPerLink = 6 }; // sizeof(ValueInternalLink) = 128 on 32 bits architecture.
573 enum InternalFlags {
574 flagAvailable = 0,
575 flagUsed = 1
576 };
577
578 ValueInternalLink();
579
580 ~ValueInternalLink();
581
582 Value items_[itemPerLink];
583 char *keys_[itemPerLink];
584 ValueInternalLink *previous_;
585 ValueInternalLink *next_;
586 };
587
588
589 /** \brief A linked page based hash-table implementation used internally by Value.
590 * \internal ValueInternalMap is a tradional bucket based hash-table, with a linked
591 * list in each bucket to handle collision. There is an addional twist in that
592 * each node of the collision linked list is a page containing a fixed amount of
593 * value. This provides a better compromise between memory usage and speed.
594 *
595 * Each bucket is made up of a chained list of ValueInternalLink. The last
596 * link of a given bucket can be found in the 'previous_' field of the following bucket.
597 * The last link of the last bucket is stored in tailLink_ as it has no following bucket.
598 * Only the last link of a bucket may contains 'available' item. The last link always
599 * contains at least one element unless is it the bucket one very first link.
600 */
601 class JSON_API ValueInternalMap
602 {
603 friend class ValueIteratorBase;
604 friend class Value;
605 public:
606 typedef unsigned int HashKey;
607 typedef unsigned int BucketIndex;
608
609# ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
610 struct IteratorState
611 {
612 ValueInternalMap *map_;
613 ValueInternalLink *link_;
614 BucketIndex itemIndex_;
615 BucketIndex bucketIndex_;
616 };
617# endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
618
619 ValueInternalMap();
620 ValueInternalMap( const ValueInternalMap &other );
621 ValueInternalMap &operator =( const ValueInternalMap &other );
622 ~ValueInternalMap();
623
624 void swap( ValueInternalMap &other );
625
626 BucketIndex size() const;
627
628 void clear();
629
630 bool reserveDelta( BucketIndex growth );
631
632 bool reserve( BucketIndex newItemCount );
633
634 const Value *find( const char *key ) const;
635
636 Value *find( const char *key );
637
638 Value &resolveReference( const char *key,
639 bool isStatic );
640
641 void remove( const char *key );
642
643 void doActualRemove( ValueInternalLink *link,
644 BucketIndex index,
645 BucketIndex bucketIndex );
646
647 ValueInternalLink *&getLastLinkInBucket( BucketIndex bucketIndex );
648
649 Value &setNewItem( const char *key,
650 bool isStatic,
651 ValueInternalLink *link,
652 BucketIndex index );
653
654 Value &unsafeAdd( const char *key,
655 bool isStatic,
656 HashKey hashedKey );
657
658 HashKey hash( const char *key ) const;
659
660 int compare( const ValueInternalMap &other ) const;
661
662 private:
663 void makeBeginIterator( IteratorState &it ) const;
664 void makeEndIterator( IteratorState &it ) const;
665 static bool equals( const IteratorState &x, const IteratorState &other );
666 static void increment( IteratorState &iterator );
667 static void incrementBucket( IteratorState &iterator );
668 static void decrement( IteratorState &iterator );
669 static const char *key( const IteratorState &iterator );
670 static const char *key( const IteratorState &iterator, bool &isStatic );
671 static Value &value( const IteratorState &iterator );
672 static int distance( const IteratorState &x, const IteratorState &y );
673
674 private:
675 ValueInternalLink *buckets_;
676 ValueInternalLink *tailLink_;
677 BucketIndex bucketsSize_;
678 BucketIndex itemCount_;
679 };
680
681 /** \brief A simplified deque implementation used internally by Value.
682 * \internal
683 * It is based on a list of fixed "page", each page contains a fixed number of items.
684 * Instead of using a linked-list, a array of pointer is used for fast item look-up.
685 * Look-up for an element is as follow:
686 * - compute page index: pageIndex = itemIndex / itemsPerPage
687 * - look-up item in page: pages_[pageIndex][itemIndex % itemsPerPage]
688 *
689 * Insertion is amortized constant time (only the array containing the index of pointers
690 * need to be reallocated when items are appended).
691 */
692 class JSON_API ValueInternalArray
693 {
694 friend class Value;
695 friend class ValueIteratorBase;
696 public:
697 enum { itemsPerPage = 8 }; // should be a power of 2 for fast divide and modulo.
698 typedef Value::ArrayIndex ArrayIndex;
699 typedef unsigned int PageIndex;
700
701# ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
702 struct IteratorState // Must be a POD
703 {
704 ValueInternalArray *array_;
705 Value **currentPageIndex_;
706 unsigned int currentItemIndex_;
707 };
708# endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
709
710 ValueInternalArray();
711 ValueInternalArray( const ValueInternalArray &other );
712 ValueInternalArray &operator =( const ValueInternalArray &other );
713 ~ValueInternalArray();
714 void swap( ValueInternalArray &other );
715
716 void clear();
717 void resize( ArrayIndex newSize );
718
719 Value &resolveReference( ArrayIndex index );
720
721 Value *find( ArrayIndex index ) const;
722
723 ArrayIndex size() const;
724
725 int compare( const ValueInternalArray &other ) const;
726
727 private:
728 static bool equals( const IteratorState &x, const IteratorState &other );
729 static void increment( IteratorState &iterator );
730 static void decrement( IteratorState &iterator );
731 static Value &dereference( const IteratorState &iterator );
732 static Value &unsafeDereference( const IteratorState &iterator );
733 static int distance( const IteratorState &x, const IteratorState &y );
734 static ArrayIndex indexOf( const IteratorState &iterator );
735 void makeBeginIterator( IteratorState &it ) const;
736 void makeEndIterator( IteratorState &it ) const;
737 void makeIterator( IteratorState &it, ArrayIndex index ) const;
738
739 void makeIndexValid( ArrayIndex index );
740
741 Value **pages_;
742 ArrayIndex size_;
743 PageIndex pageCount_;
744 };
745
746 /** \brief Allocator to customize Value internal array.
747 * Below is an example of a simple implementation (actual implementation use
748 * memory pool).
749 \code
750class DefaultValueArrayAllocator : public ValueArrayAllocator
751{
752public: // overridden from ValueArrayAllocator
753 virtual ~DefaultValueArrayAllocator()
754 {
755 }
756
757 virtual ValueInternalArray *newArray()
758 {
759 return new ValueInternalArray();
760 }
761
762 virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other )
763 {
764 return new ValueInternalArray( other );
765 }
766
767 virtual void destruct( ValueInternalArray *array )
768 {
769 delete array;
770 }
771
772 virtual void reallocateArrayPageIndex( Value **&indexes,
773 ValueInternalArray::PageIndex &indexCount,
774 ValueInternalArray::PageIndex minNewIndexCount )
775 {
776 ValueInternalArray::PageIndex newIndexCount = (indexCount*3)/2 + 1;
777 if ( minNewIndexCount > newIndexCount )
778 newIndexCount = minNewIndexCount;
779 void *newIndexes = realloc( indexes, sizeof(Value*) * newIndexCount );
780 if ( !newIndexes )
781 throw std::bad_alloc();
782 indexCount = newIndexCount;
783 indexes = static_cast<Value **>( newIndexes );
784 }
785 virtual void releaseArrayPageIndex( Value **indexes,
786 ValueInternalArray::PageIndex indexCount )
787 {
788 if ( indexes )
789 free( indexes );
790 }
791
792 virtual Value *allocateArrayPage()
793 {
794 return static_cast<Value *>( malloc( sizeof(Value) * ValueInternalArray::itemsPerPage ) );
795 }
796
797 virtual void releaseArrayPage( Value *value )
798 {
799 if ( value )
800 free( value );
801 }
802};
803 \endcode
804 */
805 class JSON_API ValueArrayAllocator
806 {
807 public:
808 virtual ~ValueArrayAllocator();
809 virtual ValueInternalArray *newArray() = 0;
810 virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other ) = 0;
811 virtual void destructArray( ValueInternalArray *array ) = 0;
812 /** \brief Reallocate array page index.
813 * Reallocates an array of pointer on each page.
814 * \param indexes [input] pointer on the current index. May be \c NULL.
815 * [output] pointer on the new index of at least
816 * \a minNewIndexCount pages.
817 * \param indexCount [input] current number of pages in the index.
818 * [output] number of page the reallocated index can handle.
819 * \b MUST be >= \a minNewIndexCount.
820 * \param minNewIndexCount Minimum number of page the new index must be able to
821 * handle.
822 */
823 virtual void reallocateArrayPageIndex( Value **&indexes,
824 ValueInternalArray::PageIndex &indexCount,
825 ValueInternalArray::PageIndex minNewIndexCount ) = 0;
826 virtual void releaseArrayPageIndex( Value **indexes,
827 ValueInternalArray::PageIndex indexCount ) = 0;
828 virtual Value *allocateArrayPage() = 0;
829 virtual void releaseArrayPage( Value *value ) = 0;
830 };
831#endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP
832
833
834 /** \brief Experimental and untested: base class for Value iterators.
835 *
836 */
837 class ValueIteratorBase
838 {
839 public:
840 typedef unsigned int size_t;
841 typedef int difference_type;
842 typedef ValueIteratorBase SelfType;
843
844 ValueIteratorBase();
845#ifndef JSON_VALUE_USE_INTERNAL_MAP
846 explicit ValueIteratorBase( const Value::ObjectValues::iterator &current );
847#else
848 ValueIteratorBase( const ValueInternalArray::IteratorState &state );
849 ValueIteratorBase( const ValueInternalMap::IteratorState &state );
850#endif
851
852 bool operator ==( const SelfType &other ) const
853 {
854 return isEqual( other );
855 }
856
857 bool operator !=( const SelfType &other ) const
858 {
859 return !isEqual( other );
860 }
861
862 difference_type operator -( const SelfType &other ) const
863 {
864 return computeDistance( other );
865 }
866
867 /// Returns either the index or the member name of the referenced value as a Value.
868 Value key() const;
869
870 /// Returns the index of the referenced Value. -1 if it is not an arrayValue.
871 Value::UInt index() const;
872
873 /// Returns the member name of the referenced Value. "" if it is not an objectValue.
874 const char *memberName() const;
875
876 protected:
877 Value &deref() const;
878
879 void increment();
880
881 void decrement();
882
883 difference_type computeDistance( const SelfType &other ) const;
884
885 bool isEqual( const SelfType &other ) const;
886
887 void copy( const SelfType &other );
888
889 private:
890#ifndef JSON_VALUE_USE_INTERNAL_MAP
891 Value::ObjectValues::iterator current_;
892#else
893 union
894 {
895 ValueInternalArray::IteratorState array_;
896 ValueInternalMap::IteratorState map_;
897 } iterator_;
898 bool isArray_;
899#endif
900 };
901
902 /** \brief Experimental and untested: const iterator for object and array value.
903 *
904 */
905 class ValueConstIterator : public ValueIteratorBase
906 {
907 friend class Value;
908 public:
909 typedef unsigned int size_t;
910 typedef int difference_type;
911 typedef const Value &reference;
912 typedef const Value *pointer;
913 typedef ValueConstIterator SelfType;
914
915 ValueConstIterator();
916 private:
917 /*! \internal Use by Value to create an iterator.
918 */
919#ifndef JSON_VALUE_USE_INTERNAL_MAP
920 explicit ValueConstIterator( const Value::ObjectValues::iterator &current );
921#else
922 ValueConstIterator( const ValueInternalArray::IteratorState &state );
923 ValueConstIterator( const ValueInternalMap::IteratorState &state );
924#endif
925 public:
926 SelfType &operator =( const ValueIteratorBase &other );
927
928 SelfType operator++( int )
929 {
930 SelfType temp( *this );
931 ++*this;
932 return temp;
933 }
934
935 SelfType operator--( int )
936 {
937 SelfType temp( *this );
938 --*this;
939 return temp;
940 }
941
942 SelfType &operator--()
943 {
944 decrement();
945 return *this;
946 }
947
948 SelfType &operator++()
949 {
950 increment();
951 return *this;
952 }
953
954 reference operator *() const
955 {
956 return deref();
957 }
958 };
959
960
961 /** \brief Experimental and untested: iterator for object and array value.
962 */
963 class ValueIterator : public ValueIteratorBase
964 {
965 friend class Value;
966 public:
967 typedef unsigned int size_t;
968 typedef int difference_type;
969 typedef Value &reference;
970 typedef Value *pointer;
971 typedef ValueIterator SelfType;
972
973 ValueIterator();
974 ValueIterator( const ValueConstIterator &other );
975 ValueIterator( const ValueIterator &other );
976 private:
977 /*! \internal Use by Value to create an iterator.
978 */
979#ifndef JSON_VALUE_USE_INTERNAL_MAP
980 explicit ValueIterator( const Value::ObjectValues::iterator &current );
981#else
982 ValueIterator( const ValueInternalArray::IteratorState &state );
983 ValueIterator( const ValueInternalMap::IteratorState &state );
984#endif
985 public:
986
987 SelfType &operator =( const SelfType &other );
988
989 SelfType operator++( int )
990 {
991 SelfType temp( *this );
992 ++*this;
993 return temp;
994 }
995
996 SelfType operator--( int )
997 {
998 SelfType temp( *this );
999 --*this;
1000 return temp;
1001 }
1002
1003 SelfType &operator--()
1004 {
1005 decrement();
1006 return *this;
1007 }
1008
1009 SelfType &operator++()
1010 {
1011 increment();
1012 return *this;
1013 }
1014
1015 reference operator *() const
1016 {
1017 return deref();
1018 }
1019 };
1020
1021
1022} // namespace Json
1023
1024
1025#endif // CPPTL_JSON_H_INCLUDED