json_value.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634
  1. // Copyright 2011 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. #if !defined(JSON_IS_AMALGAMATION)
  6. #include <json/assertions.h>
  7. #include <json/value.h>
  8. #include <json/writer.h>
  9. #endif // if !defined(JSON_IS_AMALGAMATION)
  10. #include <algorithm>
  11. #include <cassert>
  12. #include <cmath>
  13. #include <cstddef>
  14. #include <cstring>
  15. #include <iostream>
  16. #include <sstream>
  17. #include <utility>
  18. // Provide implementation equivalent of std::snprintf for older _MSC compilers
  19. #if defined(_MSC_VER) && _MSC_VER < 1900
  20. #include <stdarg.h>
  21. static int msvc_pre1900_c99_vsnprintf(char* outBuf, size_t size,
  22. const char* format, va_list ap) {
  23. int count = -1;
  24. if (size != 0)
  25. count = _vsnprintf_s(outBuf, size, _TRUNCATE, format, ap);
  26. if (count == -1)
  27. count = _vscprintf(format, ap);
  28. return count;
  29. }
  30. int JSON_API msvc_pre1900_c99_snprintf(char* outBuf, size_t size,
  31. const char* format, ...) {
  32. va_list ap;
  33. va_start(ap, format);
  34. const int count = msvc_pre1900_c99_vsnprintf(outBuf, size, format, ap);
  35. va_end(ap);
  36. return count;
  37. }
  38. #endif
  39. // Disable warning C4702 : unreachable code
  40. #if defined(_MSC_VER)
  41. #pragma warning(disable : 4702)
  42. #endif
  43. #define JSON_ASSERT_UNREACHABLE assert(false)
  44. namespace Json {
  45. template <typename T>
  46. static std::unique_ptr<T> cloneUnique(const std::unique_ptr<T>& p) {
  47. std::unique_ptr<T> r;
  48. if (p) {
  49. r = std::unique_ptr<T>(new T(*p));
  50. }
  51. return r;
  52. }
  53. // This is a walkaround to avoid the static initialization of Value::null.
  54. // kNull must be word-aligned to avoid crashing on ARM. We use an alignment of
  55. // 8 (instead of 4) as a bit of future-proofing.
  56. #if defined(__ARMEL__)
  57. #define ALIGNAS(byte_alignment) __attribute__((aligned(byte_alignment)))
  58. #else
  59. #define ALIGNAS(byte_alignment)
  60. #endif
  61. // static
  62. Value const& Value::nullSingleton() {
  63. static Value const nullStatic;
  64. return nullStatic;
  65. }
  66. #if JSON_USE_NULLREF
  67. // for backwards compatibility, we'll leave these global references around, but
  68. // DO NOT use them in JSONCPP library code any more!
  69. // static
  70. Value const& Value::null = Value::nullSingleton();
  71. // static
  72. Value const& Value::nullRef = Value::nullSingleton();
  73. #endif
  74. #if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
  75. template <typename T, typename U>
  76. static inline bool InRange(double d, T min, U max) {
  77. // The casts can lose precision, but we are looking only for
  78. // an approximate range. Might fail on edge cases though. ~cdunn
  79. return d >= static_cast<double>(min) && d <= static_cast<double>(max);
  80. }
  81. #else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
  82. static inline double integerToDouble(Json::UInt64 value) {
  83. return static_cast<double>(Int64(value / 2)) * 2.0 +
  84. static_cast<double>(Int64(value & 1));
  85. }
  86. template <typename T> static inline double integerToDouble(T value) {
  87. return static_cast<double>(value);
  88. }
  89. template <typename T, typename U>
  90. static inline bool InRange(double d, T min, U max) {
  91. return d >= integerToDouble(min) && d <= integerToDouble(max);
  92. }
  93. #endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
  94. /** Duplicates the specified string value.
  95. * @param value Pointer to the string to duplicate. Must be zero-terminated if
  96. * length is "unknown".
  97. * @param length Length of the value. if equals to unknown, then it will be
  98. * computed using strlen(value).
  99. * @return Pointer on the duplicate instance of string.
  100. */
  101. static inline char* duplicateStringValue(const char* value, size_t length) {
  102. // Avoid an integer overflow in the call to malloc below by limiting length
  103. // to a sane value.
  104. if (length >= static_cast<size_t>(Value::maxInt))
  105. length = Value::maxInt - 1;
  106. auto newString = static_cast<char*>(malloc(length + 1));
  107. if (newString == nullptr) {
  108. throwRuntimeError("in Json::Value::duplicateStringValue(): "
  109. "Failed to allocate string value buffer");
  110. }
  111. memcpy(newString, value, length);
  112. newString[length] = 0;
  113. return newString;
  114. }
  115. /* Record the length as a prefix.
  116. */
  117. static inline char* duplicateAndPrefixStringValue(const char* value,
  118. unsigned int length) {
  119. // Avoid an integer overflow in the call to malloc below by limiting length
  120. // to a sane value.
  121. JSON_ASSERT_MESSAGE(length <= static_cast<unsigned>(Value::maxInt) -
  122. sizeof(unsigned) - 1U,
  123. "in Json::Value::duplicateAndPrefixStringValue(): "
  124. "length too big for prefixing");
  125. size_t actualLength = sizeof(length) + length + 1;
  126. auto newString = static_cast<char*>(malloc(actualLength));
  127. if (newString == nullptr) {
  128. throwRuntimeError("in Json::Value::duplicateAndPrefixStringValue(): "
  129. "Failed to allocate string value buffer");
  130. }
  131. *reinterpret_cast<unsigned*>(newString) = length;
  132. memcpy(newString + sizeof(unsigned), value, length);
  133. newString[actualLength - 1U] =
  134. 0; // to avoid buffer over-run accidents by users later
  135. return newString;
  136. }
  137. inline static void decodePrefixedString(bool isPrefixed, char const* prefixed,
  138. unsigned* length, char const** value) {
  139. if (!isPrefixed) {
  140. *length = static_cast<unsigned>(strlen(prefixed));
  141. *value = prefixed;
  142. } else {
  143. *length = *reinterpret_cast<unsigned const*>(prefixed);
  144. *value = prefixed + sizeof(unsigned);
  145. }
  146. }
  147. /** Free the string duplicated by
  148. * duplicateStringValue()/duplicateAndPrefixStringValue().
  149. */
  150. #if JSONCPP_USING_SECURE_MEMORY
  151. static inline void releasePrefixedStringValue(char* value) {
  152. unsigned length = 0;
  153. char const* valueDecoded;
  154. decodePrefixedString(true, value, &length, &valueDecoded);
  155. size_t const size = sizeof(unsigned) + length + 1U;
  156. memset(value, 0, size);
  157. free(value);
  158. }
  159. static inline void releaseStringValue(char* value, unsigned length) {
  160. // length==0 => we allocated the strings memory
  161. size_t size = (length == 0) ? strlen(value) : length;
  162. memset(value, 0, size);
  163. free(value);
  164. }
  165. #else // !JSONCPP_USING_SECURE_MEMORY
  166. static inline void releasePrefixedStringValue(char* value) { free(value); }
  167. static inline void releaseStringValue(char* value, unsigned) { free(value); }
  168. #endif // JSONCPP_USING_SECURE_MEMORY
  169. } // namespace Json
  170. // //////////////////////////////////////////////////////////////////
  171. // //////////////////////////////////////////////////////////////////
  172. // //////////////////////////////////////////////////////////////////
  173. // ValueInternals...
  174. // //////////////////////////////////////////////////////////////////
  175. // //////////////////////////////////////////////////////////////////
  176. // //////////////////////////////////////////////////////////////////
  177. #if !defined(JSON_IS_AMALGAMATION)
  178. #include "json_valueiterator.inl"
  179. #endif // if !defined(JSON_IS_AMALGAMATION)
  180. namespace Json {
  181. #if JSON_USE_EXCEPTION
  182. Exception::Exception(String msg) : msg_(std::move(msg)) {}
  183. Exception::~Exception() noexcept = default;
  184. char const* Exception::what() const noexcept { return msg_.c_str(); }
  185. RuntimeError::RuntimeError(String const& msg) : Exception(msg) {}
  186. LogicError::LogicError(String const& msg) : Exception(msg) {}
  187. JSONCPP_NORETURN void throwRuntimeError(String const& msg) {
  188. throw RuntimeError(msg);
  189. }
  190. JSONCPP_NORETURN void throwLogicError(String const& msg) {
  191. throw LogicError(msg);
  192. }
  193. #else // !JSON_USE_EXCEPTION
  194. JSONCPP_NORETURN void throwRuntimeError(String const& msg) {
  195. std::cerr << msg << std::endl;
  196. abort();
  197. }
  198. JSONCPP_NORETURN void throwLogicError(String const& msg) {
  199. std::cerr << msg << std::endl;
  200. abort();
  201. }
  202. #endif
  203. // //////////////////////////////////////////////////////////////////
  204. // //////////////////////////////////////////////////////////////////
  205. // //////////////////////////////////////////////////////////////////
  206. // class Value::CZString
  207. // //////////////////////////////////////////////////////////////////
  208. // //////////////////////////////////////////////////////////////////
  209. // //////////////////////////////////////////////////////////////////
  210. // Notes: policy_ indicates if the string was allocated when
  211. // a string is stored.
  212. Value::CZString::CZString(ArrayIndex index) : cstr_(nullptr), index_(index) {}
  213. Value::CZString::CZString(char const* str, unsigned length,
  214. DuplicationPolicy allocate)
  215. : cstr_(str) {
  216. // allocate != duplicate
  217. storage_.policy_ = allocate & 0x3;
  218. storage_.length_ = length & 0x3FFFFFFF;
  219. }
  220. Value::CZString::CZString(const CZString& other) {
  221. cstr_ = (other.storage_.policy_ != noDuplication && other.cstr_ != nullptr
  222. ? duplicateStringValue(other.cstr_, other.storage_.length_)
  223. : other.cstr_);
  224. storage_.policy_ =
  225. static_cast<unsigned>(
  226. other.cstr_
  227. ? (static_cast<DuplicationPolicy>(other.storage_.policy_) ==
  228. noDuplication
  229. ? noDuplication
  230. : duplicate)
  231. : static_cast<DuplicationPolicy>(other.storage_.policy_)) &
  232. 3U;
  233. storage_.length_ = other.storage_.length_;
  234. }
  235. Value::CZString::CZString(CZString&& other) noexcept
  236. : cstr_(other.cstr_), index_(other.index_) {
  237. other.cstr_ = nullptr;
  238. }
  239. Value::CZString::~CZString() {
  240. if (cstr_ && storage_.policy_ == duplicate) {
  241. releaseStringValue(const_cast<char*>(cstr_),
  242. storage_.length_ + 1U); // +1 for null terminating
  243. // character for sake of
  244. // completeness but not actually
  245. // necessary
  246. }
  247. }
  248. void Value::CZString::swap(CZString& other) {
  249. std::swap(cstr_, other.cstr_);
  250. std::swap(index_, other.index_);
  251. }
  252. Value::CZString& Value::CZString::operator=(const CZString& other) {
  253. cstr_ = other.cstr_;
  254. index_ = other.index_;
  255. return *this;
  256. }
  257. Value::CZString& Value::CZString::operator=(CZString&& other) noexcept {
  258. cstr_ = other.cstr_;
  259. index_ = other.index_;
  260. other.cstr_ = nullptr;
  261. return *this;
  262. }
  263. bool Value::CZString::operator<(const CZString& other) const {
  264. if (!cstr_)
  265. return index_ < other.index_;
  266. // return strcmp(cstr_, other.cstr_) < 0;
  267. // Assume both are strings.
  268. unsigned this_len = this->storage_.length_;
  269. unsigned other_len = other.storage_.length_;
  270. unsigned min_len = std::min<unsigned>(this_len, other_len);
  271. JSON_ASSERT(this->cstr_ && other.cstr_);
  272. int comp = memcmp(this->cstr_, other.cstr_, min_len);
  273. if (comp < 0)
  274. return true;
  275. if (comp > 0)
  276. return false;
  277. return (this_len < other_len);
  278. }
  279. bool Value::CZString::operator==(const CZString& other) const {
  280. if (!cstr_)
  281. return index_ == other.index_;
  282. // return strcmp(cstr_, other.cstr_) == 0;
  283. // Assume both are strings.
  284. unsigned this_len = this->storage_.length_;
  285. unsigned other_len = other.storage_.length_;
  286. if (this_len != other_len)
  287. return false;
  288. JSON_ASSERT(this->cstr_ && other.cstr_);
  289. int comp = memcmp(this->cstr_, other.cstr_, this_len);
  290. return comp == 0;
  291. }
  292. ArrayIndex Value::CZString::index() const { return index_; }
  293. // const char* Value::CZString::c_str() const { return cstr_; }
  294. const char* Value::CZString::data() const { return cstr_; }
  295. unsigned Value::CZString::length() const { return storage_.length_; }
  296. bool Value::CZString::isStaticString() const {
  297. return storage_.policy_ == noDuplication;
  298. }
  299. // //////////////////////////////////////////////////////////////////
  300. // //////////////////////////////////////////////////////////////////
  301. // //////////////////////////////////////////////////////////////////
  302. // class Value::Value
  303. // //////////////////////////////////////////////////////////////////
  304. // //////////////////////////////////////////////////////////////////
  305. // //////////////////////////////////////////////////////////////////
  306. /*! \internal Default constructor initialization must be equivalent to:
  307. * memset( this, 0, sizeof(Value) )
  308. * This optimization is used in ValueInternalMap fast allocator.
  309. */
  310. Value::Value(ValueType type) {
  311. static char const emptyString[] = "";
  312. initBasic(type);
  313. switch (type) {
  314. case nullValue:
  315. break;
  316. case intValue:
  317. case uintValue:
  318. value_.int_ = 0;
  319. break;
  320. case realValue:
  321. value_.real_ = 0.0;
  322. break;
  323. case stringValue:
  324. // allocated_ == false, so this is safe.
  325. value_.string_ = const_cast<char*>(static_cast<char const*>(emptyString));
  326. break;
  327. case arrayValue:
  328. case objectValue:
  329. value_.map_ = new ObjectValues();
  330. break;
  331. case booleanValue:
  332. value_.bool_ = false;
  333. break;
  334. default:
  335. JSON_ASSERT_UNREACHABLE;
  336. }
  337. }
  338. Value::Value(Int value) {
  339. initBasic(intValue);
  340. value_.int_ = value;
  341. }
  342. Value::Value(UInt value) {
  343. initBasic(uintValue);
  344. value_.uint_ = value;
  345. }
  346. #if defined(JSON_HAS_INT64)
  347. Value::Value(Int64 value) {
  348. initBasic(intValue);
  349. value_.int_ = value;
  350. }
  351. Value::Value(UInt64 value) {
  352. initBasic(uintValue);
  353. value_.uint_ = value;
  354. }
  355. #endif // defined(JSON_HAS_INT64)
  356. Value::Value(double value) {
  357. initBasic(realValue);
  358. value_.real_ = value;
  359. }
  360. Value::Value(const char* value) {
  361. initBasic(stringValue, true);
  362. JSON_ASSERT_MESSAGE(value != nullptr,
  363. "Null Value Passed to Value Constructor");
  364. value_.string_ = duplicateAndPrefixStringValue(
  365. value, static_cast<unsigned>(strlen(value)));
  366. }
  367. Value::Value(const char* begin, const char* end) {
  368. initBasic(stringValue, true);
  369. value_.string_ =
  370. duplicateAndPrefixStringValue(begin, static_cast<unsigned>(end - begin));
  371. }
  372. Value::Value(const String& value) {
  373. initBasic(stringValue, true);
  374. value_.string_ = duplicateAndPrefixStringValue(
  375. value.data(), static_cast<unsigned>(value.length()));
  376. }
  377. Value::Value(const StaticString& value) {
  378. initBasic(stringValue);
  379. value_.string_ = const_cast<char*>(value.c_str());
  380. }
  381. Value::Value(bool value) {
  382. initBasic(booleanValue);
  383. value_.bool_ = value;
  384. }
  385. Value::Value(const Value& other) {
  386. dupPayload(other);
  387. dupMeta(other);
  388. }
  389. Value::Value(Value&& other) noexcept {
  390. initBasic(nullValue);
  391. swap(other);
  392. }
  393. Value::~Value() {
  394. releasePayload();
  395. value_.uint_ = 0;
  396. }
  397. Value& Value::operator=(const Value& other) {
  398. Value(other).swap(*this);
  399. return *this;
  400. }
  401. Value& Value::operator=(Value&& other) noexcept {
  402. other.swap(*this);
  403. return *this;
  404. }
  405. void Value::swapPayload(Value& other) {
  406. std::swap(bits_, other.bits_);
  407. std::swap(value_, other.value_);
  408. }
  409. void Value::copyPayload(const Value& other) {
  410. releasePayload();
  411. dupPayload(other);
  412. }
  413. void Value::swap(Value& other) {
  414. swapPayload(other);
  415. std::swap(comments_, other.comments_);
  416. std::swap(start_, other.start_);
  417. std::swap(limit_, other.limit_);
  418. }
  419. void Value::copy(const Value& other) {
  420. copyPayload(other);
  421. dupMeta(other);
  422. }
  423. ValueType Value::type() const {
  424. return static_cast<ValueType>(bits_.value_type_);
  425. }
  426. int Value::compare(const Value& other) const {
  427. if (*this < other)
  428. return -1;
  429. if (*this > other)
  430. return 1;
  431. return 0;
  432. }
  433. bool Value::operator<(const Value& other) const {
  434. int typeDelta = type() - other.type();
  435. if (typeDelta)
  436. return typeDelta < 0;
  437. switch (type()) {
  438. case nullValue:
  439. return false;
  440. case intValue:
  441. return value_.int_ < other.value_.int_;
  442. case uintValue:
  443. return value_.uint_ < other.value_.uint_;
  444. case realValue:
  445. return value_.real_ < other.value_.real_;
  446. case booleanValue:
  447. return value_.bool_ < other.value_.bool_;
  448. case stringValue: {
  449. if ((value_.string_ == nullptr) || (other.value_.string_ == nullptr)) {
  450. return other.value_.string_ != nullptr;
  451. }
  452. unsigned this_len;
  453. unsigned other_len;
  454. char const* this_str;
  455. char const* other_str;
  456. decodePrefixedString(this->isAllocated(), this->value_.string_, &this_len,
  457. &this_str);
  458. decodePrefixedString(other.isAllocated(), other.value_.string_, &other_len,
  459. &other_str);
  460. unsigned min_len = std::min<unsigned>(this_len, other_len);
  461. JSON_ASSERT(this_str && other_str);
  462. int comp = memcmp(this_str, other_str, min_len);
  463. if (comp < 0)
  464. return true;
  465. if (comp > 0)
  466. return false;
  467. return (this_len < other_len);
  468. }
  469. case arrayValue:
  470. case objectValue: {
  471. auto thisSize = value_.map_->size();
  472. auto otherSize = other.value_.map_->size();
  473. if (thisSize != otherSize)
  474. return thisSize < otherSize;
  475. return (*value_.map_) < (*other.value_.map_);
  476. }
  477. default:
  478. JSON_ASSERT_UNREACHABLE;
  479. }
  480. return false; // unreachable
  481. }
  482. bool Value::operator<=(const Value& other) const { return !(other < *this); }
  483. bool Value::operator>=(const Value& other) const { return !(*this < other); }
  484. bool Value::operator>(const Value& other) const { return other < *this; }
  485. bool Value::operator==(const Value& other) const {
  486. if (type() != other.type())
  487. return false;
  488. switch (type()) {
  489. case nullValue:
  490. return true;
  491. case intValue:
  492. return value_.int_ == other.value_.int_;
  493. case uintValue:
  494. return value_.uint_ == other.value_.uint_;
  495. case realValue:
  496. return value_.real_ == other.value_.real_;
  497. case booleanValue:
  498. return value_.bool_ == other.value_.bool_;
  499. case stringValue: {
  500. if ((value_.string_ == nullptr) || (other.value_.string_ == nullptr)) {
  501. return (value_.string_ == other.value_.string_);
  502. }
  503. unsigned this_len;
  504. unsigned other_len;
  505. char const* this_str;
  506. char const* other_str;
  507. decodePrefixedString(this->isAllocated(), this->value_.string_, &this_len,
  508. &this_str);
  509. decodePrefixedString(other.isAllocated(), other.value_.string_, &other_len,
  510. &other_str);
  511. if (this_len != other_len)
  512. return false;
  513. JSON_ASSERT(this_str && other_str);
  514. int comp = memcmp(this_str, other_str, this_len);
  515. return comp == 0;
  516. }
  517. case arrayValue:
  518. case objectValue:
  519. return value_.map_->size() == other.value_.map_->size() &&
  520. (*value_.map_) == (*other.value_.map_);
  521. default:
  522. JSON_ASSERT_UNREACHABLE;
  523. }
  524. return false; // unreachable
  525. }
  526. bool Value::operator!=(const Value& other) const { return !(*this == other); }
  527. const char* Value::asCString() const {
  528. JSON_ASSERT_MESSAGE(type() == stringValue,
  529. "in Json::Value::asCString(): requires stringValue");
  530. if (value_.string_ == nullptr)
  531. return nullptr;
  532. unsigned this_len;
  533. char const* this_str;
  534. decodePrefixedString(this->isAllocated(), this->value_.string_, &this_len,
  535. &this_str);
  536. return this_str;
  537. }
  538. #if JSONCPP_USING_SECURE_MEMORY
  539. unsigned Value::getCStringLength() const {
  540. JSON_ASSERT_MESSAGE(type() == stringValue,
  541. "in Json::Value::asCString(): requires stringValue");
  542. if (value_.string_ == 0)
  543. return 0;
  544. unsigned this_len;
  545. char const* this_str;
  546. decodePrefixedString(this->isAllocated(), this->value_.string_, &this_len,
  547. &this_str);
  548. return this_len;
  549. }
  550. #endif
  551. bool Value::getString(char const** begin, char const** end) const {
  552. if (type() != stringValue)
  553. return false;
  554. if (value_.string_ == nullptr)
  555. return false;
  556. unsigned length;
  557. decodePrefixedString(this->isAllocated(), this->value_.string_, &length,
  558. begin);
  559. *end = *begin + length;
  560. return true;
  561. }
  562. String Value::asString() const {
  563. switch (type()) {
  564. case nullValue:
  565. return "";
  566. case stringValue: {
  567. if (value_.string_ == nullptr)
  568. return "";
  569. unsigned this_len;
  570. char const* this_str;
  571. decodePrefixedString(this->isAllocated(), this->value_.string_, &this_len,
  572. &this_str);
  573. return String(this_str, this_len);
  574. }
  575. case booleanValue:
  576. return value_.bool_ ? "true" : "false";
  577. case intValue:
  578. return valueToString(value_.int_);
  579. case uintValue:
  580. return valueToString(value_.uint_);
  581. case realValue:
  582. return valueToString(value_.real_);
  583. default:
  584. JSON_FAIL_MESSAGE("Type is not convertible to string");
  585. }
  586. }
  587. Value::Int Value::asInt() const {
  588. switch (type()) {
  589. case intValue:
  590. JSON_ASSERT_MESSAGE(isInt(), "LargestInt out of Int range");
  591. return Int(value_.int_);
  592. case uintValue:
  593. JSON_ASSERT_MESSAGE(isInt(), "LargestUInt out of Int range");
  594. return Int(value_.uint_);
  595. case realValue:
  596. JSON_ASSERT_MESSAGE(InRange(value_.real_, minInt, maxInt),
  597. "double out of Int range");
  598. return Int(value_.real_);
  599. case nullValue:
  600. return 0;
  601. case booleanValue:
  602. return value_.bool_ ? 1 : 0;
  603. default:
  604. break;
  605. }
  606. JSON_FAIL_MESSAGE("Value is not convertible to Int.");
  607. }
  608. Value::UInt Value::asUInt() const {
  609. switch (type()) {
  610. case intValue:
  611. JSON_ASSERT_MESSAGE(isUInt(), "LargestInt out of UInt range");
  612. return UInt(value_.int_);
  613. case uintValue:
  614. JSON_ASSERT_MESSAGE(isUInt(), "LargestUInt out of UInt range");
  615. return UInt(value_.uint_);
  616. case realValue:
  617. JSON_ASSERT_MESSAGE(InRange(value_.real_, 0, maxUInt),
  618. "double out of UInt range");
  619. return UInt(value_.real_);
  620. case nullValue:
  621. return 0;
  622. case booleanValue:
  623. return value_.bool_ ? 1 : 0;
  624. default:
  625. break;
  626. }
  627. JSON_FAIL_MESSAGE("Value is not convertible to UInt.");
  628. }
  629. #if defined(JSON_HAS_INT64)
  630. Value::Int64 Value::asInt64() const {
  631. switch (type()) {
  632. case intValue:
  633. return Int64(value_.int_);
  634. case uintValue:
  635. JSON_ASSERT_MESSAGE(isInt64(), "LargestUInt out of Int64 range");
  636. return Int64(value_.uint_);
  637. case realValue:
  638. JSON_ASSERT_MESSAGE(InRange(value_.real_, minInt64, maxInt64),
  639. "double out of Int64 range");
  640. return Int64(value_.real_);
  641. case nullValue:
  642. return 0;
  643. case booleanValue:
  644. return value_.bool_ ? 1 : 0;
  645. default:
  646. break;
  647. }
  648. JSON_FAIL_MESSAGE("Value is not convertible to Int64.");
  649. }
  650. Value::UInt64 Value::asUInt64() const {
  651. switch (type()) {
  652. case intValue:
  653. JSON_ASSERT_MESSAGE(isUInt64(), "LargestInt out of UInt64 range");
  654. return UInt64(value_.int_);
  655. case uintValue:
  656. return UInt64(value_.uint_);
  657. case realValue:
  658. JSON_ASSERT_MESSAGE(InRange(value_.real_, 0, maxUInt64),
  659. "double out of UInt64 range");
  660. return UInt64(value_.real_);
  661. case nullValue:
  662. return 0;
  663. case booleanValue:
  664. return value_.bool_ ? 1 : 0;
  665. default:
  666. break;
  667. }
  668. JSON_FAIL_MESSAGE("Value is not convertible to UInt64.");
  669. }
  670. #endif // if defined(JSON_HAS_INT64)
  671. LargestInt Value::asLargestInt() const {
  672. #if defined(JSON_NO_INT64)
  673. return asInt();
  674. #else
  675. return asInt64();
  676. #endif
  677. }
  678. LargestUInt Value::asLargestUInt() const {
  679. #if defined(JSON_NO_INT64)
  680. return asUInt();
  681. #else
  682. return asUInt64();
  683. #endif
  684. }
  685. double Value::asDouble() const {
  686. switch (type()) {
  687. case intValue:
  688. return static_cast<double>(value_.int_);
  689. case uintValue:
  690. #if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
  691. return static_cast<double>(value_.uint_);
  692. #else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
  693. return integerToDouble(value_.uint_);
  694. #endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
  695. case realValue:
  696. return value_.real_;
  697. case nullValue:
  698. return 0.0;
  699. case booleanValue:
  700. return value_.bool_ ? 1.0 : 0.0;
  701. default:
  702. break;
  703. }
  704. JSON_FAIL_MESSAGE("Value is not convertible to double.");
  705. }
  706. float Value::asFloat() const {
  707. switch (type()) {
  708. case intValue:
  709. return static_cast<float>(value_.int_);
  710. case uintValue:
  711. #if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
  712. return static_cast<float>(value_.uint_);
  713. #else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
  714. // This can fail (silently?) if the value is bigger than MAX_FLOAT.
  715. return static_cast<float>(integerToDouble(value_.uint_));
  716. #endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
  717. case realValue:
  718. return static_cast<float>(value_.real_);
  719. case nullValue:
  720. return 0.0;
  721. case booleanValue:
  722. return value_.bool_ ? 1.0F : 0.0F;
  723. default:
  724. break;
  725. }
  726. JSON_FAIL_MESSAGE("Value is not convertible to float.");
  727. }
  728. bool Value::asBool() const {
  729. switch (type()) {
  730. case booleanValue:
  731. return value_.bool_;
  732. case nullValue:
  733. return false;
  734. case intValue:
  735. return value_.int_ != 0;
  736. case uintValue:
  737. return value_.uint_ != 0;
  738. case realValue: {
  739. // According to JavaScript language zero or NaN is regarded as false
  740. const auto value_classification = std::fpclassify(value_.real_);
  741. return value_classification != FP_ZERO && value_classification != FP_NAN;
  742. }
  743. default:
  744. break;
  745. }
  746. JSON_FAIL_MESSAGE("Value is not convertible to bool.");
  747. }
  748. bool Value::isConvertibleTo(ValueType other) const {
  749. switch (other) {
  750. case nullValue:
  751. return (isNumeric() && asDouble() == 0.0) ||
  752. (type() == booleanValue && !value_.bool_) ||
  753. (type() == stringValue && asString().empty()) ||
  754. (type() == arrayValue && value_.map_->empty()) ||
  755. (type() == objectValue && value_.map_->empty()) ||
  756. type() == nullValue;
  757. case intValue:
  758. return isInt() ||
  759. (type() == realValue && InRange(value_.real_, minInt, maxInt)) ||
  760. type() == booleanValue || type() == nullValue;
  761. case uintValue:
  762. return isUInt() ||
  763. (type() == realValue && InRange(value_.real_, 0, maxUInt)) ||
  764. type() == booleanValue || type() == nullValue;
  765. case realValue:
  766. return isNumeric() || type() == booleanValue || type() == nullValue;
  767. case booleanValue:
  768. return isNumeric() || type() == booleanValue || type() == nullValue;
  769. case stringValue:
  770. return isNumeric() || type() == booleanValue || type() == stringValue ||
  771. type() == nullValue;
  772. case arrayValue:
  773. return type() == arrayValue || type() == nullValue;
  774. case objectValue:
  775. return type() == objectValue || type() == nullValue;
  776. }
  777. JSON_ASSERT_UNREACHABLE;
  778. return false;
  779. }
  780. /// Number of values in array or object
  781. ArrayIndex Value::size() const {
  782. switch (type()) {
  783. case nullValue:
  784. case intValue:
  785. case uintValue:
  786. case realValue:
  787. case booleanValue:
  788. case stringValue:
  789. return 0;
  790. case arrayValue: // size of the array is highest index + 1
  791. if (!value_.map_->empty()) {
  792. ObjectValues::const_iterator itLast = value_.map_->end();
  793. --itLast;
  794. return (*itLast).first.index() + 1;
  795. }
  796. return 0;
  797. case objectValue:
  798. return ArrayIndex(value_.map_->size());
  799. }
  800. JSON_ASSERT_UNREACHABLE;
  801. return 0; // unreachable;
  802. }
  803. bool Value::empty() const {
  804. if (isNull() || isArray() || isObject())
  805. return size() == 0U;
  806. return false;
  807. }
  808. Value::operator bool() const { return !isNull(); }
  809. void Value::clear() {
  810. JSON_ASSERT_MESSAGE(type() == nullValue || type() == arrayValue ||
  811. type() == objectValue,
  812. "in Json::Value::clear(): requires complex value");
  813. start_ = 0;
  814. limit_ = 0;
  815. switch (type()) {
  816. case arrayValue:
  817. case objectValue:
  818. value_.map_->clear();
  819. break;
  820. default:
  821. break;
  822. }
  823. }
  824. void Value::resize(ArrayIndex newSize) {
  825. JSON_ASSERT_MESSAGE(type() == nullValue || type() == arrayValue,
  826. "in Json::Value::resize(): requires arrayValue");
  827. if (type() == nullValue)
  828. *this = Value(arrayValue);
  829. ArrayIndex oldSize = size();
  830. if (newSize == 0)
  831. clear();
  832. else if (newSize > oldSize)
  833. for (ArrayIndex i = oldSize; i < newSize; ++i)
  834. (*this)[i];
  835. else {
  836. for (ArrayIndex index = newSize; index < oldSize; ++index) {
  837. value_.map_->erase(index);
  838. }
  839. JSON_ASSERT(size() == newSize);
  840. }
  841. }
  842. Value& Value::operator[](ArrayIndex index) {
  843. JSON_ASSERT_MESSAGE(
  844. type() == nullValue || type() == arrayValue,
  845. "in Json::Value::operator[](ArrayIndex): requires arrayValue");
  846. if (type() == nullValue)
  847. *this = Value(arrayValue);
  848. CZString key(index);
  849. auto it = value_.map_->lower_bound(key);
  850. if (it != value_.map_->end() && (*it).first == key)
  851. return (*it).second;
  852. ObjectValues::value_type defaultValue(key, nullSingleton());
  853. it = value_.map_->insert(it, defaultValue);
  854. return (*it).second;
  855. }
  856. Value& Value::operator[](int index) {
  857. JSON_ASSERT_MESSAGE(
  858. index >= 0,
  859. "in Json::Value::operator[](int index): index cannot be negative");
  860. return (*this)[ArrayIndex(index)];
  861. }
  862. const Value& Value::operator[](ArrayIndex index) const {
  863. JSON_ASSERT_MESSAGE(
  864. type() == nullValue || type() == arrayValue,
  865. "in Json::Value::operator[](ArrayIndex)const: requires arrayValue");
  866. if (type() == nullValue)
  867. return nullSingleton();
  868. CZString key(index);
  869. ObjectValues::const_iterator it = value_.map_->find(key);
  870. if (it == value_.map_->end())
  871. return nullSingleton();
  872. return (*it).second;
  873. }
  874. const Value& Value::operator[](int index) const {
  875. JSON_ASSERT_MESSAGE(
  876. index >= 0,
  877. "in Json::Value::operator[](int index) const: index cannot be negative");
  878. return (*this)[ArrayIndex(index)];
  879. }
  880. void Value::initBasic(ValueType type, bool allocated) {
  881. setType(type);
  882. setIsAllocated(allocated);
  883. comments_ = Comments{};
  884. start_ = 0;
  885. limit_ = 0;
  886. }
  887. void Value::dupPayload(const Value& other) {
  888. setType(other.type());
  889. setIsAllocated(false);
  890. switch (type()) {
  891. case nullValue:
  892. case intValue:
  893. case uintValue:
  894. case realValue:
  895. case booleanValue:
  896. value_ = other.value_;
  897. break;
  898. case stringValue:
  899. if (other.value_.string_ && other.isAllocated()) {
  900. unsigned len;
  901. char const* str;
  902. decodePrefixedString(other.isAllocated(), other.value_.string_, &len,
  903. &str);
  904. value_.string_ = duplicateAndPrefixStringValue(str, len);
  905. setIsAllocated(true);
  906. } else {
  907. value_.string_ = other.value_.string_;
  908. }
  909. break;
  910. case arrayValue:
  911. case objectValue:
  912. value_.map_ = new ObjectValues(*other.value_.map_);
  913. break;
  914. default:
  915. JSON_ASSERT_UNREACHABLE;
  916. }
  917. }
  918. void Value::releasePayload() {
  919. switch (type()) {
  920. case nullValue:
  921. case intValue:
  922. case uintValue:
  923. case realValue:
  924. case booleanValue:
  925. break;
  926. case stringValue:
  927. if (isAllocated())
  928. releasePrefixedStringValue(value_.string_);
  929. break;
  930. case arrayValue:
  931. case objectValue:
  932. delete value_.map_;
  933. break;
  934. default:
  935. JSON_ASSERT_UNREACHABLE;
  936. }
  937. }
  938. void Value::dupMeta(const Value& other) {
  939. comments_ = other.comments_;
  940. start_ = other.start_;
  941. limit_ = other.limit_;
  942. }
  943. // Access an object value by name, create a null member if it does not exist.
  944. // @pre Type of '*this' is object or null.
  945. // @param key is null-terminated.
  946. Value& Value::resolveReference(const char* key) {
  947. JSON_ASSERT_MESSAGE(
  948. type() == nullValue || type() == objectValue,
  949. "in Json::Value::resolveReference(): requires objectValue");
  950. if (type() == nullValue)
  951. *this = Value(objectValue);
  952. CZString actualKey(key, static_cast<unsigned>(strlen(key)),
  953. CZString::noDuplication); // NOTE!
  954. auto it = value_.map_->lower_bound(actualKey);
  955. if (it != value_.map_->end() && (*it).first == actualKey)
  956. return (*it).second;
  957. ObjectValues::value_type defaultValue(actualKey, nullSingleton());
  958. it = value_.map_->insert(it, defaultValue);
  959. Value& value = (*it).second;
  960. return value;
  961. }
  962. // @param key is not null-terminated.
  963. Value& Value::resolveReference(char const* key, char const* end) {
  964. JSON_ASSERT_MESSAGE(
  965. type() == nullValue || type() == objectValue,
  966. "in Json::Value::resolveReference(key, end): requires objectValue");
  967. if (type() == nullValue)
  968. *this = Value(objectValue);
  969. CZString actualKey(key, static_cast<unsigned>(end - key),
  970. CZString::duplicateOnCopy);
  971. auto it = value_.map_->lower_bound(actualKey);
  972. if (it != value_.map_->end() && (*it).first == actualKey)
  973. return (*it).second;
  974. ObjectValues::value_type defaultValue(actualKey, nullSingleton());
  975. it = value_.map_->insert(it, defaultValue);
  976. Value& value = (*it).second;
  977. return value;
  978. }
  979. Value Value::get(ArrayIndex index, const Value& defaultValue) const {
  980. const Value* value = &((*this)[index]);
  981. return value == &nullSingleton() ? defaultValue : *value;
  982. }
  983. bool Value::isValidIndex(ArrayIndex index) const { return index < size(); }
  984. Value const* Value::find(char const* begin, char const* end) const {
  985. JSON_ASSERT_MESSAGE(type() == nullValue || type() == objectValue,
  986. "in Json::Value::find(begin, end): requires "
  987. "objectValue or nullValue");
  988. if (type() == nullValue)
  989. return nullptr;
  990. CZString actualKey(begin, static_cast<unsigned>(end - begin),
  991. CZString::noDuplication);
  992. ObjectValues::const_iterator it = value_.map_->find(actualKey);
  993. if (it == value_.map_->end())
  994. return nullptr;
  995. return &(*it).second;
  996. }
  997. Value* Value::demand(char const* begin, char const* end) {
  998. JSON_ASSERT_MESSAGE(type() == nullValue || type() == objectValue,
  999. "in Json::Value::demand(begin, end): requires "
  1000. "objectValue or nullValue");
  1001. return &resolveReference(begin, end);
  1002. }
  1003. const Value& Value::operator[](const char* key) const {
  1004. Value const* found = find(key, key + strlen(key));
  1005. if (!found)
  1006. return nullSingleton();
  1007. return *found;
  1008. }
  1009. Value const& Value::operator[](const String& key) const {
  1010. Value const* found = find(key.data(), key.data() + key.length());
  1011. if (!found)
  1012. return nullSingleton();
  1013. return *found;
  1014. }
  1015. Value& Value::operator[](const char* key) {
  1016. return resolveReference(key, key + strlen(key));
  1017. }
  1018. Value& Value::operator[](const String& key) {
  1019. return resolveReference(key.data(), key.data() + key.length());
  1020. }
  1021. Value& Value::operator[](const StaticString& key) {
  1022. return resolveReference(key.c_str());
  1023. }
  1024. Value& Value::append(const Value& value) { return append(Value(value)); }
  1025. Value& Value::append(Value&& value) {
  1026. JSON_ASSERT_MESSAGE(type() == nullValue || type() == arrayValue,
  1027. "in Json::Value::append: requires arrayValue");
  1028. if (type() == nullValue) {
  1029. *this = Value(arrayValue);
  1030. }
  1031. return this->value_.map_->emplace(size(), std::move(value)).first->second;
  1032. }
  1033. bool Value::insert(ArrayIndex index, const Value& newValue) {
  1034. return insert(index, Value(newValue));
  1035. }
  1036. bool Value::insert(ArrayIndex index, Value&& newValue) {
  1037. JSON_ASSERT_MESSAGE(type() == nullValue || type() == arrayValue,
  1038. "in Json::Value::insert: requires arrayValue");
  1039. ArrayIndex length = size();
  1040. if (index > length) {
  1041. return false;
  1042. }
  1043. for (ArrayIndex i = length; i > index; i--) {
  1044. (*this)[i] = std::move((*this)[i - 1]);
  1045. }
  1046. (*this)[index] = std::move(newValue);
  1047. return true;
  1048. }
  1049. Value Value::get(char const* begin, char const* end,
  1050. Value const& defaultValue) const {
  1051. Value const* found = find(begin, end);
  1052. return !found ? defaultValue : *found;
  1053. }
  1054. Value Value::get(char const* key, Value const& defaultValue) const {
  1055. return get(key, key + strlen(key), defaultValue);
  1056. }
  1057. Value Value::get(String const& key, Value const& defaultValue) const {
  1058. return get(key.data(), key.data() + key.length(), defaultValue);
  1059. }
  1060. bool Value::removeMember(const char* begin, const char* end, Value* removed) {
  1061. if (type() != objectValue) {
  1062. return false;
  1063. }
  1064. CZString actualKey(begin, static_cast<unsigned>(end - begin),
  1065. CZString::noDuplication);
  1066. auto it = value_.map_->find(actualKey);
  1067. if (it == value_.map_->end())
  1068. return false;
  1069. if (removed)
  1070. *removed = std::move(it->second);
  1071. value_.map_->erase(it);
  1072. return true;
  1073. }
  1074. bool Value::removeMember(const char* key, Value* removed) {
  1075. return removeMember(key, key + strlen(key), removed);
  1076. }
  1077. bool Value::removeMember(String const& key, Value* removed) {
  1078. return removeMember(key.data(), key.data() + key.length(), removed);
  1079. }
  1080. void Value::removeMember(const char* key) {
  1081. JSON_ASSERT_MESSAGE(type() == nullValue || type() == objectValue,
  1082. "in Json::Value::removeMember(): requires objectValue");
  1083. if (type() == nullValue)
  1084. return;
  1085. CZString actualKey(key, unsigned(strlen(key)), CZString::noDuplication);
  1086. value_.map_->erase(actualKey);
  1087. }
  1088. void Value::removeMember(const String& key) { removeMember(key.c_str()); }
  1089. bool Value::removeIndex(ArrayIndex index, Value* removed) {
  1090. if (type() != arrayValue) {
  1091. return false;
  1092. }
  1093. CZString key(index);
  1094. auto it = value_.map_->find(key);
  1095. if (it == value_.map_->end()) {
  1096. return false;
  1097. }
  1098. if (removed)
  1099. *removed = it->second;
  1100. ArrayIndex oldSize = size();
  1101. // shift left all items left, into the place of the "removed"
  1102. for (ArrayIndex i = index; i < (oldSize - 1); ++i) {
  1103. CZString keey(i);
  1104. (*value_.map_)[keey] = (*this)[i + 1];
  1105. }
  1106. // erase the last one ("leftover")
  1107. CZString keyLast(oldSize - 1);
  1108. auto itLast = value_.map_->find(keyLast);
  1109. value_.map_->erase(itLast);
  1110. return true;
  1111. }
  1112. bool Value::isMember(char const* begin, char const* end) const {
  1113. Value const* value = find(begin, end);
  1114. return nullptr != value;
  1115. }
  1116. bool Value::isMember(char const* key) const {
  1117. return isMember(key, key + strlen(key));
  1118. }
  1119. bool Value::isMember(String const& key) const {
  1120. return isMember(key.data(), key.data() + key.length());
  1121. }
  1122. Value::Members Value::getMemberNames() const {
  1123. JSON_ASSERT_MESSAGE(
  1124. type() == nullValue || type() == objectValue,
  1125. "in Json::Value::getMemberNames(), value must be objectValue");
  1126. if (type() == nullValue)
  1127. return Value::Members();
  1128. Members members;
  1129. members.reserve(value_.map_->size());
  1130. ObjectValues::const_iterator it = value_.map_->begin();
  1131. ObjectValues::const_iterator itEnd = value_.map_->end();
  1132. for (; it != itEnd; ++it) {
  1133. members.push_back(String((*it).first.data(), (*it).first.length()));
  1134. }
  1135. return members;
  1136. }
  1137. static bool IsIntegral(double d) {
  1138. double integral_part;
  1139. return modf(d, &integral_part) == 0.0;
  1140. }
  1141. bool Value::isNull() const { return type() == nullValue; }
  1142. bool Value::isBool() const { return type() == booleanValue; }
  1143. bool Value::isInt() const {
  1144. switch (type()) {
  1145. case intValue:
  1146. #if defined(JSON_HAS_INT64)
  1147. return value_.int_ >= minInt && value_.int_ <= maxInt;
  1148. #else
  1149. return true;
  1150. #endif
  1151. case uintValue:
  1152. return value_.uint_ <= UInt(maxInt);
  1153. case realValue:
  1154. return value_.real_ >= minInt && value_.real_ <= maxInt &&
  1155. IsIntegral(value_.real_);
  1156. default:
  1157. break;
  1158. }
  1159. return false;
  1160. }
  1161. bool Value::isUInt() const {
  1162. switch (type()) {
  1163. case intValue:
  1164. #if defined(JSON_HAS_INT64)
  1165. return value_.int_ >= 0 && LargestUInt(value_.int_) <= LargestUInt(maxUInt);
  1166. #else
  1167. return value_.int_ >= 0;
  1168. #endif
  1169. case uintValue:
  1170. #if defined(JSON_HAS_INT64)
  1171. return value_.uint_ <= maxUInt;
  1172. #else
  1173. return true;
  1174. #endif
  1175. case realValue:
  1176. return value_.real_ >= 0 && value_.real_ <= maxUInt &&
  1177. IsIntegral(value_.real_);
  1178. default:
  1179. break;
  1180. }
  1181. return false;
  1182. }
  1183. bool Value::isInt64() const {
  1184. #if defined(JSON_HAS_INT64)
  1185. switch (type()) {
  1186. case intValue:
  1187. return true;
  1188. case uintValue:
  1189. return value_.uint_ <= UInt64(maxInt64);
  1190. case realValue:
  1191. // Note that maxInt64 (= 2^63 - 1) is not exactly representable as a
  1192. // double, so double(maxInt64) will be rounded up to 2^63. Therefore we
  1193. // require the value to be strictly less than the limit.
  1194. return value_.real_ >= double(minInt64) &&
  1195. value_.real_ < double(maxInt64) && IsIntegral(value_.real_);
  1196. default:
  1197. break;
  1198. }
  1199. #endif // JSON_HAS_INT64
  1200. return false;
  1201. }
  1202. bool Value::isUInt64() const {
  1203. #if defined(JSON_HAS_INT64)
  1204. switch (type()) {
  1205. case intValue:
  1206. return value_.int_ >= 0;
  1207. case uintValue:
  1208. return true;
  1209. case realValue:
  1210. // Note that maxUInt64 (= 2^64 - 1) is not exactly representable as a
  1211. // double, so double(maxUInt64) will be rounded up to 2^64. Therefore we
  1212. // require the value to be strictly less than the limit.
  1213. return value_.real_ >= 0 && value_.real_ < maxUInt64AsDouble &&
  1214. IsIntegral(value_.real_);
  1215. default:
  1216. break;
  1217. }
  1218. #endif // JSON_HAS_INT64
  1219. return false;
  1220. }
  1221. bool Value::isIntegral() const {
  1222. switch (type()) {
  1223. case intValue:
  1224. case uintValue:
  1225. return true;
  1226. case realValue:
  1227. #if defined(JSON_HAS_INT64)
  1228. // Note that maxUInt64 (= 2^64 - 1) is not exactly representable as a
  1229. // double, so double(maxUInt64) will be rounded up to 2^64. Therefore we
  1230. // require the value to be strictly less than the limit.
  1231. return value_.real_ >= double(minInt64) &&
  1232. value_.real_ < maxUInt64AsDouble && IsIntegral(value_.real_);
  1233. #else
  1234. return value_.real_ >= minInt && value_.real_ <= maxUInt &&
  1235. IsIntegral(value_.real_);
  1236. #endif // JSON_HAS_INT64
  1237. default:
  1238. break;
  1239. }
  1240. return false;
  1241. }
  1242. bool Value::isDouble() const {
  1243. return type() == intValue || type() == uintValue || type() == realValue;
  1244. }
  1245. bool Value::isNumeric() const { return isDouble(); }
  1246. bool Value::isString() const { return type() == stringValue; }
  1247. bool Value::isArray() const { return type() == arrayValue; }
  1248. bool Value::isObject() const { return type() == objectValue; }
  1249. Value::Comments::Comments(const Comments& that)
  1250. : ptr_{cloneUnique(that.ptr_)} {}
  1251. Value::Comments::Comments(Comments&& that) noexcept
  1252. : ptr_{std::move(that.ptr_)} {}
  1253. Value::Comments& Value::Comments::operator=(const Comments& that) {
  1254. ptr_ = cloneUnique(that.ptr_);
  1255. return *this;
  1256. }
  1257. Value::Comments& Value::Comments::operator=(Comments&& that) noexcept {
  1258. ptr_ = std::move(that.ptr_);
  1259. return *this;
  1260. }
  1261. bool Value::Comments::has(CommentPlacement slot) const {
  1262. return ptr_ && !(*ptr_)[slot].empty();
  1263. }
  1264. String Value::Comments::get(CommentPlacement slot) const {
  1265. if (!ptr_)
  1266. return {};
  1267. return (*ptr_)[slot];
  1268. }
  1269. void Value::Comments::set(CommentPlacement slot, String comment) {
  1270. if (slot >= CommentPlacement::numberOfCommentPlacement)
  1271. return;
  1272. if (!ptr_)
  1273. ptr_ = std::unique_ptr<Array>(new Array());
  1274. (*ptr_)[slot] = std::move(comment);
  1275. }
  1276. void Value::setComment(String comment, CommentPlacement placement) {
  1277. if (!comment.empty() && (comment.back() == '\n')) {
  1278. // Always discard trailing newline, to aid indentation.
  1279. comment.pop_back();
  1280. }
  1281. JSON_ASSERT(!comment.empty());
  1282. JSON_ASSERT_MESSAGE(
  1283. comment[0] == '\0' || comment[0] == '/',
  1284. "in Json::Value::setComment(): Comments must start with /");
  1285. comments_.set(placement, std::move(comment));
  1286. }
  1287. bool Value::hasComment(CommentPlacement placement) const {
  1288. return comments_.has(placement);
  1289. }
  1290. String Value::getComment(CommentPlacement placement) const {
  1291. return comments_.get(placement);
  1292. }
  1293. void Value::setOffsetStart(ptrdiff_t start) { start_ = start; }
  1294. void Value::setOffsetLimit(ptrdiff_t limit) { limit_ = limit; }
  1295. ptrdiff_t Value::getOffsetStart() const { return start_; }
  1296. ptrdiff_t Value::getOffsetLimit() const { return limit_; }
  1297. String Value::toStyledString() const {
  1298. StreamWriterBuilder builder;
  1299. String out = this->hasComment(commentBefore) ? "\n" : "";
  1300. out += Json::writeString(builder, *this);
  1301. out += '\n';
  1302. return out;
  1303. }
  1304. Value::const_iterator Value::begin() const {
  1305. switch (type()) {
  1306. case arrayValue:
  1307. case objectValue:
  1308. if (value_.map_)
  1309. return const_iterator(value_.map_->begin());
  1310. break;
  1311. default:
  1312. break;
  1313. }
  1314. return {};
  1315. }
  1316. Value::const_iterator Value::end() const {
  1317. switch (type()) {
  1318. case arrayValue:
  1319. case objectValue:
  1320. if (value_.map_)
  1321. return const_iterator(value_.map_->end());
  1322. break;
  1323. default:
  1324. break;
  1325. }
  1326. return {};
  1327. }
  1328. Value::iterator Value::begin() {
  1329. switch (type()) {
  1330. case arrayValue:
  1331. case objectValue:
  1332. if (value_.map_)
  1333. return iterator(value_.map_->begin());
  1334. break;
  1335. default:
  1336. break;
  1337. }
  1338. return iterator();
  1339. }
  1340. Value::iterator Value::end() {
  1341. switch (type()) {
  1342. case arrayValue:
  1343. case objectValue:
  1344. if (value_.map_)
  1345. return iterator(value_.map_->end());
  1346. break;
  1347. default:
  1348. break;
  1349. }
  1350. return iterator();
  1351. }
  1352. // class PathArgument
  1353. // //////////////////////////////////////////////////////////////////
  1354. PathArgument::PathArgument() = default;
  1355. PathArgument::PathArgument(ArrayIndex index)
  1356. : index_(index), kind_(kindIndex) {}
  1357. PathArgument::PathArgument(const char* key) : key_(key), kind_(kindKey) {}
  1358. PathArgument::PathArgument(String key) : key_(std::move(key)), kind_(kindKey) {}
  1359. // class Path
  1360. // //////////////////////////////////////////////////////////////////
  1361. Path::Path(const String& path, const PathArgument& a1, const PathArgument& a2,
  1362. const PathArgument& a3, const PathArgument& a4,
  1363. const PathArgument& a5) {
  1364. InArgs in;
  1365. in.reserve(5);
  1366. in.push_back(&a1);
  1367. in.push_back(&a2);
  1368. in.push_back(&a3);
  1369. in.push_back(&a4);
  1370. in.push_back(&a5);
  1371. makePath(path, in);
  1372. }
  1373. void Path::makePath(const String& path, const InArgs& in) {
  1374. const char* current = path.c_str();
  1375. const char* end = current + path.length();
  1376. auto itInArg = in.begin();
  1377. while (current != end) {
  1378. if (*current == '[') {
  1379. ++current;
  1380. if (*current == '%')
  1381. addPathInArg(path, in, itInArg, PathArgument::kindIndex);
  1382. else {
  1383. ArrayIndex index = 0;
  1384. for (; current != end && *current >= '0' && *current <= '9'; ++current)
  1385. index = index * 10 + ArrayIndex(*current - '0');
  1386. args_.push_back(index);
  1387. }
  1388. if (current == end || *++current != ']')
  1389. invalidPath(path, int(current - path.c_str()));
  1390. } else if (*current == '%') {
  1391. addPathInArg(path, in, itInArg, PathArgument::kindKey);
  1392. ++current;
  1393. } else if (*current == '.' || *current == ']') {
  1394. ++current;
  1395. } else {
  1396. const char* beginName = current;
  1397. while (current != end && !strchr("[.", *current))
  1398. ++current;
  1399. args_.push_back(String(beginName, current));
  1400. }
  1401. }
  1402. }
  1403. void Path::addPathInArg(const String& /*path*/, const InArgs& in,
  1404. InArgs::const_iterator& itInArg,
  1405. PathArgument::Kind kind) {
  1406. if (itInArg == in.end()) {
  1407. // Error: missing argument %d
  1408. } else if ((*itInArg)->kind_ != kind) {
  1409. // Error: bad argument type
  1410. } else {
  1411. args_.push_back(**itInArg++);
  1412. }
  1413. }
  1414. void Path::invalidPath(const String& /*path*/, int /*location*/) {
  1415. // Error: invalid path.
  1416. }
  1417. const Value& Path::resolve(const Value& root) const {
  1418. const Value* node = &root;
  1419. for (const auto& arg : args_) {
  1420. if (arg.kind_ == PathArgument::kindIndex) {
  1421. if (!node->isArray() || !node->isValidIndex(arg.index_)) {
  1422. // Error: unable to resolve path (array value expected at position... )
  1423. return Value::nullSingleton();
  1424. }
  1425. node = &((*node)[arg.index_]);
  1426. } else if (arg.kind_ == PathArgument::kindKey) {
  1427. if (!node->isObject()) {
  1428. // Error: unable to resolve path (object value expected at position...)
  1429. return Value::nullSingleton();
  1430. }
  1431. node = &((*node)[arg.key_]);
  1432. if (node == &Value::nullSingleton()) {
  1433. // Error: unable to resolve path (object has no member named '' at
  1434. // position...)
  1435. return Value::nullSingleton();
  1436. }
  1437. }
  1438. }
  1439. return *node;
  1440. }
  1441. Value Path::resolve(const Value& root, const Value& defaultValue) const {
  1442. const Value* node = &root;
  1443. for (const auto& arg : args_) {
  1444. if (arg.kind_ == PathArgument::kindIndex) {
  1445. if (!node->isArray() || !node->isValidIndex(arg.index_))
  1446. return defaultValue;
  1447. node = &((*node)[arg.index_]);
  1448. } else if (arg.kind_ == PathArgument::kindKey) {
  1449. if (!node->isObject())
  1450. return defaultValue;
  1451. node = &((*node)[arg.key_]);
  1452. if (node == &Value::nullSingleton())
  1453. return defaultValue;
  1454. }
  1455. }
  1456. return *node;
  1457. }
  1458. Value& Path::make(Value& root) const {
  1459. Value* node = &root;
  1460. for (const auto& arg : args_) {
  1461. if (arg.kind_ == PathArgument::kindIndex) {
  1462. if (!node->isArray()) {
  1463. // Error: node is not an array at position ...
  1464. }
  1465. node = &((*node)[arg.index_]);
  1466. } else if (arg.kind_ == PathArgument::kindKey) {
  1467. if (!node->isObject()) {
  1468. // Error: node is not an object at position...
  1469. }
  1470. node = &((*node)[arg.key_]);
  1471. }
  1472. }
  1473. return *node;
  1474. }
  1475. } // namespace Json