value.h 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  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_VALUE_H_INCLUDED
  6. #define JSON_VALUE_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 isMember()const, get()const,
  470. /// and operator[]const
  471. Value const* find(const String& key) const;
  472. /// Most general and efficient version of object-mutators.
  473. /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
  474. /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
  475. Value* demand(char const* begin, char const* end);
  476. /// \brief Remove and return the named member.
  477. ///
  478. /// Do nothing if it did not exist.
  479. /// \pre type() is objectValue or nullValue
  480. /// \post type() is unchanged
  481. void removeMember(const char* key);
  482. /// Same as removeMember(const char*)
  483. /// \param key may contain embedded nulls.
  484. void removeMember(const String& key);
  485. /// Same as removeMember(const char* begin, const char* end, Value* removed),
  486. /// but 'key' is null-terminated.
  487. bool removeMember(const char* key, Value* removed);
  488. /** \brief Remove the named map member.
  489. *
  490. * Update 'removed' iff removed.
  491. * \param key may contain embedded nulls.
  492. * \return true iff removed (no exceptions)
  493. */
  494. bool removeMember(String const& key, Value* removed);
  495. /// Same as removeMember(String const& key, Value* removed)
  496. bool removeMember(const char* begin, const char* end, Value* removed);
  497. /** \brief Remove the indexed array element.
  498. *
  499. * O(n) expensive operations.
  500. * Update 'removed' iff removed.
  501. * \return true if removed (no exceptions)
  502. */
  503. bool removeIndex(ArrayIndex index, Value* removed);
  504. /// Return true if the object has a member named key.
  505. /// \note 'key' must be null-terminated.
  506. bool isMember(const char* key) const;
  507. /// Return true if the object has a member named key.
  508. /// \param key may contain embedded nulls.
  509. bool isMember(const String& key) const;
  510. /// Same as isMember(String const& key)const
  511. bool isMember(const char* begin, const char* end) const;
  512. /// \brief Return a list of the member names.
  513. ///
  514. /// If null, return an empty list.
  515. /// \pre type() is objectValue or nullValue
  516. /// \post if type() was nullValue, it remains nullValue
  517. Members getMemberNames() const;
  518. /// deprecated Always pass len.
  519. JSONCPP_DEPRECATED("Use setComment(String const&) instead.")
  520. void setComment(const char* comment, CommentPlacement placement) {
  521. setComment(String(comment, strlen(comment)), placement);
  522. }
  523. /// Comments must be //... or /* ... */
  524. void setComment(const char* comment, size_t len, CommentPlacement placement) {
  525. setComment(String(comment, len), placement);
  526. }
  527. /// Comments must be //... or /* ... */
  528. void setComment(String comment, CommentPlacement placement);
  529. bool hasComment(CommentPlacement placement) const;
  530. /// Include delimiters and embedded newlines.
  531. String getComment(CommentPlacement placement) const;
  532. String toStyledString() const;
  533. const_iterator begin() const;
  534. const_iterator end() const;
  535. iterator begin();
  536. iterator end();
  537. /// \brief Returns a reference to the first element in the `Value`.
  538. /// Requires that this value holds an array or json object, with at least one
  539. /// element.
  540. const Value& front() const;
  541. /// \brief Returns a reference to the first element in the `Value`.
  542. /// Requires that this value holds an array or json object, with at least one
  543. /// element.
  544. Value& front();
  545. /// \brief Returns a reference to the last element in the `Value`.
  546. /// Requires that value holds an array or json object, with at least one
  547. /// element.
  548. const Value& back() const;
  549. /// \brief Returns a reference to the last element in the `Value`.
  550. /// Requires that this value holds an array or json object, with at least one
  551. /// element.
  552. Value& back();
  553. // Accessors for the [start, limit) range of bytes within the JSON text from
  554. // which this value was parsed, if any.
  555. void setOffsetStart(ptrdiff_t start);
  556. void setOffsetLimit(ptrdiff_t limit);
  557. ptrdiff_t getOffsetStart() const;
  558. ptrdiff_t getOffsetLimit() const;
  559. private:
  560. void setType(ValueType v) {
  561. bits_.value_type_ = static_cast<unsigned char>(v);
  562. }
  563. bool isAllocated() const { return bits_.allocated_; }
  564. void setIsAllocated(bool v) { bits_.allocated_ = v; }
  565. void initBasic(ValueType type, bool allocated = false);
  566. void dupPayload(const Value& other);
  567. void releasePayload();
  568. void dupMeta(const Value& other);
  569. Value& resolveReference(const char* key);
  570. Value& resolveReference(const char* key, const char* end);
  571. // struct MemberNamesTransform
  572. //{
  573. // typedef const char *result_type;
  574. // const char *operator()( const CZString &name ) const
  575. // {
  576. // return name.c_str();
  577. // }
  578. //};
  579. union ValueHolder {
  580. LargestInt int_;
  581. LargestUInt uint_;
  582. double real_;
  583. bool bool_;
  584. char* string_; // if allocated_, ptr to { unsigned, char[] }.
  585. ObjectValues* map_;
  586. } value_;
  587. struct {
  588. // Really a ValueType, but types should agree for bitfield packing.
  589. unsigned int value_type_ : 8;
  590. // Unless allocated_, string_ must be null-terminated.
  591. unsigned int allocated_ : 1;
  592. } bits_;
  593. class Comments {
  594. public:
  595. Comments() = default;
  596. Comments(const Comments& that);
  597. Comments(Comments&& that) noexcept;
  598. Comments& operator=(const Comments& that);
  599. Comments& operator=(Comments&& that) noexcept;
  600. bool has(CommentPlacement slot) const;
  601. String get(CommentPlacement slot) const;
  602. void set(CommentPlacement slot, String comment);
  603. private:
  604. using Array = std::array<String, numberOfCommentPlacement>;
  605. std::unique_ptr<Array> ptr_;
  606. };
  607. Comments comments_;
  608. // [start, limit) byte offsets in the source JSON text from which this Value
  609. // was extracted.
  610. ptrdiff_t start_;
  611. ptrdiff_t limit_;
  612. };
  613. template <> inline bool Value::as<bool>() const { return asBool(); }
  614. template <> inline bool Value::is<bool>() const { return isBool(); }
  615. template <> inline Int Value::as<Int>() const { return asInt(); }
  616. template <> inline bool Value::is<Int>() const { return isInt(); }
  617. template <> inline UInt Value::as<UInt>() const { return asUInt(); }
  618. template <> inline bool Value::is<UInt>() const { return isUInt(); }
  619. #if defined(JSON_HAS_INT64)
  620. template <> inline Int64 Value::as<Int64>() const { return asInt64(); }
  621. template <> inline bool Value::is<Int64>() const { return isInt64(); }
  622. template <> inline UInt64 Value::as<UInt64>() const { return asUInt64(); }
  623. template <> inline bool Value::is<UInt64>() const { return isUInt64(); }
  624. #endif
  625. template <> inline double Value::as<double>() const { return asDouble(); }
  626. template <> inline bool Value::is<double>() const { return isDouble(); }
  627. template <> inline String Value::as<String>() const { return asString(); }
  628. template <> inline bool Value::is<String>() const { return isString(); }
  629. /// These `as` specializations are type conversions, and do not have a
  630. /// corresponding `is`.
  631. template <> inline float Value::as<float>() const { return asFloat(); }
  632. template <> inline const char* Value::as<const char*>() const {
  633. return asCString();
  634. }
  635. /** \brief Experimental and untested: represents an element of the "path" to
  636. * access a node.
  637. */
  638. class JSON_API PathArgument {
  639. public:
  640. friend class Path;
  641. PathArgument();
  642. PathArgument(ArrayIndex index);
  643. PathArgument(const char* key);
  644. PathArgument(String key);
  645. private:
  646. enum Kind { kindNone = 0, kindIndex, kindKey };
  647. String key_;
  648. ArrayIndex index_{};
  649. Kind kind_{kindNone};
  650. };
  651. /** \brief Experimental and untested: represents a "path" to access a node.
  652. *
  653. * Syntax:
  654. * - "." => root node
  655. * - ".[n]" => elements at index 'n' of root node (an array value)
  656. * - ".name" => member named 'name' of root node (an object value)
  657. * - ".name1.name2.name3"
  658. * - ".[0][1][2].name1[3]"
  659. * - ".%" => member name is provided as parameter
  660. * - ".[%]" => index is provided as parameter
  661. */
  662. class JSON_API Path {
  663. public:
  664. Path(const String& path, const PathArgument& a1 = PathArgument(),
  665. const PathArgument& a2 = PathArgument(),
  666. const PathArgument& a3 = PathArgument(),
  667. const PathArgument& a4 = PathArgument(),
  668. const PathArgument& a5 = PathArgument());
  669. const Value& resolve(const Value& root) const;
  670. Value resolve(const Value& root, const Value& defaultValue) const;
  671. /// Creates the "path" to access the specified node and returns a reference on
  672. /// the node.
  673. Value& make(Value& root) const;
  674. private:
  675. using InArgs = std::vector<const PathArgument*>;
  676. using Args = std::vector<PathArgument>;
  677. void makePath(const String& path, const InArgs& in);
  678. void addPathInArg(const String& path, const InArgs& in,
  679. InArgs::const_iterator& itInArg, PathArgument::Kind kind);
  680. static void invalidPath(const String& path, int location);
  681. Args args_;
  682. };
  683. /** \brief base class for Value iterators.
  684. *
  685. */
  686. class JSON_API ValueIteratorBase {
  687. public:
  688. using iterator_category = std::bidirectional_iterator_tag;
  689. using size_t = unsigned int;
  690. using difference_type = int;
  691. using SelfType = ValueIteratorBase;
  692. bool operator==(const SelfType& other) const { return isEqual(other); }
  693. bool operator!=(const SelfType& other) const { return !isEqual(other); }
  694. difference_type operator-(const SelfType& other) const {
  695. return other.computeDistance(*this);
  696. }
  697. /// Return either the index or the member name of the referenced value as a
  698. /// Value.
  699. Value key() const;
  700. /// Return the index of the referenced Value, or -1 if it is not an
  701. /// arrayValue.
  702. UInt index() const;
  703. /// Return the member name of the referenced Value, or "" if it is not an
  704. /// objectValue.
  705. /// \note Avoid `c_str()` on result, as embedded zeroes are possible.
  706. String name() const;
  707. /// Return the member name of the referenced Value. "" if it is not an
  708. /// objectValue.
  709. /// deprecated This cannot be used for UTF-8 strings, since there can be
  710. /// embedded nulls.
  711. JSONCPP_DEPRECATED("Use `key = name();` instead.")
  712. char const* memberName() const;
  713. /// Return the member name of the referenced Value, or NULL if it is not an
  714. /// objectValue.
  715. /// \note Better version than memberName(). Allows embedded nulls.
  716. char const* memberName(char const** end) const;
  717. protected:
  718. /*! Internal utility functions to assist with implementing
  719. * other iterator functions. The const and non-const versions
  720. * of the "deref" protected methods expose the protected
  721. * current_ member variable in a way that can often be
  722. * optimized away by the compiler.
  723. */
  724. const Value& deref() const;
  725. Value& deref();
  726. void increment();
  727. void decrement();
  728. difference_type computeDistance(const SelfType& other) const;
  729. bool isEqual(const SelfType& other) const;
  730. void copy(const SelfType& other);
  731. private:
  732. Value::ObjectValues::iterator current_;
  733. // Indicates that iterator is for a null value.
  734. bool isNull_{true};
  735. public:
  736. // For some reason, BORLAND needs these at the end, rather
  737. // than earlier. No idea why.
  738. ValueIteratorBase();
  739. explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
  740. };
  741. /** \brief const iterator for object and array value.
  742. *
  743. */
  744. class JSON_API ValueConstIterator : public ValueIteratorBase {
  745. friend class Value;
  746. public:
  747. using value_type = const Value;
  748. // typedef unsigned int size_t;
  749. // typedef int difference_type;
  750. using reference = const Value&;
  751. using pointer = const Value*;
  752. using SelfType = ValueConstIterator;
  753. ValueConstIterator();
  754. ValueConstIterator(ValueIterator const& other);
  755. private:
  756. /*! internal Use by Value to create an iterator.
  757. */
  758. explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
  759. public:
  760. SelfType& operator=(const ValueIteratorBase& other);
  761. SelfType operator++(int) {
  762. SelfType temp(*this);
  763. ++*this;
  764. return temp;
  765. }
  766. SelfType operator--(int) {
  767. SelfType temp(*this);
  768. --*this;
  769. return temp;
  770. }
  771. SelfType& operator--() {
  772. decrement();
  773. return *this;
  774. }
  775. SelfType& operator++() {
  776. increment();
  777. return *this;
  778. }
  779. reference operator*() const { return deref(); }
  780. pointer operator->() const { return &deref(); }
  781. };
  782. /** \brief Iterator for object and array value.
  783. */
  784. class JSON_API ValueIterator : public ValueIteratorBase {
  785. friend class Value;
  786. public:
  787. using value_type = Value;
  788. using size_t = unsigned int;
  789. using difference_type = int;
  790. using reference = Value&;
  791. using pointer = Value*;
  792. using SelfType = ValueIterator;
  793. ValueIterator();
  794. explicit ValueIterator(const ValueConstIterator& other);
  795. ValueIterator(const ValueIterator& other);
  796. private:
  797. /*! internal Use by Value to create an iterator.
  798. */
  799. explicit ValueIterator(const Value::ObjectValues::iterator& current);
  800. public:
  801. SelfType& operator=(const SelfType& other);
  802. SelfType operator++(int) {
  803. SelfType temp(*this);
  804. ++*this;
  805. return temp;
  806. }
  807. SelfType operator--(int) {
  808. SelfType temp(*this);
  809. --*this;
  810. return temp;
  811. }
  812. SelfType& operator--() {
  813. decrement();
  814. return *this;
  815. }
  816. SelfType& operator++() {
  817. increment();
  818. return *this;
  819. }
  820. /*! The return value of non-const iterators can be
  821. * changed, so the these functions are not const
  822. * because the returned references/pointers can be used
  823. * to change state of the base class.
  824. */
  825. reference operator*() const { return const_cast<reference>(deref()); }
  826. pointer operator->() const { return const_cast<pointer>(&deref()); }
  827. };
  828. inline void swap(Value& a, Value& b) { a.swap(b); }
  829. inline const Value& Value::front() const { return *begin(); }
  830. inline Value& Value::front() { return *begin(); }
  831. inline const Value& Value::back() const { return *(--end()); }
  832. inline Value& Value::back() { return *(--end()); }
  833. } // namespace Json
  834. #if !defined(__SUNPRO_CC)
  835. #pragma pack(pop)
  836. #endif
  837. #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  838. #pragma warning(pop)
  839. #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  840. #endif // JSON_H_INCLUDED