value.h 30 KB

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