value.h 32 KB

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