value.h 33 KB

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