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