value.h 29 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() JSONCPP_NOEXCEPT override;
  62. char const* what() const JSONCPP_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(const Value& other);
  312. Value(Value&& other);
  313. ~Value();
  314. /// \note Overwrite existing comments. To preserve comments, use
  315. /// #swapPayload().
  316. Value& operator=(const Value& other);
  317. Value& operator=(Value&& other);
  318. /// Swap everything.
  319. void swap(Value& other);
  320. /// Swap values but leave comments and source offsets in place.
  321. void swapPayload(Value& other);
  322. /// copy everything.
  323. void copy(const Value& other);
  324. /// copy values but leave comments and source offsets in place.
  325. void copyPayload(const Value& other);
  326. ValueType type() const;
  327. /// Compare payload only, not comments etc.
  328. bool operator<(const Value& other) const;
  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. int compare(const Value& other) const;
  335. const char* asCString() const; ///< Embedded zeroes could cause you trouble!
  336. #if JSONCPP_USING_SECURE_MEMORY
  337. unsigned getCStringLength() const; // Allows you to understand the length of
  338. // the CString
  339. #endif
  340. String asString() const; ///< Embedded zeroes are possible.
  341. /** Get raw char* of string-value.
  342. * \return false if !string. (Seg-fault if str or end are NULL.)
  343. */
  344. bool getString(char const** begin, char const** end) const;
  345. Int asInt() const;
  346. UInt asUInt() const;
  347. #if defined(JSON_HAS_INT64)
  348. Int64 asInt64() const;
  349. UInt64 asUInt64() const;
  350. #endif // if defined(JSON_HAS_INT64)
  351. LargestInt asLargestInt() const;
  352. LargestUInt asLargestUInt() const;
  353. float asFloat() const;
  354. double asDouble() const;
  355. bool asBool() const;
  356. bool isNull() const;
  357. bool isBool() const;
  358. bool isInt() const;
  359. bool isInt64() const;
  360. bool isUInt() const;
  361. bool isUInt64() const;
  362. bool isIntegral() const;
  363. bool isDouble() const;
  364. bool isNumeric() const;
  365. bool isString() const;
  366. bool isArray() const;
  367. bool isObject() const;
  368. /// The `as<T>` and `is<T>` member function templates and specializations.
  369. template <typename T> T as() const JSONCPP_TEMPLATE_DELETE;
  370. template <typename T> bool is() const JSONCPP_TEMPLATE_DELETE;
  371. bool isConvertibleTo(ValueType other) const;
  372. /// Number of values in array or object
  373. ArrayIndex size() const;
  374. /// \brief Return true if empty array, empty object, or null;
  375. /// otherwise, false.
  376. bool empty() const;
  377. /// Return !isNull()
  378. JSONCPP_OP_EXPLICIT operator bool() const;
  379. /// Remove all object members and array elements.
  380. /// \pre type() is arrayValue, objectValue, or nullValue
  381. /// \post type() is unchanged
  382. void clear();
  383. /// Resize the array to newSize elements.
  384. /// New elements are initialized to null.
  385. /// May only be called on nullValue or arrayValue.
  386. /// \pre type() is arrayValue or nullValue
  387. /// \post type() is arrayValue
  388. void resize(ArrayIndex newSize);
  389. //@{
  390. /// Access an array element (zero based index). If the array contains less
  391. /// than index element, then null value are inserted in the array so that
  392. /// its size is index+1.
  393. /// (You may need to say 'value[0u]' to get your compiler to distinguish
  394. /// this from the operator[] which takes a string.)
  395. Value& operator[](ArrayIndex index);
  396. Value& operator[](int index);
  397. //@}
  398. //@{
  399. /// Access an array element (zero based index).
  400. /// (You may need to say 'value[0u]' to get your compiler to distinguish
  401. /// this from the operator[] which takes a string.)
  402. const Value& operator[](ArrayIndex index) const;
  403. const Value& operator[](int index) const;
  404. //@}
  405. /// If the array contains at least index+1 elements, returns the element
  406. /// value, otherwise returns defaultValue.
  407. Value get(ArrayIndex index, const Value& defaultValue) const;
  408. /// Return true if index < size().
  409. bool isValidIndex(ArrayIndex index) const;
  410. /// \brief Append value to array at the end.
  411. ///
  412. /// Equivalent to jsonvalue[jsonvalue.size()] = value;
  413. Value& append(const Value& value);
  414. Value& append(Value&& value);
  415. /// \brief Insert value in array at specific index
  416. bool insert(ArrayIndex index, const Value& newValue);
  417. bool insert(ArrayIndex index, Value&& newValue);
  418. /// Access an object value by name, create a null member if it does not exist.
  419. /// \note Because of our implementation, keys are limited to 2^30 -1 chars.
  420. /// Exceeding that will cause an exception.
  421. Value& operator[](const char* key);
  422. /// Access an object value by name, returns null if there is no member with
  423. /// that name.
  424. const Value& operator[](const char* key) const;
  425. /// Access an object value by name, create a null member if it does not exist.
  426. /// \param key may contain embedded nulls.
  427. Value& operator[](const String& key);
  428. /// Access an object value by name, returns null if there is no member with
  429. /// that name.
  430. /// \param key may contain embedded nulls.
  431. const Value& operator[](const String& key) const;
  432. /** \brief Access an object value by name, create a null member if it does not
  433. * exist.
  434. *
  435. * If the object has no entry for that name, then the member name used to
  436. * store the new entry is not duplicated.
  437. * Example of use:
  438. * \code
  439. * Json::Value object;
  440. * static const StaticString code("code");
  441. * object[code] = 1234;
  442. * \endcode
  443. */
  444. Value& operator[](const StaticString& key);
  445. /// Return the member named key if it exist, defaultValue otherwise.
  446. /// \note deep copy
  447. Value get(const char* key, const Value& defaultValue) const;
  448. /// Return the member named key if it exist, defaultValue otherwise.
  449. /// \note deep copy
  450. /// \note key may contain embedded nulls.
  451. Value get(const char* begin, const char* end,
  452. const Value& defaultValue) const;
  453. /// Return the member named key if it exist, defaultValue otherwise.
  454. /// \note deep copy
  455. /// \param key may contain embedded nulls.
  456. Value get(const String& key, const Value& defaultValue) const;
  457. /// Most general and efficient version of isMember()const, get()const,
  458. /// and operator[]const
  459. /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
  460. Value const* find(char const* begin, char const* end) const;
  461. /// Most general and efficient version of object-mutators.
  462. /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
  463. /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
  464. Value* demand(char const* begin, char const* end);
  465. /// \brief Remove and return the named member.
  466. ///
  467. /// Do nothing if it did not exist.
  468. /// \pre type() is objectValue or nullValue
  469. /// \post type() is unchanged
  470. void removeMember(const char* key);
  471. /// Same as removeMember(const char*)
  472. /// \param key may contain embedded nulls.
  473. void removeMember(const String& key);
  474. /// Same as removeMember(const char* begin, const char* end, Value* removed),
  475. /// but 'key' is null-terminated.
  476. bool removeMember(const char* key, Value* removed);
  477. /** \brief Remove the named map member.
  478. *
  479. * Update 'removed' iff removed.
  480. * \param key may contain embedded nulls.
  481. * \return true iff removed (no exceptions)
  482. */
  483. bool removeMember(String const& key, Value* removed);
  484. /// Same as removeMember(String const& key, Value* removed)
  485. bool removeMember(const char* begin, const char* end, Value* removed);
  486. /** \brief Remove the indexed array element.
  487. *
  488. * O(n) expensive operations.
  489. * Update 'removed' iff removed.
  490. * \return true if removed (no exceptions)
  491. */
  492. bool removeIndex(ArrayIndex index, Value* removed);
  493. /// Return true if the object has a member named key.
  494. /// \note 'key' must be null-terminated.
  495. bool isMember(const char* key) const;
  496. /// Return true if the object has a member named key.
  497. /// \param key may contain embedded nulls.
  498. bool isMember(const String& key) const;
  499. /// Same as isMember(String const& key)const
  500. bool isMember(const char* begin, const char* end) const;
  501. /// \brief Return a list of the member names.
  502. ///
  503. /// If null, return an empty list.
  504. /// \pre type() is objectValue or nullValue
  505. /// \post if type() was nullValue, it remains nullValue
  506. Members getMemberNames() const;
  507. /// \deprecated Always pass len.
  508. JSONCPP_DEPRECATED("Use setComment(String const&) instead.")
  509. void setComment(const char* comment, CommentPlacement placement) {
  510. setComment(String(comment, strlen(comment)), placement);
  511. }
  512. /// Comments must be //... or /* ... */
  513. void setComment(const char* comment, size_t len, CommentPlacement placement) {
  514. setComment(String(comment, len), placement);
  515. }
  516. /// Comments must be //... or /* ... */
  517. void setComment(String comment, CommentPlacement placement);
  518. bool hasComment(CommentPlacement placement) const;
  519. /// Include delimiters and embedded newlines.
  520. String getComment(CommentPlacement placement) const;
  521. String toStyledString() const;
  522. const_iterator begin() const;
  523. const_iterator end() const;
  524. iterator begin();
  525. iterator end();
  526. // Accessors for the [start, limit) range of bytes within the JSON text from
  527. // which this value was parsed, if any.
  528. void setOffsetStart(ptrdiff_t start);
  529. void setOffsetLimit(ptrdiff_t limit);
  530. ptrdiff_t getOffsetStart() const;
  531. ptrdiff_t getOffsetLimit() const;
  532. private:
  533. void setType(ValueType v) {
  534. bits_.value_type_ = static_cast<unsigned char>(v);
  535. }
  536. bool isAllocated() const { return bits_.allocated_; }
  537. void setIsAllocated(bool v) { bits_.allocated_ = v; }
  538. void initBasic(ValueType type, bool allocated = false);
  539. void dupPayload(const Value& other);
  540. void releasePayload();
  541. void dupMeta(const Value& other);
  542. Value& resolveReference(const char* key);
  543. Value& resolveReference(const char* key, const char* end);
  544. // struct MemberNamesTransform
  545. //{
  546. // typedef const char *result_type;
  547. // const char *operator()( const CZString &name ) const
  548. // {
  549. // return name.c_str();
  550. // }
  551. //};
  552. union ValueHolder {
  553. LargestInt int_;
  554. LargestUInt uint_;
  555. double real_;
  556. bool bool_;
  557. char* string_; // if allocated_, ptr to { unsigned, char[] }.
  558. ObjectValues* map_;
  559. } value_;
  560. struct {
  561. // Really a ValueType, but types should agree for bitfield packing.
  562. unsigned int value_type_ : 8;
  563. // Unless allocated_, string_ must be null-terminated.
  564. unsigned int allocated_ : 1;
  565. } bits_;
  566. class Comments {
  567. public:
  568. Comments() = default;
  569. Comments(const Comments& that);
  570. Comments(Comments&& that);
  571. Comments& operator=(const Comments& that);
  572. Comments& operator=(Comments&& that);
  573. bool has(CommentPlacement slot) const;
  574. String get(CommentPlacement slot) const;
  575. void set(CommentPlacement slot, String comment);
  576. private:
  577. using Array = std::array<String, numberOfCommentPlacement>;
  578. std::unique_ptr<Array> ptr_;
  579. };
  580. Comments comments_;
  581. // [start, limit) byte offsets in the source JSON text from which this Value
  582. // was extracted.
  583. ptrdiff_t start_;
  584. ptrdiff_t limit_;
  585. };
  586. template <> inline bool Value::as<bool>() const { return asBool(); }
  587. template <> inline bool Value::is<bool>() const { return isBool(); }
  588. template <> inline Int Value::as<Int>() const { return asInt(); }
  589. template <> inline bool Value::is<Int>() const { return isInt(); }
  590. template <> inline UInt Value::as<UInt>() const { return asUInt(); }
  591. template <> inline bool Value::is<UInt>() const { return isUInt(); }
  592. #if defined(JSON_HAS_INT64)
  593. template <> inline Int64 Value::as<Int64>() const { return asInt64(); }
  594. template <> inline bool Value::is<Int64>() const { return isInt64(); }
  595. template <> inline UInt64 Value::as<UInt64>() const { return asUInt64(); }
  596. template <> inline bool Value::is<UInt64>() const { return isUInt64(); }
  597. #endif
  598. template <> inline double Value::as<double>() const { return asDouble(); }
  599. template <> inline bool Value::is<double>() const { return isDouble(); }
  600. template <> inline String Value::as<String>() const { return asString(); }
  601. template <> inline bool Value::is<String>() const { return isString(); }
  602. /// These `as` specializations are type conversions, and do not have a
  603. /// corresponding `is`.
  604. template <> inline float Value::as<float>() const { return asFloat(); }
  605. template <> inline const char* Value::as<const char*>() const {
  606. return asCString();
  607. }
  608. /** \brief Experimental and untested: represents an element of the "path" to
  609. * access a node.
  610. */
  611. class JSON_API PathArgument {
  612. public:
  613. friend class Path;
  614. PathArgument();
  615. PathArgument(ArrayIndex index);
  616. PathArgument(const char* key);
  617. PathArgument(String key);
  618. private:
  619. enum Kind { kindNone = 0, kindIndex, kindKey };
  620. String key_;
  621. ArrayIndex index_{};
  622. Kind kind_{kindNone};
  623. };
  624. /** \brief Experimental and untested: represents a "path" to access a node.
  625. *
  626. * Syntax:
  627. * - "." => root node
  628. * - ".[n]" => elements at index 'n' of root node (an array value)
  629. * - ".name" => member named 'name' of root node (an object value)
  630. * - ".name1.name2.name3"
  631. * - ".[0][1][2].name1[3]"
  632. * - ".%" => member name is provided as parameter
  633. * - ".[%]" => index is provided as parameter
  634. */
  635. class JSON_API Path {
  636. public:
  637. Path(const String& path, const PathArgument& a1 = PathArgument(),
  638. const PathArgument& a2 = PathArgument(),
  639. const PathArgument& a3 = PathArgument(),
  640. const PathArgument& a4 = PathArgument(),
  641. const PathArgument& a5 = PathArgument());
  642. const Value& resolve(const Value& root) const;
  643. Value resolve(const Value& root, const Value& defaultValue) const;
  644. /// Creates the "path" to access the specified node and returns a reference on
  645. /// the node.
  646. Value& make(Value& root) const;
  647. private:
  648. using InArgs = std::vector<const PathArgument*>;
  649. using Args = std::vector<PathArgument>;
  650. void makePath(const String& path, const InArgs& in);
  651. void addPathInArg(const String& path, const InArgs& in,
  652. InArgs::const_iterator& itInArg, PathArgument::Kind kind);
  653. static void invalidPath(const String& path, int location);
  654. Args args_;
  655. };
  656. /** \brief base class for Value iterators.
  657. *
  658. */
  659. class JSON_API ValueIteratorBase {
  660. public:
  661. using iterator_category = std::bidirectional_iterator_tag;
  662. using size_t = unsigned int;
  663. using difference_type = int;
  664. using SelfType = ValueIteratorBase;
  665. bool operator==(const SelfType& other) const { return isEqual(other); }
  666. bool operator!=(const SelfType& other) const { return !isEqual(other); }
  667. difference_type operator-(const SelfType& other) const {
  668. return other.computeDistance(*this);
  669. }
  670. /// Return either the index or the member name of the referenced value as a
  671. /// Value.
  672. Value key() const;
  673. /// Return the index of the referenced Value, or -1 if it is not an
  674. /// arrayValue.
  675. UInt index() const;
  676. /// Return the member name of the referenced Value, or "" if it is not an
  677. /// objectValue.
  678. /// \note Avoid `c_str()` on result, as embedded zeroes are possible.
  679. String name() const;
  680. /// Return the member name of the referenced Value. "" if it is not an
  681. /// objectValue.
  682. /// \deprecated This cannot be used for UTF-8 strings, since there can be
  683. /// embedded nulls.
  684. JSONCPP_DEPRECATED("Use `key = name();` instead.")
  685. char const* memberName() const;
  686. /// Return the member name of the referenced Value, or NULL if it is not an
  687. /// objectValue.
  688. /// \note Better version than memberName(). Allows embedded nulls.
  689. char const* memberName(char const** end) const;
  690. protected:
  691. /*! Internal utility functions to assist with implementing
  692. * other iterator functions. The const and non-const versions
  693. * of the "deref" protected methods expose the protected
  694. * current_ member variable in a way that can often be
  695. * optimized away by the compiler.
  696. */
  697. const Value& deref() const;
  698. Value& deref();
  699. void increment();
  700. void decrement();
  701. difference_type computeDistance(const SelfType& other) const;
  702. bool isEqual(const SelfType& other) const;
  703. void copy(const SelfType& other);
  704. private:
  705. Value::ObjectValues::iterator current_;
  706. // Indicates that iterator is for a null value.
  707. bool isNull_{true};
  708. public:
  709. // For some reason, BORLAND needs these at the end, rather
  710. // than earlier. No idea why.
  711. ValueIteratorBase();
  712. explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
  713. };
  714. /** \brief const iterator for object and array value.
  715. *
  716. */
  717. class JSON_API ValueConstIterator : public ValueIteratorBase {
  718. friend class Value;
  719. public:
  720. using value_type = const Value;
  721. // typedef unsigned int size_t;
  722. // typedef int difference_type;
  723. using reference = const Value&;
  724. using pointer = const Value*;
  725. using SelfType = ValueConstIterator;
  726. ValueConstIterator();
  727. ValueConstIterator(ValueIterator const& other);
  728. private:
  729. /*! \internal Use by Value to create an iterator.
  730. */
  731. explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
  732. public:
  733. SelfType& operator=(const ValueIteratorBase& other);
  734. SelfType operator++(int) {
  735. SelfType temp(*this);
  736. ++*this;
  737. return temp;
  738. }
  739. SelfType operator--(int) {
  740. SelfType temp(*this);
  741. --*this;
  742. return temp;
  743. }
  744. SelfType& operator--() {
  745. decrement();
  746. return *this;
  747. }
  748. SelfType& operator++() {
  749. increment();
  750. return *this;
  751. }
  752. reference operator*() const { return deref(); }
  753. pointer operator->() const { return &deref(); }
  754. };
  755. /** \brief Iterator for object and array value.
  756. */
  757. class JSON_API ValueIterator : public ValueIteratorBase {
  758. friend class Value;
  759. public:
  760. using value_type = Value;
  761. using size_t = unsigned int;
  762. using difference_type = int;
  763. using reference = Value&;
  764. using pointer = Value*;
  765. using SelfType = ValueIterator;
  766. ValueIterator();
  767. explicit ValueIterator(const ValueConstIterator& other);
  768. ValueIterator(const ValueIterator& other);
  769. private:
  770. /*! \internal Use by Value to create an iterator.
  771. */
  772. explicit ValueIterator(const Value::ObjectValues::iterator& current);
  773. public:
  774. SelfType& operator=(const SelfType& other);
  775. SelfType operator++(int) {
  776. SelfType temp(*this);
  777. ++*this;
  778. return temp;
  779. }
  780. SelfType operator--(int) {
  781. SelfType temp(*this);
  782. --*this;
  783. return temp;
  784. }
  785. SelfType& operator--() {
  786. decrement();
  787. return *this;
  788. }
  789. SelfType& operator++() {
  790. increment();
  791. return *this;
  792. }
  793. /*! The return value of non-const iterators can be
  794. * changed, so the these functions are not const
  795. * because the returned references/pointers can be used
  796. * to change state of the base class.
  797. */
  798. reference operator*() { return deref(); }
  799. pointer operator->() { return &deref(); }
  800. };
  801. inline void swap(Value& a, Value& b) { a.swap(b); }
  802. } // namespace Json
  803. #pragma pack(pop)
  804. #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  805. #pragma warning(pop)
  806. #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  807. #endif // JSON_H_INCLUDED