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