value.h 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  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. Value& resolveReference(const char* key, bool isStatic);
  392. #ifdef JSON_VALUE_USE_INTERNAL_MAP
  393. inline bool isItemAvailable() const { return itemIsUsed_ == 0; }
  394. inline void setItemUsed(bool isUsed = true) { itemIsUsed_ = isUsed ? 1 : 0; }
  395. inline bool isMemberNameStatic() const { return memberNameIsStatic_ == 0; }
  396. inline void setMemberNameIsStatic(bool isStatic) {
  397. memberNameIsStatic_ = isStatic ? 1 : 0;
  398. }
  399. #endif // # ifdef JSON_VALUE_USE_INTERNAL_MAP
  400. private:
  401. struct CommentInfo {
  402. CommentInfo();
  403. ~CommentInfo();
  404. void setComment(const char* text);
  405. char* comment_;
  406. };
  407. // struct MemberNamesTransform
  408. //{
  409. // typedef const char *result_type;
  410. // const char *operator()( const CZString &name ) const
  411. // {
  412. // return name.c_str();
  413. // }
  414. //};
  415. union ValueHolder {
  416. LargestInt int_;
  417. LargestUInt uint_;
  418. double real_;
  419. bool bool_;
  420. char* string_;
  421. #ifdef JSON_VALUE_USE_INTERNAL_MAP
  422. ValueInternalArray* array_;
  423. ValueInternalMap* map_;
  424. #else
  425. ObjectValues* map_;
  426. #endif
  427. } value_;
  428. ValueType type_ : 8;
  429. int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
  430. #ifdef JSON_VALUE_USE_INTERNAL_MAP
  431. unsigned int itemIsUsed_ : 1; // used by the ValueInternalMap container.
  432. int memberNameIsStatic_ : 1; // used by the ValueInternalMap container.
  433. #endif
  434. CommentInfo* comments_;
  435. // [start, limit) byte offsets in the source JSON text from which this Value
  436. // was extracted.
  437. size_t start_;
  438. size_t limit_;
  439. };
  440. /** \brief Experimental and untested: represents an element of the "path" to
  441. * access a node.
  442. */
  443. class JSON_API PathArgument {
  444. public:
  445. friend class Path;
  446. PathArgument();
  447. PathArgument(ArrayIndex index);
  448. PathArgument(const char* key);
  449. PathArgument(const std::string& key);
  450. private:
  451. enum Kind {
  452. kindNone = 0,
  453. kindIndex,
  454. kindKey
  455. };
  456. std::string key_;
  457. ArrayIndex index_;
  458. Kind kind_;
  459. };
  460. /** \brief Experimental and untested: represents a "path" to access a node.
  461. *
  462. * Syntax:
  463. * - "." => root node
  464. * - ".[n]" => elements at index 'n' of root node (an array value)
  465. * - ".name" => member named 'name' of root node (an object value)
  466. * - ".name1.name2.name3"
  467. * - ".[0][1][2].name1[3]"
  468. * - ".%" => member name is provided as parameter
  469. * - ".[%]" => index is provied as parameter
  470. */
  471. class JSON_API Path {
  472. public:
  473. Path(const std::string& path,
  474. const PathArgument& a1 = PathArgument(),
  475. const PathArgument& a2 = PathArgument(),
  476. const PathArgument& a3 = PathArgument(),
  477. const PathArgument& a4 = PathArgument(),
  478. const PathArgument& a5 = PathArgument());
  479. const Value& resolve(const Value& root) const;
  480. Value resolve(const Value& root, const Value& defaultValue) const;
  481. /// Creates the "path" to access the specified node and returns a reference on
  482. /// the node.
  483. Value& make(Value& root) const;
  484. private:
  485. typedef std::vector<const PathArgument*> InArgs;
  486. typedef std::vector<PathArgument> Args;
  487. void makePath(const std::string& path, const InArgs& in);
  488. void addPathInArg(const std::string& path,
  489. const InArgs& in,
  490. InArgs::const_iterator& itInArg,
  491. PathArgument::Kind kind);
  492. void invalidPath(const std::string& path, int location);
  493. Args args_;
  494. };
  495. #ifdef JSON_VALUE_USE_INTERNAL_MAP
  496. /** \brief Allocator to customize Value internal map.
  497. * Below is an example of a simple implementation (default implementation
  498. actually
  499. * use memory pool for speed).
  500. * \code
  501. class DefaultValueMapAllocator : public ValueMapAllocator
  502. {
  503. public: // overridden from ValueMapAllocator
  504. virtual ValueInternalMap *newMap()
  505. {
  506. return new ValueInternalMap();
  507. }
  508. virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other )
  509. {
  510. return new ValueInternalMap( other );
  511. }
  512. virtual void destructMap( ValueInternalMap *map )
  513. {
  514. delete map;
  515. }
  516. virtual ValueInternalLink *allocateMapBuckets( unsigned int size )
  517. {
  518. return new ValueInternalLink[size];
  519. }
  520. virtual void releaseMapBuckets( ValueInternalLink *links )
  521. {
  522. delete [] links;
  523. }
  524. virtual ValueInternalLink *allocateMapLink()
  525. {
  526. return new ValueInternalLink();
  527. }
  528. virtual void releaseMapLink( ValueInternalLink *link )
  529. {
  530. delete link;
  531. }
  532. };
  533. * \endcode
  534. */
  535. class JSON_API ValueMapAllocator {
  536. public:
  537. virtual ~ValueMapAllocator();
  538. virtual ValueInternalMap* newMap() = 0;
  539. virtual ValueInternalMap* newMapCopy(const ValueInternalMap& other) = 0;
  540. virtual void destructMap(ValueInternalMap* map) = 0;
  541. virtual ValueInternalLink* allocateMapBuckets(unsigned int size) = 0;
  542. virtual void releaseMapBuckets(ValueInternalLink* links) = 0;
  543. virtual ValueInternalLink* allocateMapLink() = 0;
  544. virtual void releaseMapLink(ValueInternalLink* link) = 0;
  545. };
  546. /** \brief ValueInternalMap hash-map bucket chain link (for internal use only).
  547. * \internal previous_ & next_ allows for bidirectional traversal.
  548. */
  549. class JSON_API ValueInternalLink {
  550. public:
  551. enum {
  552. itemPerLink = 6
  553. }; // sizeof(ValueInternalLink) = 128 on 32 bits architecture.
  554. enum InternalFlags {
  555. flagAvailable = 0,
  556. flagUsed = 1
  557. };
  558. ValueInternalLink();
  559. ~ValueInternalLink();
  560. Value items_[itemPerLink];
  561. char* keys_[itemPerLink];
  562. ValueInternalLink* previous_;
  563. ValueInternalLink* next_;
  564. };
  565. /** \brief A linked page based hash-table implementation used internally by
  566. *Value.
  567. * \internal ValueInternalMap is a tradional bucket based hash-table, with a
  568. *linked
  569. * list in each bucket to handle collision. There is an addional twist in that
  570. * each node of the collision linked list is a page containing a fixed amount of
  571. * value. This provides a better compromise between memory usage and speed.
  572. *
  573. * Each bucket is made up of a chained list of ValueInternalLink. The last
  574. * link of a given bucket can be found in the 'previous_' field of the following
  575. *bucket.
  576. * The last link of the last bucket is stored in tailLink_ as it has no
  577. *following bucket.
  578. * Only the last link of a bucket may contains 'available' item. The last link
  579. *always
  580. * contains at least one element unless is it the bucket one very first link.
  581. */
  582. class JSON_API ValueInternalMap {
  583. friend class ValueIteratorBase;
  584. friend class Value;
  585. public:
  586. typedef unsigned int HashKey;
  587. typedef unsigned int BucketIndex;
  588. #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
  589. struct IteratorState {
  590. IteratorState() : map_(0), link_(0), itemIndex_(0), bucketIndex_(0) {}
  591. ValueInternalMap* map_;
  592. ValueInternalLink* link_;
  593. BucketIndex itemIndex_;
  594. BucketIndex bucketIndex_;
  595. };
  596. #endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
  597. ValueInternalMap();
  598. ValueInternalMap(const ValueInternalMap& other);
  599. ValueInternalMap& operator=(ValueInternalMap other);
  600. ~ValueInternalMap();
  601. void swap(ValueInternalMap& other);
  602. BucketIndex size() const;
  603. void clear();
  604. bool reserveDelta(BucketIndex growth);
  605. bool reserve(BucketIndex newItemCount);
  606. const Value* find(const char* key) const;
  607. Value* find(const char* key);
  608. Value& resolveReference(const char* key, bool isStatic);
  609. void remove(const char* key);
  610. void doActualRemove(ValueInternalLink* link,
  611. BucketIndex index,
  612. BucketIndex bucketIndex);
  613. ValueInternalLink*& getLastLinkInBucket(BucketIndex bucketIndex);
  614. Value& setNewItem(const char* key,
  615. bool isStatic,
  616. ValueInternalLink* link,
  617. BucketIndex index);
  618. Value& unsafeAdd(const char* key, bool isStatic, HashKey hashedKey);
  619. HashKey hash(const char* key) const;
  620. int compare(const ValueInternalMap& other) const;
  621. private:
  622. void makeBeginIterator(IteratorState& it) const;
  623. void makeEndIterator(IteratorState& it) const;
  624. static bool equals(const IteratorState& x, const IteratorState& other);
  625. static void increment(IteratorState& iterator);
  626. static void incrementBucket(IteratorState& iterator);
  627. static void decrement(IteratorState& iterator);
  628. static const char* key(const IteratorState& iterator);
  629. static const char* key(const IteratorState& iterator, bool& isStatic);
  630. static Value& value(const IteratorState& iterator);
  631. static int distance(const IteratorState& x, const IteratorState& y);
  632. private:
  633. ValueInternalLink* buckets_;
  634. ValueInternalLink* tailLink_;
  635. BucketIndex bucketsSize_;
  636. BucketIndex itemCount_;
  637. };
  638. /** \brief A simplified deque implementation used internally by Value.
  639. * \internal
  640. * It is based on a list of fixed "page", each page contains a fixed number of
  641. *items.
  642. * Instead of using a linked-list, a array of pointer is used for fast item
  643. *look-up.
  644. * Look-up for an element is as follow:
  645. * - compute page index: pageIndex = itemIndex / itemsPerPage
  646. * - look-up item in page: pages_[pageIndex][itemIndex % itemsPerPage]
  647. *
  648. * Insertion is amortized constant time (only the array containing the index of
  649. *pointers
  650. * need to be reallocated when items are appended).
  651. */
  652. class JSON_API ValueInternalArray {
  653. friend class Value;
  654. friend class ValueIteratorBase;
  655. public:
  656. enum {
  657. itemsPerPage = 8
  658. }; // should be a power of 2 for fast divide and modulo.
  659. typedef Value::ArrayIndex ArrayIndex;
  660. typedef unsigned int PageIndex;
  661. #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
  662. struct IteratorState // Must be a POD
  663. {
  664. IteratorState() : array_(0), currentPageIndex_(0), currentItemIndex_(0) {}
  665. ValueInternalArray* array_;
  666. Value** currentPageIndex_;
  667. unsigned int currentItemIndex_;
  668. };
  669. #endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
  670. ValueInternalArray();
  671. ValueInternalArray(const ValueInternalArray& other);
  672. ValueInternalArray& operator=(ValueInternalArray other);
  673. ~ValueInternalArray();
  674. void swap(ValueInternalArray& other);
  675. void clear();
  676. void resize(ArrayIndex newSize);
  677. Value& resolveReference(ArrayIndex index);
  678. Value* find(ArrayIndex index) const;
  679. ArrayIndex size() const;
  680. int compare(const ValueInternalArray& other) const;
  681. private:
  682. static bool equals(const IteratorState& x, const IteratorState& other);
  683. static void increment(IteratorState& iterator);
  684. static void decrement(IteratorState& iterator);
  685. static Value& dereference(const IteratorState& iterator);
  686. static Value& unsafeDereference(const IteratorState& iterator);
  687. static int distance(const IteratorState& x, const IteratorState& y);
  688. static ArrayIndex indexOf(const IteratorState& iterator);
  689. void makeBeginIterator(IteratorState& it) const;
  690. void makeEndIterator(IteratorState& it) const;
  691. void makeIterator(IteratorState& it, ArrayIndex index) const;
  692. void makeIndexValid(ArrayIndex index);
  693. Value** pages_;
  694. ArrayIndex size_;
  695. PageIndex pageCount_;
  696. };
  697. /** \brief Experimental: do not use. Allocator to customize Value internal
  698. array.
  699. * Below is an example of a simple implementation (actual implementation use
  700. * memory pool).
  701. \code
  702. class DefaultValueArrayAllocator : public ValueArrayAllocator
  703. {
  704. public: // overridden from ValueArrayAllocator
  705. virtual ~DefaultValueArrayAllocator()
  706. {
  707. }
  708. virtual ValueInternalArray *newArray()
  709. {
  710. return new ValueInternalArray();
  711. }
  712. virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other )
  713. {
  714. return new ValueInternalArray( other );
  715. }
  716. virtual void destruct( ValueInternalArray *array )
  717. {
  718. delete array;
  719. }
  720. virtual void reallocateArrayPageIndex( Value **&indexes,
  721. ValueInternalArray::PageIndex
  722. &indexCount,
  723. ValueInternalArray::PageIndex
  724. minNewIndexCount )
  725. {
  726. ValueInternalArray::PageIndex newIndexCount = (indexCount*3)/2 + 1;
  727. if ( minNewIndexCount > newIndexCount )
  728. newIndexCount = minNewIndexCount;
  729. void *newIndexes = realloc( indexes, sizeof(Value*) * newIndexCount );
  730. if ( !newIndexes )
  731. throw std::bad_alloc();
  732. indexCount = newIndexCount;
  733. indexes = static_cast<Value **>( newIndexes );
  734. }
  735. virtual void releaseArrayPageIndex( Value **indexes,
  736. ValueInternalArray::PageIndex indexCount )
  737. {
  738. if ( indexes )
  739. free( indexes );
  740. }
  741. virtual Value *allocateArrayPage()
  742. {
  743. return static_cast<Value *>( malloc( sizeof(Value) *
  744. ValueInternalArray::itemsPerPage ) );
  745. }
  746. virtual void releaseArrayPage( Value *value )
  747. {
  748. if ( value )
  749. free( value );
  750. }
  751. };
  752. \endcode
  753. */
  754. class JSON_API ValueArrayAllocator {
  755. public:
  756. virtual ~ValueArrayAllocator();
  757. virtual ValueInternalArray* newArray() = 0;
  758. virtual ValueInternalArray* newArrayCopy(const ValueInternalArray& other) = 0;
  759. virtual void destructArray(ValueInternalArray* array) = 0;
  760. /** \brief Reallocate array page index.
  761. * Reallocates an array of pointer on each page.
  762. * \param indexes [input] pointer on the current index. May be \c NULL.
  763. * [output] pointer on the new index of at least
  764. * \a minNewIndexCount pages.
  765. * \param indexCount [input] current number of pages in the index.
  766. * [output] number of page the reallocated index can handle.
  767. * \b MUST be >= \a minNewIndexCount.
  768. * \param minNewIndexCount Minimum number of page the new index must be able
  769. * to
  770. * handle.
  771. */
  772. virtual void
  773. reallocateArrayPageIndex(Value**& indexes,
  774. ValueInternalArray::PageIndex& indexCount,
  775. ValueInternalArray::PageIndex minNewIndexCount) = 0;
  776. virtual void
  777. releaseArrayPageIndex(Value** indexes,
  778. ValueInternalArray::PageIndex indexCount) = 0;
  779. virtual Value* allocateArrayPage() = 0;
  780. virtual void releaseArrayPage(Value* value) = 0;
  781. };
  782. #endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP
  783. /** \brief base class for Value iterators.
  784. *
  785. */
  786. class JSON_API ValueIteratorBase {
  787. public:
  788. typedef std::bidirectional_iterator_tag iterator_category;
  789. typedef unsigned int size_t;
  790. typedef int difference_type;
  791. typedef ValueIteratorBase SelfType;
  792. ValueIteratorBase();
  793. #ifndef JSON_VALUE_USE_INTERNAL_MAP
  794. explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
  795. #else
  796. ValueIteratorBase(const ValueInternalArray::IteratorState& state);
  797. ValueIteratorBase(const ValueInternalMap::IteratorState& state);
  798. #endif
  799. bool operator==(const SelfType& other) const { return isEqual(other); }
  800. bool operator!=(const SelfType& other) const { return !isEqual(other); }
  801. difference_type operator-(const SelfType& other) const {
  802. return computeDistance(other);
  803. }
  804. /// Return either the index or the member name of the referenced value as a
  805. /// Value.
  806. Value key() const;
  807. /// Return the index of the referenced Value. -1 if it is not an arrayValue.
  808. UInt index() const;
  809. /// Return the member name of the referenced Value. "" if it is not an
  810. /// objectValue.
  811. const char* memberName() const;
  812. protected:
  813. Value& deref() const;
  814. void increment();
  815. void decrement();
  816. difference_type computeDistance(const SelfType& other) const;
  817. bool isEqual(const SelfType& other) const;
  818. void copy(const SelfType& other);
  819. private:
  820. #ifndef JSON_VALUE_USE_INTERNAL_MAP
  821. Value::ObjectValues::iterator current_;
  822. // Indicates that iterator is for a null value.
  823. bool isNull_;
  824. #else
  825. union {
  826. ValueInternalArray::IteratorState array_;
  827. ValueInternalMap::IteratorState map_;
  828. } iterator_;
  829. bool isArray_;
  830. #endif
  831. };
  832. /** \brief const iterator for object and array value.
  833. *
  834. */
  835. class JSON_API ValueConstIterator : public ValueIteratorBase {
  836. friend class Value;
  837. public:
  838. typedef const Value value_type;
  839. typedef unsigned int size_t;
  840. typedef int difference_type;
  841. typedef const Value& reference;
  842. typedef const Value* pointer;
  843. typedef ValueConstIterator SelfType;
  844. ValueConstIterator();
  845. private:
  846. /*! \internal Use by Value to create an iterator.
  847. */
  848. #ifndef JSON_VALUE_USE_INTERNAL_MAP
  849. explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
  850. #else
  851. ValueConstIterator(const ValueInternalArray::IteratorState& state);
  852. ValueConstIterator(const ValueInternalMap::IteratorState& state);
  853. #endif
  854. public:
  855. SelfType& operator=(const ValueIteratorBase& other);
  856. SelfType operator++(int) {
  857. SelfType temp(*this);
  858. ++*this;
  859. return temp;
  860. }
  861. SelfType operator--(int) {
  862. SelfType temp(*this);
  863. --*this;
  864. return temp;
  865. }
  866. SelfType& operator--() {
  867. decrement();
  868. return *this;
  869. }
  870. SelfType& operator++() {
  871. increment();
  872. return *this;
  873. }
  874. reference operator*() const { return deref(); }
  875. pointer operator->() const { return &deref(); }
  876. };
  877. /** \brief Iterator for object and array value.
  878. */
  879. class JSON_API ValueIterator : public ValueIteratorBase {
  880. friend class Value;
  881. public:
  882. typedef Value value_type;
  883. typedef unsigned int size_t;
  884. typedef int difference_type;
  885. typedef Value& reference;
  886. typedef Value* pointer;
  887. typedef ValueIterator SelfType;
  888. ValueIterator();
  889. ValueIterator(const ValueConstIterator& other);
  890. ValueIterator(const ValueIterator& other);
  891. private:
  892. /*! \internal Use by Value to create an iterator.
  893. */
  894. #ifndef JSON_VALUE_USE_INTERNAL_MAP
  895. explicit ValueIterator(const Value::ObjectValues::iterator& current);
  896. #else
  897. ValueIterator(const ValueInternalArray::IteratorState& state);
  898. ValueIterator(const ValueInternalMap::IteratorState& state);
  899. #endif
  900. public:
  901. SelfType& operator=(const SelfType& other);
  902. SelfType operator++(int) {
  903. SelfType temp(*this);
  904. ++*this;
  905. return temp;
  906. }
  907. SelfType operator--(int) {
  908. SelfType temp(*this);
  909. --*this;
  910. return temp;
  911. }
  912. SelfType& operator--() {
  913. decrement();
  914. return *this;
  915. }
  916. SelfType& operator++() {
  917. increment();
  918. return *this;
  919. }
  920. reference operator*() const { return deref(); }
  921. pointer operator->() const { return &deref(); }
  922. };
  923. } // namespace Json
  924. #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  925. #pragma warning(pop)
  926. #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  927. #endif // CPPTL_JSON_H_INCLUDED