value.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  1. // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
  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. #include <exception>
  13. #ifndef JSON_USE_CPPTL_SMALLMAP
  14. #include <map>
  15. #else
  16. #include <cpptl/smallmap.h>
  17. #endif
  18. #ifdef JSON_USE_CPPTL
  19. #include <cpptl/forwards.h>
  20. #endif
  21. //Conditional NORETURN attribute on the throw functions would:
  22. // a) suppress false positives from static code analysis
  23. // b) possibly improve optimization opportunities.
  24. #if !defined(JSONCPP_NORETURN)
  25. # if defined(_MSC_VER)
  26. # define JSONCPP_NORETURN __declspec(noreturn)
  27. # elif defined(__GNUC__)
  28. # define JSONCPP_NORETURN __attribute__ ((__noreturn__))
  29. # else
  30. # define JSONCPP_NORETURN
  31. # endif
  32. #endif
  33. // Disable warning C4251: <data member>: <type> needs to have dll-interface to
  34. // be used by...
  35. #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  36. #pragma warning(push)
  37. #pragma warning(disable : 4251)
  38. #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  39. #pragma pack(push, 8)
  40. /** \brief JSON (JavaScript Object Notation).
  41. */
  42. namespace Json {
  43. /** Base class for all exceptions we throw.
  44. *
  45. * We use nothing but these internally. Of course, STL can throw others.
  46. */
  47. class JSON_API Exception : public std::exception {
  48. public:
  49. Exception(JSONCPP_STRING const& msg);
  50. ~Exception() JSONCPP_NOEXCEPT JSONCPP_OVERRIDE;
  51. char const* what() const JSONCPP_NOEXCEPT JSONCPP_OVERRIDE;
  52. protected:
  53. JSONCPP_STRING msg_;
  54. };
  55. /** Exceptions which the user cannot easily avoid.
  56. *
  57. * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
  58. *
  59. * \remark derived from Json::Exception
  60. */
  61. class JSON_API RuntimeError : public Exception {
  62. public:
  63. RuntimeError(JSONCPP_STRING const& msg);
  64. };
  65. /** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
  66. *
  67. * These are precondition-violations (user bugs) and internal errors (our bugs).
  68. *
  69. * \remark derived from Json::Exception
  70. */
  71. class JSON_API LogicError : public Exception {
  72. public:
  73. LogicError(JSONCPP_STRING const& msg);
  74. };
  75. /// used internally
  76. JSONCPP_NORETURN void throwRuntimeError(JSONCPP_STRING const& msg);
  77. /// used internally
  78. JSONCPP_NORETURN void throwLogicError(JSONCPP_STRING const& msg);
  79. /** \brief Type of the value held by a Value object.
  80. */
  81. enum ValueType {
  82. nullValue = 0, ///< 'null' value
  83. intValue, ///< signed integer value
  84. uintValue, ///< unsigned integer value
  85. realValue, ///< double value
  86. stringValue, ///< UTF-8 string value
  87. booleanValue, ///< bool value
  88. arrayValue, ///< array value (ordered list)
  89. objectValue ///< object value (collection of name/value pairs).
  90. };
  91. enum CommentPlacement {
  92. commentBefore = 0, ///< a comment placed on the line before a value
  93. commentAfterOnSameLine, ///< a comment just after a value on the same line
  94. commentAfter, ///< a comment on the line after a value (only make sense for
  95. /// root value)
  96. numberOfCommentPlacement
  97. };
  98. //# ifdef JSON_USE_CPPTL
  99. // typedef CppTL::AnyEnumerator<const char *> EnumMemberNames;
  100. // typedef CppTL::AnyEnumerator<const Value &> EnumValues;
  101. //# endif
  102. /** \brief Lightweight wrapper to tag static string.
  103. *
  104. * Value constructor and objectValue member assignment takes advantage of the
  105. * StaticString and avoid the cost of string duplication when storing the
  106. * string or the member name.
  107. *
  108. * Example of usage:
  109. * \code
  110. * Json::Value aValue( StaticString("some text") );
  111. * Json::Value object;
  112. * static const StaticString code("code");
  113. * object[code] = 1234;
  114. * \endcode
  115. */
  116. class JSON_API StaticString {
  117. public:
  118. explicit StaticString(const char* czstring) : c_str_(czstring) {}
  119. operator const char*() const { return c_str_; }
  120. const char* c_str() const { return c_str_; }
  121. private:
  122. const char* c_str_;
  123. };
  124. /** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
  125. *
  126. * This class is a discriminated union wrapper that can represents a:
  127. * - signed integer [range: Value::minInt - Value::maxInt]
  128. * - unsigned integer (range: 0 - Value::maxUInt)
  129. * - double
  130. * - UTF-8 string
  131. * - boolean
  132. * - 'null'
  133. * - an ordered list of Value
  134. * - collection of name/value pairs (javascript object)
  135. *
  136. * The type of the held value is represented by a #ValueType and
  137. * can be obtained using type().
  138. *
  139. * Values of an #objectValue or #arrayValue can be accessed using operator[]()
  140. * methods.
  141. * Non-const methods will automatically create the a #nullValue element
  142. * if it does not exist.
  143. * The sequence of an #arrayValue will be automatically resized and initialized
  144. * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
  145. *
  146. * The get() methods can be used to obtain default value in the case the
  147. * required element does not exist.
  148. *
  149. * It is possible to iterate over the list of a #objectValue values using
  150. * the getMemberNames() method.
  151. *
  152. * \note #Value string-length fit in size_t, but keys must be < 2^30.
  153. * (The reason is an implementation detail.) A #CharReader will raise an
  154. * exception if a bound is exceeded to avoid security holes in your app,
  155. * but the Value API does *not* check bounds. That is the responsibility
  156. * of the caller.
  157. */
  158. class JSON_API Value {
  159. friend class ValueIteratorBase;
  160. public:
  161. typedef std::vector<JSONCPP_STRING> Members;
  162. typedef ValueIterator iterator;
  163. typedef ValueConstIterator const_iterator;
  164. typedef Json::UInt UInt;
  165. typedef Json::Int Int;
  166. #if defined(JSON_HAS_INT64)
  167. typedef Json::UInt64 UInt64;
  168. typedef Json::Int64 Int64;
  169. #endif // defined(JSON_HAS_INT64)
  170. typedef Json::LargestInt LargestInt;
  171. typedef Json::LargestUInt LargestUInt;
  172. typedef Json::ArrayIndex ArrayIndex;
  173. // Required for boost integration, e. g. BOOST_TEST
  174. typedef std::string value_type;
  175. static const Value& null; ///< We regret this reference to a global instance; prefer the simpler Value().
  176. static const Value& nullRef; ///< just a kludge for binary-compatibility; same as null
  177. static Value const& nullSingleton(); ///< Prefer this to null or nullRef.
  178. /// Minimum signed integer value that can be stored in a Json::Value.
  179. static const LargestInt minLargestInt;
  180. /// Maximum signed integer value that can be stored in a Json::Value.
  181. static const LargestInt maxLargestInt;
  182. /// Maximum unsigned integer value that can be stored in a Json::Value.
  183. static const LargestUInt maxLargestUInt;
  184. /// Minimum signed int value that can be stored in a Json::Value.
  185. static const Int minInt;
  186. /// Maximum signed int value that can be stored in a Json::Value.
  187. static const Int maxInt;
  188. /// Maximum unsigned int value that can be stored in a Json::Value.
  189. static const UInt maxUInt;
  190. #if defined(JSON_HAS_INT64)
  191. /// Minimum signed 64 bits int value that can be stored in a Json::Value.
  192. static const Int64 minInt64;
  193. /// Maximum signed 64 bits int value that can be stored in a Json::Value.
  194. static const Int64 maxInt64;
  195. /// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
  196. static const UInt64 maxUInt64;
  197. #endif // defined(JSON_HAS_INT64)
  198. private:
  199. #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
  200. class CZString {
  201. public:
  202. enum DuplicationPolicy {
  203. noDuplication = 0,
  204. duplicate,
  205. duplicateOnCopy
  206. };
  207. CZString(ArrayIndex index);
  208. CZString(char const* str, unsigned length, DuplicationPolicy allocate);
  209. CZString(CZString const& other);
  210. #if JSON_HAS_RVALUE_REFERENCES
  211. CZString(CZString&& other);
  212. #endif
  213. ~CZString();
  214. CZString& operator=(const CZString& other);
  215. #if JSON_HAS_RVALUE_REFERENCES
  216. CZString& operator=(CZString&& other);
  217. #endif
  218. bool operator<(CZString const& other) const;
  219. bool operator==(CZString const& other) const;
  220. ArrayIndex index() const;
  221. //const char* c_str() const; ///< \deprecated
  222. char const* data() const;
  223. unsigned length() const;
  224. bool isStaticString() const;
  225. private:
  226. void swap(CZString& other);
  227. struct StringStorage {
  228. unsigned policy_: 2;
  229. unsigned length_: 30; // 1GB max
  230. };
  231. char const* cstr_; // actually, a prefixed string, unless policy is noDup
  232. union {
  233. ArrayIndex index_;
  234. StringStorage storage_;
  235. };
  236. };
  237. public:
  238. #ifndef JSON_USE_CPPTL_SMALLMAP
  239. typedef std::map<CZString, Value> ObjectValues;
  240. #else
  241. typedef CppTL::SmallMap<CZString, Value> ObjectValues;
  242. #endif // ifndef JSON_USE_CPPTL_SMALLMAP
  243. #endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
  244. public:
  245. /** \brief Create a default Value of the given type.
  246. This is a very useful constructor.
  247. To create an empty array, pass arrayValue.
  248. To create an empty object, pass objectValue.
  249. Another Value can then be set to this one by assignment.
  250. This is useful since clear() and resize() will not alter types.
  251. Examples:
  252. \code
  253. Json::Value null_value; // null
  254. Json::Value arr_value(Json::arrayValue); // []
  255. Json::Value obj_value(Json::objectValue); // {}
  256. \endcode
  257. */
  258. Value(ValueType type = nullValue);
  259. Value(Int value);
  260. Value(UInt value);
  261. #if defined(JSON_HAS_INT64)
  262. Value(Int64 value);
  263. Value(UInt64 value);
  264. #endif // if defined(JSON_HAS_INT64)
  265. Value(double value);
  266. Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.)
  267. Value(const char* begin, const char* end); ///< Copy all, incl zeroes.
  268. /** \brief Constructs a value from a static string.
  269. * Like other value string constructor but do not duplicate the string for
  270. * internal storage. The given string must remain alive after the call to this
  271. * constructor.
  272. * \note This works only for null-terminated strings. (We cannot change the
  273. * size of this class, so we have nowhere to store the length,
  274. * which might be computed later for various operations.)
  275. *
  276. * Example of usage:
  277. * \code
  278. * static StaticString foo("some text");
  279. * Json::Value aValue(foo);
  280. * \endcode
  281. */
  282. Value(const StaticString& value);
  283. Value(const JSONCPP_STRING& value); ///< Copy data() til size(). Embedded zeroes too.
  284. #ifdef JSON_USE_CPPTL
  285. Value(const CppTL::ConstString& value);
  286. #endif
  287. Value(bool value);
  288. /// Deep copy.
  289. Value(const Value& other);
  290. #if JSON_HAS_RVALUE_REFERENCES
  291. /// Move constructor
  292. Value(Value&& other);
  293. #endif
  294. ~Value();
  295. /// Deep copy, then swap(other).
  296. /// \note Over-write existing comments. To preserve comments, use #swapPayload().
  297. Value& operator=(Value other);
  298. /// Swap everything.
  299. void swap(Value& other);
  300. /// Swap values but leave comments and source offsets in place.
  301. void swapPayload(Value& other);
  302. /// copy everything.
  303. void copy(const Value& other);
  304. /// copy values but leave comments and source offsets in place.
  305. void copyPayload(const Value& other);
  306. ValueType type() const;
  307. /// Compare payload only, not comments etc.
  308. bool operator<(const Value& other) const;
  309. bool operator<=(const Value& other) const;
  310. bool operator>=(const Value& other) const;
  311. bool operator>(const Value& other) const;
  312. bool operator==(const Value& other) const;
  313. bool operator!=(const Value& other) const;
  314. int compare(const Value& other) const;
  315. const char* asCString() const; ///< Embedded zeroes could cause you trouble!
  316. #if JSONCPP_USING_SECURE_MEMORY
  317. unsigned getCStringLength() const; //Allows you to understand the length of the CString
  318. #endif
  319. JSONCPP_STRING asString() const; ///< Embedded zeroes are possible.
  320. /** Get raw char* of string-value.
  321. * \return false if !string. (Seg-fault if str or end are NULL.)
  322. */
  323. bool getString(
  324. char const** begin, char const** end) const;
  325. #ifdef JSON_USE_CPPTL
  326. CppTL::ConstString asConstString() const;
  327. #endif
  328. Int asInt() const;
  329. UInt asUInt() const;
  330. #if defined(JSON_HAS_INT64)
  331. Int64 asInt64() const;
  332. UInt64 asUInt64() const;
  333. #endif // if defined(JSON_HAS_INT64)
  334. LargestInt asLargestInt() const;
  335. LargestUInt asLargestUInt() const;
  336. float asFloat() const;
  337. double asDouble() const;
  338. bool asBool() const;
  339. bool isNull() const;
  340. bool isBool() const;
  341. bool isInt() const;
  342. bool isInt64() const;
  343. bool isUInt() const;
  344. bool isUInt64() const;
  345. bool isIntegral() const;
  346. bool isDouble() const;
  347. bool isNumeric() const;
  348. bool isString() const;
  349. bool isArray() const;
  350. bool isObject() const;
  351. bool isConvertibleTo(ValueType other) const;
  352. /// Number of values in array or object
  353. ArrayIndex size() const;
  354. /// \brief Return true if empty array, empty object, or null;
  355. /// otherwise, false.
  356. bool empty() const;
  357. /// Return !isNull()
  358. explicit operator bool() const;
  359. /// Remove all object members and array elements.
  360. /// \pre type() is arrayValue, objectValue, or nullValue
  361. /// \post type() is unchanged
  362. void clear();
  363. /// Resize the array to size elements.
  364. /// New elements are initialized to null.
  365. /// May only be called on nullValue or arrayValue.
  366. /// \pre type() is arrayValue or nullValue
  367. /// \post type() is arrayValue
  368. void resize(ArrayIndex size);
  369. /// Access an array element (zero based index ).
  370. /// If the array contains less than index element, then null value are
  371. /// inserted
  372. /// in the array so that its size is index+1.
  373. /// (You may need to say 'value[0u]' to get your compiler to distinguish
  374. /// this from the operator[] which takes a string.)
  375. Value& operator[](ArrayIndex index);
  376. /// Access an array element (zero based index ).
  377. /// If the array contains less than index element, then null value are
  378. /// inserted
  379. /// in the array so that its size is index+1.
  380. /// (You may need to say 'value[0u]' to get your compiler to distinguish
  381. /// this from the operator[] which takes a string.)
  382. Value& operator[](int index);
  383. /// Access an array element (zero based index )
  384. /// (You may need to say 'value[0u]' to get your compiler to distinguish
  385. /// this from the operator[] which takes a string.)
  386. const Value& operator[](ArrayIndex index) const;
  387. /// Access an array element (zero based index )
  388. /// (You may need to say 'value[0u]' to get your compiler to distinguish
  389. /// this from the operator[] which takes a string.)
  390. const Value& operator[](int index) const;
  391. /// If the array contains at least index+1 elements, returns the element
  392. /// value,
  393. /// otherwise returns defaultValue.
  394. Value get(ArrayIndex index, const Value& defaultValue) const;
  395. /// Return true if index < size().
  396. bool isValidIndex(ArrayIndex index) const;
  397. /// \brief Append value to array at the end.
  398. ///
  399. /// Equivalent to jsonvalue[jsonvalue.size()] = value;
  400. Value& append(const Value& value);
  401. #if JSON_HAS_RVALUE_REFERENCES
  402. Value& append(Value&& value);
  403. #endif
  404. /// Access an object value by name, create a null member if it does not exist.
  405. /// \note Because of our implementation, keys are limited to 2^30 -1 chars.
  406. /// Exceeding that will cause an exception.
  407. Value& operator[](const char* key);
  408. /// Access an object value by name, returns null if there is no member with
  409. /// that name.
  410. const Value& operator[](const char* key) const;
  411. /// Access an object value by name, create a null member if it does not exist.
  412. /// \param key may contain embedded nulls.
  413. Value& operator[](const JSONCPP_STRING& key);
  414. /// Access an object value by name, returns null if there is no member with
  415. /// that name.
  416. /// \param key may contain embedded nulls.
  417. const Value& operator[](const JSONCPP_STRING& key) const;
  418. /** \brief Access an object value by name, create a null member if it does not
  419. exist.
  420. * If the object has no entry for that name, then the member name used to store
  421. * the new entry is not duplicated.
  422. * Example of use:
  423. * \code
  424. * Json::Value object;
  425. * static const StaticString code("code");
  426. * object[code] = 1234;
  427. * \endcode
  428. */
  429. Value& operator[](const StaticString& key);
  430. #ifdef JSON_USE_CPPTL
  431. /// Access an object value by name, create a null member if it does not exist.
  432. Value& operator[](const CppTL::ConstString& key);
  433. /// Access an object value by name, returns null if there is no member with
  434. /// that name.
  435. const Value& operator[](const CppTL::ConstString& key) const;
  436. #endif
  437. /// Return the member named key if it exist, defaultValue otherwise.
  438. /// \note deep copy
  439. Value get(const char* key, const Value& defaultValue) const;
  440. /// Return the member named key if it exist, defaultValue otherwise.
  441. /// \note deep copy
  442. /// \note key may contain embedded nulls.
  443. Value get(const char* begin, const char* end, const Value& defaultValue) const;
  444. /// Return the member named key if it exist, defaultValue otherwise.
  445. /// \note deep copy
  446. /// \param key may contain embedded nulls.
  447. Value get(const JSONCPP_STRING& key, const Value& defaultValue) const;
  448. #ifdef JSON_USE_CPPTL
  449. /// Return the member named key if it exist, defaultValue otherwise.
  450. /// \note deep copy
  451. Value get(const CppTL::ConstString& key, const Value& defaultValue) const;
  452. #endif
  453. /// Most general and efficient version of isMember()const, get()const,
  454. /// and operator[]const
  455. /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
  456. Value const* find(char const* begin, char const* end) const;
  457. /// Most general and efficient version of object-mutators.
  458. /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
  459. /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
  460. Value const* demand(char const* begin, char const* end);
  461. /// \brief Remove and return the named member.
  462. ///
  463. /// Do nothing if it did not exist.
  464. /// \return the removed Value, or null.
  465. /// \pre type() is objectValue or nullValue
  466. /// \post type() is unchanged
  467. /// \deprecated
  468. void removeMember(const char* key);
  469. /// Same as removeMember(const char*)
  470. /// \param key may contain embedded nulls.
  471. /// \deprecated
  472. void removeMember(const JSONCPP_STRING& key);
  473. /// Same as removeMember(const char* begin, const char* end, Value* removed),
  474. /// but 'key' is null-terminated.
  475. bool removeMember(const char* key, Value* removed);
  476. /** \brief Remove the named map member.
  477. Update 'removed' iff removed.
  478. \param key may contain embedded nulls.
  479. \return true iff removed (no exceptions)
  480. */
  481. bool removeMember(JSONCPP_STRING const& key, Value* removed);
  482. /// Same as removeMember(JSONCPP_STRING const& key, Value* removed)
  483. bool removeMember(const char* begin, const char* end, Value* removed);
  484. /** \brief Remove the indexed array element.
  485. O(n) expensive operations.
  486. Update 'removed' iff removed.
  487. \return true iff removed (no exceptions)
  488. */
  489. bool removeIndex(ArrayIndex i, Value* removed);
  490. /// Return true if the object has a member named key.
  491. /// \note 'key' must be null-terminated.
  492. bool isMember(const char* key) const;
  493. /// Return true if the object has a member named key.
  494. /// \param key may contain embedded nulls.
  495. bool isMember(const JSONCPP_STRING& key) const;
  496. /// Same as isMember(JSONCPP_STRING const& key)const
  497. bool isMember(const char* begin, const char* end) const;
  498. #ifdef JSON_USE_CPPTL
  499. /// Return true if the object has a member named key.
  500. bool isMember(const CppTL::ConstString& key) const;
  501. #endif
  502. /// \brief Return a list of the member names.
  503. ///
  504. /// If null, return an empty list.
  505. /// \pre type() is objectValue or nullValue
  506. /// \post if type() was nullValue, it remains nullValue
  507. Members getMemberNames() const;
  508. //# ifdef JSON_USE_CPPTL
  509. // EnumMemberNames enumMemberNames() const;
  510. // EnumValues enumValues() const;
  511. //# endif
  512. /// \deprecated Always pass len.
  513. JSONCPP_DEPRECATED("Use setComment(JSONCPP_STRING const&) instead.")
  514. void setComment(const char* comment, CommentPlacement placement);
  515. /// Comments must be //... or /* ... */
  516. void setComment(const char* comment, size_t len, CommentPlacement placement);
  517. /// Comments must be //... or /* ... */
  518. void setComment(const JSONCPP_STRING& comment, CommentPlacement placement);
  519. bool hasComment(CommentPlacement placement) const;
  520. /// Include delimiters and embedded newlines.
  521. JSONCPP_STRING getComment(CommentPlacement placement) const;
  522. JSONCPP_STRING toStyledString() const;
  523. const_iterator begin() const;
  524. const_iterator end() const;
  525. iterator begin();
  526. iterator end();
  527. // Accessors for the [start, limit) range of bytes within the JSON text from
  528. // which this value was parsed, if any.
  529. void setOffsetStart(ptrdiff_t start);
  530. void setOffsetLimit(ptrdiff_t limit);
  531. ptrdiff_t getOffsetStart() const;
  532. ptrdiff_t getOffsetLimit() const;
  533. private:
  534. void initBasic(ValueType type, bool allocated = false);
  535. Value& resolveReference(const char* key);
  536. Value& resolveReference(const char* key, const char* end);
  537. struct CommentInfo {
  538. CommentInfo();
  539. ~CommentInfo();
  540. void setComment(const char* text, size_t len);
  541. char* comment_;
  542. };
  543. // struct MemberNamesTransform
  544. //{
  545. // typedef const char *result_type;
  546. // const char *operator()( const CZString &name ) const
  547. // {
  548. // return name.c_str();
  549. // }
  550. //};
  551. union ValueHolder {
  552. LargestInt int_;
  553. LargestUInt uint_;
  554. double real_;
  555. bool bool_;
  556. char* string_; // actually ptr to unsigned, followed by str, unless !allocated_
  557. ObjectValues* map_;
  558. } value_;
  559. ValueType type_ : 8;
  560. unsigned int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
  561. // If not allocated_, string_ must be null-terminated.
  562. CommentInfo* comments_;
  563. // [start, limit) byte offsets in the source JSON text from which this Value
  564. // was extracted.
  565. ptrdiff_t start_;
  566. ptrdiff_t limit_;
  567. };
  568. /** \brief Experimental and untested: represents an element of the "path" to
  569. * access a node.
  570. */
  571. class JSON_API PathArgument {
  572. public:
  573. friend class Path;
  574. PathArgument();
  575. PathArgument(ArrayIndex index);
  576. PathArgument(const char* key);
  577. PathArgument(const JSONCPP_STRING& key);
  578. private:
  579. enum Kind {
  580. kindNone = 0,
  581. kindIndex,
  582. kindKey
  583. };
  584. JSONCPP_STRING key_;
  585. ArrayIndex index_;
  586. Kind kind_;
  587. };
  588. /** \brief Experimental and untested: represents a "path" to access a node.
  589. *
  590. * Syntax:
  591. * - "." => root node
  592. * - ".[n]" => elements at index 'n' of root node (an array value)
  593. * - ".name" => member named 'name' of root node (an object value)
  594. * - ".name1.name2.name3"
  595. * - ".[0][1][2].name1[3]"
  596. * - ".%" => member name is provided as parameter
  597. * - ".[%]" => index is provied as parameter
  598. */
  599. class JSON_API Path {
  600. public:
  601. Path(const JSONCPP_STRING& path,
  602. const PathArgument& a1 = PathArgument(),
  603. const PathArgument& a2 = PathArgument(),
  604. const PathArgument& a3 = PathArgument(),
  605. const PathArgument& a4 = PathArgument(),
  606. const PathArgument& a5 = PathArgument());
  607. const Value& resolve(const Value& root) const;
  608. Value resolve(const Value& root, const Value& defaultValue) const;
  609. /// Creates the "path" to access the specified node and returns a reference on
  610. /// the node.
  611. Value& make(Value& root) const;
  612. private:
  613. typedef std::vector<const PathArgument*> InArgs;
  614. typedef std::vector<PathArgument> Args;
  615. void makePath(const JSONCPP_STRING& path, const InArgs& in);
  616. void addPathInArg(const JSONCPP_STRING& path,
  617. const InArgs& in,
  618. InArgs::const_iterator& itInArg,
  619. PathArgument::Kind kind);
  620. void invalidPath(const JSONCPP_STRING& path, int location);
  621. Args args_;
  622. };
  623. /** \brief base class for Value iterators.
  624. *
  625. */
  626. class JSON_API ValueIteratorBase {
  627. public:
  628. typedef std::bidirectional_iterator_tag iterator_category;
  629. typedef unsigned int size_t;
  630. typedef int difference_type;
  631. typedef ValueIteratorBase SelfType;
  632. bool operator==(const SelfType& other) const { return isEqual(other); }
  633. bool operator!=(const SelfType& other) const { return !isEqual(other); }
  634. difference_type operator-(const SelfType& other) const {
  635. return other.computeDistance(*this);
  636. }
  637. /// Return either the index or the member name of the referenced value as a
  638. /// Value.
  639. Value key() const;
  640. /// Return the index of the referenced Value, or -1 if it is not an arrayValue.
  641. UInt index() const;
  642. /// Return the member name of the referenced Value, or "" if it is not an
  643. /// objectValue.
  644. /// \note Avoid `c_str()` on result, as embedded zeroes are possible.
  645. JSONCPP_STRING name() const;
  646. /// Return the member name of the referenced Value. "" if it is not an
  647. /// objectValue.
  648. /// \deprecated This cannot be used for UTF-8 strings, since there can be embedded nulls.
  649. JSONCPP_DEPRECATED("Use `key = name();` instead.")
  650. char const* memberName() const;
  651. /// Return the member name of the referenced Value, or NULL if it is not an
  652. /// objectValue.
  653. /// \note Better version than memberName(). Allows embedded nulls.
  654. char const* memberName(char const** end) const;
  655. protected:
  656. Value& deref() const;
  657. void increment();
  658. void decrement();
  659. difference_type computeDistance(const SelfType& other) const;
  660. bool isEqual(const SelfType& other) const;
  661. void copy(const SelfType& other);
  662. private:
  663. Value::ObjectValues::iterator current_;
  664. // Indicates that iterator is for a null value.
  665. bool isNull_;
  666. public:
  667. // For some reason, BORLAND needs these at the end, rather
  668. // than earlier. No idea why.
  669. ValueIteratorBase();
  670. explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
  671. };
  672. /** \brief const iterator for object and array value.
  673. *
  674. */
  675. class JSON_API ValueConstIterator : public ValueIteratorBase {
  676. friend class Value;
  677. public:
  678. typedef const Value value_type;
  679. //typedef unsigned int size_t;
  680. //typedef int difference_type;
  681. typedef const Value& reference;
  682. typedef const Value* pointer;
  683. typedef ValueConstIterator SelfType;
  684. ValueConstIterator();
  685. ValueConstIterator(ValueIterator const& other);
  686. private:
  687. /*! \internal Use by Value to create an iterator.
  688. */
  689. explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
  690. public:
  691. SelfType& operator=(const ValueIteratorBase& other);
  692. SelfType operator++(int) {
  693. SelfType temp(*this);
  694. ++*this;
  695. return temp;
  696. }
  697. SelfType operator--(int) {
  698. SelfType temp(*this);
  699. --*this;
  700. return temp;
  701. }
  702. SelfType& operator--() {
  703. decrement();
  704. return *this;
  705. }
  706. SelfType& operator++() {
  707. increment();
  708. return *this;
  709. }
  710. reference operator*() const { return deref(); }
  711. pointer operator->() const { return &deref(); }
  712. };
  713. /** \brief Iterator for object and array value.
  714. */
  715. class JSON_API ValueIterator : public ValueIteratorBase {
  716. friend class Value;
  717. public:
  718. typedef Value value_type;
  719. typedef unsigned int size_t;
  720. typedef int difference_type;
  721. typedef Value& reference;
  722. typedef Value* pointer;
  723. typedef ValueIterator SelfType;
  724. ValueIterator();
  725. explicit ValueIterator(const ValueConstIterator& other);
  726. ValueIterator(const ValueIterator& other);
  727. private:
  728. /*! \internal Use by Value to create an iterator.
  729. */
  730. explicit ValueIterator(const Value::ObjectValues::iterator& current);
  731. public:
  732. SelfType& operator=(const SelfType& other);
  733. SelfType operator++(int) {
  734. SelfType temp(*this);
  735. ++*this;
  736. return temp;
  737. }
  738. SelfType operator--(int) {
  739. SelfType temp(*this);
  740. --*this;
  741. return temp;
  742. }
  743. SelfType& operator--() {
  744. decrement();
  745. return *this;
  746. }
  747. SelfType& operator++() {
  748. increment();
  749. return *this;
  750. }
  751. reference operator*() const { return deref(); }
  752. pointer operator->() const { return &deref(); }
  753. };
  754. } // namespace Json
  755. namespace std {
  756. /// Specialize std::swap() for Json::Value.
  757. template<>
  758. inline void swap(Json::Value& a, Json::Value& b) { a.swap(b); }
  759. }
  760. #pragma pack(pop)
  761. #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  762. #pragma warning(pop)
  763. #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  764. #endif // CPPTL_JSON_H_INCLUDED