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