blob: ce3d3cd0e98ae0655a7200944a4e8c04f8fd1204 [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 {
Baptiste Lepilleur4a5e58c2010-01-15 14:56:59 +0000640 IteratorState()
641 : map_(0)
642 , link_(0)
643 , itemIndex_(0)
644 , bucketIndex_(0)
645 {
646 }
Christopher Dunn6d135cb2007-06-13 15:51:04 +0000647 ValueInternalMap *map_;
648 ValueInternalLink *link_;
649 BucketIndex itemIndex_;
650 BucketIndex bucketIndex_;
651 };
652# endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
653
654 ValueInternalMap();
655 ValueInternalMap( const ValueInternalMap &other );
656 ValueInternalMap &operator =( const ValueInternalMap &other );
657 ~ValueInternalMap();
658
659 void swap( ValueInternalMap &other );
660
661 BucketIndex size() const;
662
663 void clear();
664
665 bool reserveDelta( BucketIndex growth );
666
667 bool reserve( BucketIndex newItemCount );
668
669 const Value *find( const char *key ) const;
670
671 Value *find( const char *key );
672
673 Value &resolveReference( const char *key,
674 bool isStatic );
675
676 void remove( const char *key );
677
678 void doActualRemove( ValueInternalLink *link,
679 BucketIndex index,
680 BucketIndex bucketIndex );
681
682 ValueInternalLink *&getLastLinkInBucket( BucketIndex bucketIndex );
683
684 Value &setNewItem( const char *key,
685 bool isStatic,
686 ValueInternalLink *link,
687 BucketIndex index );
688
689 Value &unsafeAdd( const char *key,
690 bool isStatic,
691 HashKey hashedKey );
692
693 HashKey hash( const char *key ) const;
694
695 int compare( const ValueInternalMap &other ) const;
696
697 private:
698 void makeBeginIterator( IteratorState &it ) const;
699 void makeEndIterator( IteratorState &it ) const;
700 static bool equals( const IteratorState &x, const IteratorState &other );
701 static void increment( IteratorState &iterator );
702 static void incrementBucket( IteratorState &iterator );
703 static void decrement( IteratorState &iterator );
704 static const char *key( const IteratorState &iterator );
705 static const char *key( const IteratorState &iterator, bool &isStatic );
706 static Value &value( const IteratorState &iterator );
707 static int distance( const IteratorState &x, const IteratorState &y );
708
709 private:
710 ValueInternalLink *buckets_;
711 ValueInternalLink *tailLink_;
712 BucketIndex bucketsSize_;
713 BucketIndex itemCount_;
714 };
715
716 /** \brief A simplified deque implementation used internally by Value.
717 * \internal
718 * It is based on a list of fixed "page", each page contains a fixed number of items.
719 * Instead of using a linked-list, a array of pointer is used for fast item look-up.
720 * Look-up for an element is as follow:
721 * - compute page index: pageIndex = itemIndex / itemsPerPage
722 * - look-up item in page: pages_[pageIndex][itemIndex % itemsPerPage]
723 *
724 * Insertion is amortized constant time (only the array containing the index of pointers
725 * need to be reallocated when items are appended).
726 */
727 class JSON_API ValueInternalArray
728 {
729 friend class Value;
730 friend class ValueIteratorBase;
731 public:
732 enum { itemsPerPage = 8 }; // should be a power of 2 for fast divide and modulo.
733 typedef Value::ArrayIndex ArrayIndex;
734 typedef unsigned int PageIndex;
735
736# ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
737 struct IteratorState // Must be a POD
738 {
Baptiste Lepilleur4a5e58c2010-01-15 14:56:59 +0000739 IteratorState()
740 : array_(0)
741 , currentPageIndex_(0)
742 , currentItemIndex_(0)
743 {
744 }
Christopher Dunn6d135cb2007-06-13 15:51:04 +0000745 ValueInternalArray *array_;
746 Value **currentPageIndex_;
747 unsigned int currentItemIndex_;
748 };
749# endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
750
751 ValueInternalArray();
752 ValueInternalArray( const ValueInternalArray &other );
753 ValueInternalArray &operator =( const ValueInternalArray &other );
754 ~ValueInternalArray();
755 void swap( ValueInternalArray &other );
756
757 void clear();
758 void resize( ArrayIndex newSize );
759
760 Value &resolveReference( ArrayIndex index );
761
762 Value *find( ArrayIndex index ) const;
763
764 ArrayIndex size() const;
765
766 int compare( const ValueInternalArray &other ) const;
767
768 private:
769 static bool equals( const IteratorState &x, const IteratorState &other );
770 static void increment( IteratorState &iterator );
771 static void decrement( IteratorState &iterator );
772 static Value &dereference( const IteratorState &iterator );
773 static Value &unsafeDereference( const IteratorState &iterator );
774 static int distance( const IteratorState &x, const IteratorState &y );
775 static ArrayIndex indexOf( const IteratorState &iterator );
776 void makeBeginIterator( IteratorState &it ) const;
777 void makeEndIterator( IteratorState &it ) const;
778 void makeIterator( IteratorState &it, ArrayIndex index ) const;
779
780 void makeIndexValid( ArrayIndex index );
781
782 Value **pages_;
783 ArrayIndex size_;
784 PageIndex pageCount_;
785 };
786
787 /** \brief Allocator to customize Value internal array.
788 * Below is an example of a simple implementation (actual implementation use
789 * memory pool).
790 \code
791class DefaultValueArrayAllocator : public ValueArrayAllocator
792{
793public: // overridden from ValueArrayAllocator
794 virtual ~DefaultValueArrayAllocator()
795 {
796 }
797
798 virtual ValueInternalArray *newArray()
799 {
800 return new ValueInternalArray();
801 }
802
803 virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other )
804 {
805 return new ValueInternalArray( other );
806 }
807
808 virtual void destruct( ValueInternalArray *array )
809 {
810 delete array;
811 }
812
813 virtual void reallocateArrayPageIndex( Value **&indexes,
814 ValueInternalArray::PageIndex &indexCount,
815 ValueInternalArray::PageIndex minNewIndexCount )
816 {
817 ValueInternalArray::PageIndex newIndexCount = (indexCount*3)/2 + 1;
818 if ( minNewIndexCount > newIndexCount )
819 newIndexCount = minNewIndexCount;
820 void *newIndexes = realloc( indexes, sizeof(Value*) * newIndexCount );
821 if ( !newIndexes )
822 throw std::bad_alloc();
823 indexCount = newIndexCount;
824 indexes = static_cast<Value **>( newIndexes );
825 }
826 virtual void releaseArrayPageIndex( Value **indexes,
827 ValueInternalArray::PageIndex indexCount )
828 {
829 if ( indexes )
830 free( indexes );
831 }
832
833 virtual Value *allocateArrayPage()
834 {
835 return static_cast<Value *>( malloc( sizeof(Value) * ValueInternalArray::itemsPerPage ) );
836 }
837
838 virtual void releaseArrayPage( Value *value )
839 {
840 if ( value )
841 free( value );
842 }
843};
844 \endcode
845 */
846 class JSON_API ValueArrayAllocator
847 {
848 public:
849 virtual ~ValueArrayAllocator();
850 virtual ValueInternalArray *newArray() = 0;
851 virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other ) = 0;
852 virtual void destructArray( ValueInternalArray *array ) = 0;
853 /** \brief Reallocate array page index.
854 * Reallocates an array of pointer on each page.
855 * \param indexes [input] pointer on the current index. May be \c NULL.
856 * [output] pointer on the new index of at least
857 * \a minNewIndexCount pages.
858 * \param indexCount [input] current number of pages in the index.
859 * [output] number of page the reallocated index can handle.
860 * \b MUST be >= \a minNewIndexCount.
861 * \param minNewIndexCount Minimum number of page the new index must be able to
862 * handle.
863 */
864 virtual void reallocateArrayPageIndex( Value **&indexes,
865 ValueInternalArray::PageIndex &indexCount,
866 ValueInternalArray::PageIndex minNewIndexCount ) = 0;
867 virtual void releaseArrayPageIndex( Value **indexes,
868 ValueInternalArray::PageIndex indexCount ) = 0;
869 virtual Value *allocateArrayPage() = 0;
870 virtual void releaseArrayPage( Value *value ) = 0;
871 };
872#endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP
873
874
875 /** \brief Experimental and untested: base class for Value iterators.
876 *
877 */
878 class ValueIteratorBase
879 {
880 public:
881 typedef unsigned int size_t;
882 typedef int difference_type;
883 typedef ValueIteratorBase SelfType;
884
885 ValueIteratorBase();
886#ifndef JSON_VALUE_USE_INTERNAL_MAP
887 explicit ValueIteratorBase( const Value::ObjectValues::iterator &current );
888#else
889 ValueIteratorBase( const ValueInternalArray::IteratorState &state );
890 ValueIteratorBase( const ValueInternalMap::IteratorState &state );
891#endif
892
893 bool operator ==( const SelfType &other ) const
894 {
895 return isEqual( other );
896 }
897
898 bool operator !=( const SelfType &other ) const
899 {
900 return !isEqual( other );
901 }
902
903 difference_type operator -( const SelfType &other ) const
904 {
905 return computeDistance( other );
906 }
907
908 /// Return either the index or the member name of the referenced value as a Value.
909 Value key() const;
910
911 /// Return the index of the referenced Value. -1 if it is not an arrayValue.
912 Value::UInt index() const;
913
914 /// Return the member name of the referenced Value. "" if it is not an objectValue.
915 const char *memberName() const;
916
917 protected:
918 Value &deref() const;
919
920 void increment();
921
922 void decrement();
923
924 difference_type computeDistance( const SelfType &other ) const;
925
926 bool isEqual( const SelfType &other ) const;
927
928 void copy( const SelfType &other );
929
930 private:
931#ifndef JSON_VALUE_USE_INTERNAL_MAP
932 Value::ObjectValues::iterator current_;
Baptiste Lepilleura1d6c9e2009-11-23 22:33:30 +0000933 // Indicates that iterator is for a null value.
934 bool isNull_;
Christopher Dunn6d135cb2007-06-13 15:51:04 +0000935#else
936 union
937 {
938 ValueInternalArray::IteratorState array_;
939 ValueInternalMap::IteratorState map_;
940 } iterator_;
941 bool isArray_;
942#endif
943 };
944
945 /** \brief Experimental and untested: const iterator for object and array value.
946 *
947 */
948 class ValueConstIterator : public ValueIteratorBase
949 {
950 friend class Value;
951 public:
952 typedef unsigned int size_t;
953 typedef int difference_type;
954 typedef const Value &reference;
955 typedef const Value *pointer;
956 typedef ValueConstIterator SelfType;
957
958 ValueConstIterator();
959 private:
960 /*! \internal Use by Value to create an iterator.
961 */
962#ifndef JSON_VALUE_USE_INTERNAL_MAP
963 explicit ValueConstIterator( const Value::ObjectValues::iterator &current );
964#else
965 ValueConstIterator( const ValueInternalArray::IteratorState &state );
966 ValueConstIterator( const ValueInternalMap::IteratorState &state );
967#endif
968 public:
969 SelfType &operator =( const ValueIteratorBase &other );
970
971 SelfType operator++( int )
972 {
973 SelfType temp( *this );
974 ++*this;
975 return temp;
976 }
977
978 SelfType operator--( int )
979 {
980 SelfType temp( *this );
981 --*this;
982 return temp;
983 }
984
985 SelfType &operator--()
986 {
987 decrement();
988 return *this;
989 }
990
991 SelfType &operator++()
992 {
993 increment();
994 return *this;
995 }
996
997 reference operator *() const
998 {
999 return deref();
1000 }
1001 };
1002
1003
1004 /** \brief Experimental and untested: iterator for object and array value.
1005 */
1006 class ValueIterator : public ValueIteratorBase
1007 {
1008 friend class Value;
1009 public:
1010 typedef unsigned int size_t;
1011 typedef int difference_type;
1012 typedef Value &reference;
1013 typedef Value *pointer;
1014 typedef ValueIterator SelfType;
1015
1016 ValueIterator();
1017 ValueIterator( const ValueConstIterator &other );
1018 ValueIterator( const ValueIterator &other );
1019 private:
1020 /*! \internal Use by Value to create an iterator.
1021 */
1022#ifndef JSON_VALUE_USE_INTERNAL_MAP
1023 explicit ValueIterator( const Value::ObjectValues::iterator &current );
1024#else
1025 ValueIterator( const ValueInternalArray::IteratorState &state );
1026 ValueIterator( const ValueInternalMap::IteratorState &state );
1027#endif
1028 public:
1029
1030 SelfType &operator =( const SelfType &other );
1031
1032 SelfType operator++( int )
1033 {
1034 SelfType temp( *this );
1035 ++*this;
1036 return temp;
1037 }
1038
1039 SelfType operator--( int )
1040 {
1041 SelfType temp( *this );
1042 --*this;
1043 return temp;
1044 }
1045
1046 SelfType &operator--()
1047 {
1048 decrement();
1049 return *this;
1050 }
1051
1052 SelfType &operator++()
1053 {
1054 increment();
1055 return *this;
1056 }
1057
1058 reference operator *() const
1059 {
1060 return deref();
1061 }
1062 };
1063
1064
1065} // namespace Json
1066
1067
1068#endif // CPPTL_JSON_H_INCLUDED