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