value.h 30 KB

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