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