value.h 30 KB

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