value.h 33 KB

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