value.h 35 KB

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