value.h 30 KB

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