2
0

json.h 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346
  1. /// Json-cpp amalgamated header (http://jsoncpp.sourceforge.net/).
  2. /// It is intended to be used with #include "json/json.h"
  3. // //////////////////////////////////////////////////////////////////////
  4. // Beginning of content of file: LICENSE
  5. // //////////////////////////////////////////////////////////////////////
  6. /*
  7. The JsonCpp library's source code, including accompanying documentation,
  8. tests and demonstration applications, are licensed under the following
  9. conditions...
  10. Baptiste Lepilleur and The JsonCpp Authors explicitly disclaim copyright in all
  11. jurisdictions which recognize such a disclaimer. In such jurisdictions,
  12. this software is released into the Public Domain.
  13. In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
  14. 2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur and
  15. The JsonCpp Authors, and is released under the terms of the MIT License (see below).
  16. In jurisdictions which recognize Public Domain property, the user of this
  17. software may choose to accept it either as 1) Public Domain, 2) under the
  18. conditions of the MIT License (see below), or 3) under the terms of dual
  19. Public Domain/MIT License conditions described here, as they choose.
  20. The MIT License is about as close to Public Domain as a license can get, and is
  21. described in clear, concise terms at:
  22. http://en.wikipedia.org/wiki/MIT_License
  23. The full text of the MIT License follows:
  24. ========================================================================
  25. Copyright (c) 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
  26. Permission is hereby granted, free of charge, to any person
  27. obtaining a copy of this software and associated documentation
  28. files (the "Software"), to deal in the Software without
  29. restriction, including without limitation the rights to use, copy,
  30. modify, merge, publish, distribute, sublicense, and/or sell copies
  31. of the Software, and to permit persons to whom the Software is
  32. furnished to do so, subject to the following conditions:
  33. The above copyright notice and this permission notice shall be
  34. included in all copies or substantial portions of the Software.
  35. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  36. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  37. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  38. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  39. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  40. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  41. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  42. SOFTWARE.
  43. ========================================================================
  44. (END LICENSE TEXT)
  45. The MIT license is compatible with both the GPL and commercial
  46. software, affording one all of the rights of Public Domain with the
  47. minor nuisance of being required to keep the above copyright notice
  48. and license text in the source code. Note also that by accepting the
  49. Public Domain "license" you can re-license your copy using whatever
  50. license you like.
  51. */
  52. // //////////////////////////////////////////////////////////////////////
  53. // End of content of file: LICENSE
  54. // //////////////////////////////////////////////////////////////////////
  55. #ifndef JSON_AMALGAMATED_H_INCLUDED
  56. # define JSON_AMALGAMATED_H_INCLUDED
  57. /// If defined, indicates that the source file is amalgamated
  58. /// to prevent private header inclusion.
  59. #define JSON_IS_AMALGAMATION
  60. // //////////////////////////////////////////////////////////////////////
  61. // Beginning of content of file: include/json/version.h
  62. // //////////////////////////////////////////////////////////////////////
  63. #ifndef JSON_VERSION_H_INCLUDED
  64. #define JSON_VERSION_H_INCLUDED
  65. // Note: version must be updated in three places when doing a release. This
  66. // annoying process ensures that amalgamate, CMake, and meson all report the
  67. // correct version.
  68. // 1. /meson.build
  69. // 2. /include/json/version.h
  70. // 3. /CMakeLists.txt
  71. // IMPORTANT: also update the SOVERSION!!
  72. #define JSONCPP_VERSION_STRING "1.9.5"
  73. #define JSONCPP_VERSION_MAJOR 1
  74. #define JSONCPP_VERSION_MINOR 9
  75. #define JSONCPP_VERSION_PATCH 5
  76. #define JSONCPP_VERSION_QUALIFIER
  77. #define JSONCPP_VERSION_HEXA \
  78. ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | \
  79. (JSONCPP_VERSION_PATCH << 8))
  80. #ifdef JSONCPP_USING_SECURE_MEMORY
  81. #undef JSONCPP_USING_SECURE_MEMORY
  82. #endif
  83. #define JSONCPP_USING_SECURE_MEMORY 0
  84. // If non-zero, the library zeroes any memory that it has allocated before
  85. // it frees its memory.
  86. #endif // JSON_VERSION_H_INCLUDED
  87. // //////////////////////////////////////////////////////////////////////
  88. // End of content of file: include/json/version.h
  89. // //////////////////////////////////////////////////////////////////////
  90. // //////////////////////////////////////////////////////////////////////
  91. // Beginning of content of file: include/json/allocator.h
  92. // //////////////////////////////////////////////////////////////////////
  93. // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
  94. // Distributed under MIT license, or public domain if desired and
  95. // recognized in your jurisdiction.
  96. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  97. #ifndef JSON_ALLOCATOR_H_INCLUDED
  98. #define JSON_ALLOCATOR_H_INCLUDED
  99. #include <cstring>
  100. #include <memory>
  101. #pragma pack(push, 8)
  102. namespace Json {
  103. template <typename T> class SecureAllocator {
  104. public:
  105. // Type definitions
  106. using value_type = T;
  107. using pointer = T*;
  108. using const_pointer = const T*;
  109. using reference = T&;
  110. using const_reference = const T&;
  111. using size_type = std::size_t;
  112. using difference_type = std::ptrdiff_t;
  113. /**
  114. * Allocate memory for N items using the standard allocator.
  115. */
  116. pointer allocate(size_type n) {
  117. // allocate using "global operator new"
  118. return static_cast<pointer>(::operator new(n * sizeof(T)));
  119. }
  120. /**
  121. * Release memory which was allocated for N items at pointer P.
  122. *
  123. * The memory block is filled with zeroes before being released.
  124. */
  125. void deallocate(pointer p, size_type n) {
  126. // memset_s is used because memset may be optimized away by the compiler
  127. memset_s(p, n * sizeof(T), 0, n * sizeof(T));
  128. // free using "global operator delete"
  129. ::operator delete(p);
  130. }
  131. /**
  132. * Construct an item in-place at pointer P.
  133. */
  134. template <typename... Args> void construct(pointer p, Args&&... args) {
  135. // construct using "placement new" and "perfect forwarding"
  136. ::new (static_cast<void*>(p)) T(std::forward<Args>(args)...);
  137. }
  138. size_type max_size() const { return size_t(-1) / sizeof(T); }
  139. pointer address(reference x) const { return std::addressof(x); }
  140. const_pointer address(const_reference x) const { return std::addressof(x); }
  141. /**
  142. * Destroy an item in-place at pointer P.
  143. */
  144. void destroy(pointer p) {
  145. // destroy using "explicit destructor"
  146. p->~T();
  147. }
  148. // Boilerplate
  149. SecureAllocator() {}
  150. template <typename U> SecureAllocator(const SecureAllocator<U>&) {}
  151. template <typename U> struct rebind { using other = SecureAllocator<U>; };
  152. };
  153. template <typename T, typename U>
  154. bool operator==(const SecureAllocator<T>&, const SecureAllocator<U>&) {
  155. return true;
  156. }
  157. template <typename T, typename U>
  158. bool operator!=(const SecureAllocator<T>&, const SecureAllocator<U>&) {
  159. return false;
  160. }
  161. } // namespace Json
  162. #pragma pack(pop)
  163. #endif // JSON_ALLOCATOR_H_INCLUDED
  164. // //////////////////////////////////////////////////////////////////////
  165. // End of content of file: include/json/allocator.h
  166. // //////////////////////////////////////////////////////////////////////
  167. // //////////////////////////////////////////////////////////////////////
  168. // Beginning of content of file: include/json/config.h
  169. // //////////////////////////////////////////////////////////////////////
  170. // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
  171. // Distributed under MIT license, or public domain if desired and
  172. // recognized in your jurisdiction.
  173. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  174. #ifndef JSON_CONFIG_H_INCLUDED
  175. #define JSON_CONFIG_H_INCLUDED
  176. #include <cstddef>
  177. #include <cstdint>
  178. #include <istream>
  179. #include <memory>
  180. #include <ostream>
  181. #include <sstream>
  182. #include <string>
  183. #include <type_traits>
  184. // If non-zero, the library uses exceptions to report bad input instead of C
  185. // assertion macros. The default is to use exceptions.
  186. #ifndef JSON_USE_EXCEPTION
  187. #define JSON_USE_EXCEPTION 1
  188. #endif
  189. // Temporary, tracked for removal with issue #982.
  190. #ifndef JSON_USE_NULLREF
  191. #define JSON_USE_NULLREF 1
  192. #endif
  193. /// If defined, indicates that the source file is amalgamated
  194. /// to prevent private header inclusion.
  195. /// Remarks: it is automatically defined in the generated amalgamated header.
  196. // #define JSON_IS_AMALGAMATION
  197. // Export macros for DLL visibility
  198. #if defined(JSON_DLL_BUILD)
  199. #if defined(_MSC_VER) || defined(__MINGW32__)
  200. #define JSON_API __declspec(dllexport)
  201. #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
  202. #elif defined(__GNUC__) || defined(__clang__)
  203. #define JSON_API __attribute__((visibility("default")))
  204. #endif // if defined(_MSC_VER)
  205. #elif defined(JSON_DLL)
  206. #if defined(_MSC_VER) || defined(__MINGW32__)
  207. #define JSON_API __declspec(dllimport)
  208. #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
  209. #endif // if defined(_MSC_VER)
  210. #endif // ifdef JSON_DLL_BUILD
  211. #if !defined(JSON_API)
  212. #define JSON_API
  213. #endif
  214. #if defined(_MSC_VER) && _MSC_VER < 1800
  215. #error \
  216. "ERROR: Visual Studio 12 (2013) with _MSC_VER=1800 is the oldest supported compiler with sufficient C++11 capabilities"
  217. #endif
  218. #if defined(_MSC_VER) && _MSC_VER < 1900
  219. // As recommended at
  220. // https://stackoverflow.com/questions/2915672/snprintf-and-visual-studio-2010
  221. extern JSON_API int msvc_pre1900_c99_snprintf(char* outBuf, size_t size,
  222. const char* format, ...);
  223. #define jsoncpp_snprintf msvc_pre1900_c99_snprintf
  224. #else
  225. #define jsoncpp_snprintf std::snprintf
  226. #endif
  227. // If JSON_NO_INT64 is defined, then Json only support C++ "int" type for
  228. // integer
  229. // Storages, and 64 bits integer support is disabled.
  230. // #define JSON_NO_INT64 1
  231. // JSONCPP_OVERRIDE is maintained for backwards compatibility of external tools.
  232. // C++11 should be used directly in JSONCPP.
  233. #define JSONCPP_OVERRIDE override
  234. #ifdef __clang__
  235. #if __has_extension(attribute_deprecated_with_message)
  236. #define JSONCPP_DEPRECATED(message) __attribute__((deprecated(message)))
  237. #endif
  238. #elif defined(__GNUC__) // not clang (gcc comes later since clang emulates gcc)
  239. #if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
  240. #define JSONCPP_DEPRECATED(message) __attribute__((deprecated(message)))
  241. #elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
  242. #define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__))
  243. #endif // GNUC version
  244. #elif defined(_MSC_VER) // MSVC (after clang because clang on Windows emulates
  245. // MSVC)
  246. #define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
  247. #endif // __clang__ || __GNUC__ || _MSC_VER
  248. #if !defined(JSONCPP_DEPRECATED)
  249. #define JSONCPP_DEPRECATED(message)
  250. #endif // if !defined(JSONCPP_DEPRECATED)
  251. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 6))
  252. #define JSON_USE_INT64_DOUBLE_CONVERSION 1
  253. #endif
  254. #if !defined(JSON_IS_AMALGAMATION)
  255. #include "allocator.h"
  256. #include "version.h"
  257. #endif // if !defined(JSON_IS_AMALGAMATION)
  258. namespace Json {
  259. using Int = int;
  260. using UInt = unsigned int;
  261. #if defined(JSON_NO_INT64)
  262. using LargestInt = int;
  263. using LargestUInt = unsigned int;
  264. #undef JSON_HAS_INT64
  265. #else // if defined(JSON_NO_INT64)
  266. // For Microsoft Visual use specific types as long long is not supported
  267. #if defined(_MSC_VER) // Microsoft Visual Studio
  268. using Int64 = __int64;
  269. using UInt64 = unsigned __int64;
  270. #else // if defined(_MSC_VER) // Other platforms, use long long
  271. using Int64 = int64_t;
  272. using UInt64 = uint64_t;
  273. #endif // if defined(_MSC_VER)
  274. using LargestInt = Int64;
  275. using LargestUInt = UInt64;
  276. #define JSON_HAS_INT64
  277. #endif // if defined(JSON_NO_INT64)
  278. template <typename T>
  279. using Allocator =
  280. typename std::conditional<JSONCPP_USING_SECURE_MEMORY, SecureAllocator<T>,
  281. std::allocator<T>>::type;
  282. using String = std::basic_string<char, std::char_traits<char>, Allocator<char>>;
  283. using IStringStream =
  284. std::basic_istringstream<String::value_type, String::traits_type,
  285. String::allocator_type>;
  286. using OStringStream =
  287. std::basic_ostringstream<String::value_type, String::traits_type,
  288. String::allocator_type>;
  289. using IStream = std::istream;
  290. using OStream = std::ostream;
  291. } // namespace Json
  292. // Legacy names (formerly macros).
  293. using JSONCPP_STRING = Json::String;
  294. using JSONCPP_ISTRINGSTREAM = Json::IStringStream;
  295. using JSONCPP_OSTRINGSTREAM = Json::OStringStream;
  296. using JSONCPP_ISTREAM = Json::IStream;
  297. using JSONCPP_OSTREAM = Json::OStream;
  298. #endif // JSON_CONFIG_H_INCLUDED
  299. // //////////////////////////////////////////////////////////////////////
  300. // End of content of file: include/json/config.h
  301. // //////////////////////////////////////////////////////////////////////
  302. // //////////////////////////////////////////////////////////////////////
  303. // Beginning of content of file: include/json/forwards.h
  304. // //////////////////////////////////////////////////////////////////////
  305. // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
  306. // Distributed under MIT license, or public domain if desired and
  307. // recognized in your jurisdiction.
  308. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  309. #ifndef JSON_FORWARDS_H_INCLUDED
  310. #define JSON_FORWARDS_H_INCLUDED
  311. #if !defined(JSON_IS_AMALGAMATION)
  312. #include "config.h"
  313. #endif // if !defined(JSON_IS_AMALGAMATION)
  314. namespace Json {
  315. // writer.h
  316. class StreamWriter;
  317. class StreamWriterBuilder;
  318. class Writer;
  319. class FastWriter;
  320. class StyledWriter;
  321. class StyledStreamWriter;
  322. // reader.h
  323. class Reader;
  324. class CharReader;
  325. class CharReaderBuilder;
  326. // json_features.h
  327. class Features;
  328. // value.h
  329. using ArrayIndex = unsigned int;
  330. class StaticString;
  331. class Path;
  332. class PathArgument;
  333. class Value;
  334. class ValueIteratorBase;
  335. class ValueIterator;
  336. class ValueConstIterator;
  337. } // namespace Json
  338. #endif // JSON_FORWARDS_H_INCLUDED
  339. // //////////////////////////////////////////////////////////////////////
  340. // End of content of file: include/json/forwards.h
  341. // //////////////////////////////////////////////////////////////////////
  342. // //////////////////////////////////////////////////////////////////////
  343. // Beginning of content of file: include/json/json_features.h
  344. // //////////////////////////////////////////////////////////////////////
  345. // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
  346. // Distributed under MIT license, or public domain if desired and
  347. // recognized in your jurisdiction.
  348. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  349. #ifndef JSON_FEATURES_H_INCLUDED
  350. #define JSON_FEATURES_H_INCLUDED
  351. #if !defined(JSON_IS_AMALGAMATION)
  352. #include "forwards.h"
  353. #endif // if !defined(JSON_IS_AMALGAMATION)
  354. #pragma pack(push, 8)
  355. namespace Json {
  356. /** \brief Configuration passed to reader and writer.
  357. * This configuration object can be used to force the Reader or Writer
  358. * to behave in a standard conforming way.
  359. */
  360. class JSON_API Features {
  361. public:
  362. /** \brief A configuration that allows all features and assumes all strings
  363. * are UTF-8.
  364. * - C & C++ comments are allowed
  365. * - Root object can be any JSON value
  366. * - Assumes Value strings are encoded in UTF-8
  367. */
  368. static Features all();
  369. /** \brief A configuration that is strictly compatible with the JSON
  370. * specification.
  371. * - Comments are forbidden.
  372. * - Root object must be either an array or an object value.
  373. * - Assumes Value strings are encoded in UTF-8
  374. */
  375. static Features strictMode();
  376. /** \brief Initialize the configuration like JsonConfig::allFeatures;
  377. */
  378. Features();
  379. /// \c true if comments are allowed. Default: \c true.
  380. bool allowComments_{true};
  381. /// \c true if root must be either an array or an object value. Default: \c
  382. /// false.
  383. bool strictRoot_{false};
  384. /// \c true if dropped null placeholders are allowed. Default: \c false.
  385. bool allowDroppedNullPlaceholders_{false};
  386. /// \c true if numeric object key are allowed. Default: \c false.
  387. bool allowNumericKeys_{false};
  388. };
  389. } // namespace Json
  390. #pragma pack(pop)
  391. #endif // JSON_FEATURES_H_INCLUDED
  392. // //////////////////////////////////////////////////////////////////////
  393. // End of content of file: include/json/json_features.h
  394. // //////////////////////////////////////////////////////////////////////
  395. // //////////////////////////////////////////////////////////////////////
  396. // Beginning of content of file: include/json/value.h
  397. // //////////////////////////////////////////////////////////////////////
  398. // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
  399. // Distributed under MIT license, or public domain if desired and
  400. // recognized in your jurisdiction.
  401. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  402. #ifndef JSON_H_INCLUDED
  403. #define JSON_H_INCLUDED
  404. #if !defined(JSON_IS_AMALGAMATION)
  405. #include "forwards.h"
  406. #endif // if !defined(JSON_IS_AMALGAMATION)
  407. // Conditional NORETURN attribute on the throw functions would:
  408. // a) suppress false positives from static code analysis
  409. // b) possibly improve optimization opportunities.
  410. #if !defined(JSONCPP_NORETURN)
  411. #if defined(_MSC_VER) && _MSC_VER == 1800
  412. #define JSONCPP_NORETURN __declspec(noreturn)
  413. #else
  414. #define JSONCPP_NORETURN [[noreturn]]
  415. #endif
  416. #endif
  417. // Support for '= delete' with template declarations was a late addition
  418. // to the c++11 standard and is rejected by clang 3.8 and Apple clang 8.2
  419. // even though these declare themselves to be c++11 compilers.
  420. #if !defined(JSONCPP_TEMPLATE_DELETE)
  421. #if defined(__clang__) && defined(__apple_build_version__)
  422. #if __apple_build_version__ <= 8000042
  423. #define JSONCPP_TEMPLATE_DELETE
  424. #endif
  425. #elif defined(__clang__)
  426. #if __clang_major__ == 3 && __clang_minor__ <= 8
  427. #define JSONCPP_TEMPLATE_DELETE
  428. #endif
  429. #endif
  430. #if !defined(JSONCPP_TEMPLATE_DELETE)
  431. #define JSONCPP_TEMPLATE_DELETE = delete
  432. #endif
  433. #endif
  434. #include <array>
  435. #include <exception>
  436. #include <map>
  437. #include <memory>
  438. #include <string>
  439. #include <vector>
  440. // Disable warning C4251: <data member>: <type> needs to have dll-interface to
  441. // be used by...
  442. #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  443. #pragma warning(push)
  444. #pragma warning(disable : 4251 4275)
  445. #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  446. #pragma pack(push, 8)
  447. /** \brief JSON (JavaScript Object Notation).
  448. */
  449. namespace Json {
  450. #if JSON_USE_EXCEPTION
  451. /** Base class for all exceptions we throw.
  452. *
  453. * We use nothing but these internally. Of course, STL can throw others.
  454. */
  455. class JSON_API Exception : public std::exception {
  456. public:
  457. Exception(String msg);
  458. ~Exception() noexcept override;
  459. char const* what() const noexcept override;
  460. protected:
  461. String msg_;
  462. };
  463. /** Exceptions which the user cannot easily avoid.
  464. *
  465. * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
  466. *
  467. * \remark derived from Json::Exception
  468. */
  469. class JSON_API RuntimeError : public Exception {
  470. public:
  471. RuntimeError(String const& msg);
  472. };
  473. /** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
  474. *
  475. * These are precondition-violations (user bugs) and internal errors (our bugs).
  476. *
  477. * \remark derived from Json::Exception
  478. */
  479. class JSON_API LogicError : public Exception {
  480. public:
  481. LogicError(String const& msg);
  482. };
  483. #endif
  484. /// used internally
  485. JSONCPP_NORETURN void throwRuntimeError(String const& msg);
  486. /// used internally
  487. JSONCPP_NORETURN void throwLogicError(String const& msg);
  488. /** \brief Type of the value held by a Value object.
  489. */
  490. enum ValueType {
  491. nullValue = 0, ///< 'null' value
  492. intValue, ///< signed integer value
  493. uintValue, ///< unsigned integer value
  494. realValue, ///< double value
  495. stringValue, ///< UTF-8 string value
  496. booleanValue, ///< bool value
  497. arrayValue, ///< array value (ordered list)
  498. objectValue ///< object value (collection of name/value pairs).
  499. };
  500. enum CommentPlacement {
  501. commentBefore = 0, ///< a comment placed on the line before a value
  502. commentAfterOnSameLine, ///< a comment just after a value on the same line
  503. commentAfter, ///< a comment on the line after a value (only make sense for
  504. /// root value)
  505. numberOfCommentPlacement
  506. };
  507. /** \brief Type of precision for formatting of real values.
  508. */
  509. enum PrecisionType {
  510. significantDigits = 0, ///< we set max number of significant digits in string
  511. decimalPlaces ///< we set max number of digits after "." in string
  512. };
  513. /** \brief Lightweight wrapper to tag static string.
  514. *
  515. * Value constructor and objectValue member assignment takes advantage of the
  516. * StaticString and avoid the cost of string duplication when storing the
  517. * string or the member name.
  518. *
  519. * Example of usage:
  520. * \code
  521. * Json::Value aValue( StaticString("some text") );
  522. * Json::Value object;
  523. * static const StaticString code("code");
  524. * object[code] = 1234;
  525. * \endcode
  526. */
  527. class JSON_API StaticString {
  528. public:
  529. explicit StaticString(const char* czstring) : c_str_(czstring) {}
  530. operator const char*() const { return c_str_; }
  531. const char* c_str() const { return c_str_; }
  532. private:
  533. const char* c_str_;
  534. };
  535. /** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
  536. *
  537. * This class is a discriminated union wrapper that can represents a:
  538. * - signed integer [range: Value::minInt - Value::maxInt]
  539. * - unsigned integer (range: 0 - Value::maxUInt)
  540. * - double
  541. * - UTF-8 string
  542. * - boolean
  543. * - 'null'
  544. * - an ordered list of Value
  545. * - collection of name/value pairs (javascript object)
  546. *
  547. * The type of the held value is represented by a #ValueType and
  548. * can be obtained using type().
  549. *
  550. * Values of an #objectValue or #arrayValue can be accessed using operator[]()
  551. * methods.
  552. * Non-const methods will automatically create the a #nullValue element
  553. * if it does not exist.
  554. * The sequence of an #arrayValue will be automatically resized and initialized
  555. * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
  556. *
  557. * The get() methods can be used to obtain default value in the case the
  558. * required element does not exist.
  559. *
  560. * It is possible to iterate over the list of member keys of an object using
  561. * the getMemberNames() method.
  562. *
  563. * \note #Value string-length fit in size_t, but keys must be < 2^30.
  564. * (The reason is an implementation detail.) A #CharReader will raise an
  565. * exception if a bound is exceeded to avoid security holes in your app,
  566. * but the Value API does *not* check bounds. That is the responsibility
  567. * of the caller.
  568. */
  569. class JSON_API Value {
  570. friend class ValueIteratorBase;
  571. public:
  572. using Members = std::vector<String>;
  573. using iterator = ValueIterator;
  574. using const_iterator = ValueConstIterator;
  575. using UInt = Json::UInt;
  576. using Int = Json::Int;
  577. #if defined(JSON_HAS_INT64)
  578. using UInt64 = Json::UInt64;
  579. using Int64 = Json::Int64;
  580. #endif // defined(JSON_HAS_INT64)
  581. using LargestInt = Json::LargestInt;
  582. using LargestUInt = Json::LargestUInt;
  583. using ArrayIndex = Json::ArrayIndex;
  584. // Required for boost integration, e. g. BOOST_TEST
  585. using value_type = std::string;
  586. #if JSON_USE_NULLREF
  587. // Binary compatibility kludges, do not use.
  588. static const Value& null;
  589. static const Value& nullRef;
  590. #endif
  591. // null and nullRef are deprecated, use this instead.
  592. static Value const& nullSingleton();
  593. /// Minimum signed integer value that can be stored in a Json::Value.
  594. static constexpr LargestInt minLargestInt =
  595. LargestInt(~(LargestUInt(-1) / 2));
  596. /// Maximum signed integer value that can be stored in a Json::Value.
  597. static constexpr LargestInt maxLargestInt = LargestInt(LargestUInt(-1) / 2);
  598. /// Maximum unsigned integer value that can be stored in a Json::Value.
  599. static constexpr LargestUInt maxLargestUInt = LargestUInt(-1);
  600. /// Minimum signed int value that can be stored in a Json::Value.
  601. static constexpr Int minInt = Int(~(UInt(-1) / 2));
  602. /// Maximum signed int value that can be stored in a Json::Value.
  603. static constexpr Int maxInt = Int(UInt(-1) / 2);
  604. /// Maximum unsigned int value that can be stored in a Json::Value.
  605. static constexpr UInt maxUInt = UInt(-1);
  606. #if defined(JSON_HAS_INT64)
  607. /// Minimum signed 64 bits int value that can be stored in a Json::Value.
  608. static constexpr Int64 minInt64 = Int64(~(UInt64(-1) / 2));
  609. /// Maximum signed 64 bits int value that can be stored in a Json::Value.
  610. static constexpr Int64 maxInt64 = Int64(UInt64(-1) / 2);
  611. /// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
  612. static constexpr UInt64 maxUInt64 = UInt64(-1);
  613. #endif // defined(JSON_HAS_INT64)
  614. /// Default precision for real value for string representation.
  615. static constexpr UInt defaultRealPrecision = 17;
  616. // The constant is hard-coded because some compiler have trouble
  617. // converting Value::maxUInt64 to a double correctly (AIX/xlC).
  618. // Assumes that UInt64 is a 64 bits integer.
  619. static constexpr double maxUInt64AsDouble = 18446744073709551615.0;
  620. // Workaround for bug in the NVIDIAs CUDA 9.1 nvcc compiler
  621. // when using gcc and clang backend compilers. CZString
  622. // cannot be defined as private. See issue #486
  623. #ifdef __NVCC__
  624. public:
  625. #else
  626. private:
  627. #endif
  628. #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
  629. class CZString {
  630. public:
  631. enum DuplicationPolicy { noDuplication = 0, duplicate, duplicateOnCopy };
  632. CZString(ArrayIndex index);
  633. CZString(char const* str, unsigned length, DuplicationPolicy allocate);
  634. CZString(CZString const& other);
  635. CZString(CZString&& other) noexcept;
  636. ~CZString();
  637. CZString& operator=(const CZString& other);
  638. CZString& operator=(CZString&& other) noexcept;
  639. bool operator<(CZString const& other) const;
  640. bool operator==(CZString const& other) const;
  641. ArrayIndex index() const;
  642. // const char* c_str() const; ///< \deprecated
  643. char const* data() const;
  644. unsigned length() const;
  645. bool isStaticString() const;
  646. private:
  647. void swap(CZString& other);
  648. struct StringStorage {
  649. unsigned policy_ : 2;
  650. unsigned length_ : 30; // 1GB max
  651. };
  652. char const* cstr_; // actually, a prefixed string, unless policy is noDup
  653. union {
  654. ArrayIndex index_;
  655. StringStorage storage_;
  656. };
  657. };
  658. public:
  659. typedef std::map<CZString, Value> ObjectValues;
  660. #endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
  661. public:
  662. /**
  663. * \brief Create a default Value of the given type.
  664. *
  665. * This is a very useful constructor.
  666. * To create an empty array, pass arrayValue.
  667. * To create an empty object, pass objectValue.
  668. * Another Value can then be set to this one by assignment.
  669. * This is useful since clear() and resize() will not alter types.
  670. *
  671. * Examples:
  672. * \code
  673. * Json::Value null_value; // null
  674. * Json::Value arr_value(Json::arrayValue); // []
  675. * Json::Value obj_value(Json::objectValue); // {}
  676. * \endcode
  677. */
  678. Value(ValueType type = nullValue);
  679. Value(Int value);
  680. Value(UInt value);
  681. #if defined(JSON_HAS_INT64)
  682. Value(Int64 value);
  683. Value(UInt64 value);
  684. #endif // if defined(JSON_HAS_INT64)
  685. Value(double value);
  686. Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.)
  687. Value(const char* begin, const char* end); ///< Copy all, incl zeroes.
  688. /**
  689. * \brief Constructs a value from a static string.
  690. *
  691. * Like other value string constructor but do not duplicate the string for
  692. * internal storage. The given string must remain alive after the call to
  693. * this constructor.
  694. *
  695. * \note This works only for null-terminated strings. (We cannot change the
  696. * size of this class, so we have nowhere to store the length, which might be
  697. * computed later for various operations.)
  698. *
  699. * Example of usage:
  700. * \code
  701. * static StaticString foo("some text");
  702. * Json::Value aValue(foo);
  703. * \endcode
  704. */
  705. Value(const StaticString& value);
  706. Value(const String& value);
  707. Value(bool value);
  708. Value(std::nullptr_t ptr) = delete;
  709. Value(const Value& other);
  710. Value(Value&& other) noexcept;
  711. ~Value();
  712. /// \note Overwrite existing comments. To preserve comments, use
  713. /// #swapPayload().
  714. Value& operator=(const Value& other);
  715. Value& operator=(Value&& other) noexcept;
  716. /// Swap everything.
  717. void swap(Value& other);
  718. /// Swap values but leave comments and source offsets in place.
  719. void swapPayload(Value& other);
  720. /// copy everything.
  721. void copy(const Value& other);
  722. /// copy values but leave comments and source offsets in place.
  723. void copyPayload(const Value& other);
  724. ValueType type() const;
  725. /// Compare payload only, not comments etc.
  726. bool operator<(const Value& other) const;
  727. bool operator<=(const Value& other) const;
  728. bool operator>=(const Value& other) const;
  729. bool operator>(const Value& other) const;
  730. bool operator==(const Value& other) const;
  731. bool operator!=(const Value& other) const;
  732. int compare(const Value& other) const;
  733. const char* asCString() const; ///< Embedded zeroes could cause you trouble!
  734. #if JSONCPP_USING_SECURE_MEMORY
  735. unsigned getCStringLength() const; // Allows you to understand the length of
  736. // the CString
  737. #endif
  738. String asString() const; ///< Embedded zeroes are possible.
  739. /** Get raw char* of string-value.
  740. * \return false if !string. (Seg-fault if str or end are NULL.)
  741. */
  742. bool getString(char const** begin, char const** end) const;
  743. Int asInt() const;
  744. UInt asUInt() const;
  745. #if defined(JSON_HAS_INT64)
  746. Int64 asInt64() const;
  747. UInt64 asUInt64() const;
  748. #endif // if defined(JSON_HAS_INT64)
  749. LargestInt asLargestInt() const;
  750. LargestUInt asLargestUInt() const;
  751. float asFloat() const;
  752. double asDouble() const;
  753. bool asBool() const;
  754. bool isNull() const;
  755. bool isBool() const;
  756. bool isInt() const;
  757. bool isInt64() const;
  758. bool isUInt() const;
  759. bool isUInt64() const;
  760. bool isIntegral() const;
  761. bool isDouble() const;
  762. bool isNumeric() const;
  763. bool isString() const;
  764. bool isArray() const;
  765. bool isObject() const;
  766. /// The `as<T>` and `is<T>` member function templates and specializations.
  767. template <typename T> T as() const JSONCPP_TEMPLATE_DELETE;
  768. template <typename T> bool is() const JSONCPP_TEMPLATE_DELETE;
  769. bool isConvertibleTo(ValueType other) const;
  770. /// Number of values in array or object
  771. ArrayIndex size() const;
  772. /// \brief Return true if empty array, empty object, or null;
  773. /// otherwise, false.
  774. bool empty() const;
  775. /// Return !isNull()
  776. explicit operator bool() const;
  777. /// Remove all object members and array elements.
  778. /// \pre type() is arrayValue, objectValue, or nullValue
  779. /// \post type() is unchanged
  780. void clear();
  781. /// Resize the array to newSize elements.
  782. /// New elements are initialized to null.
  783. /// May only be called on nullValue or arrayValue.
  784. /// \pre type() is arrayValue or nullValue
  785. /// \post type() is arrayValue
  786. void resize(ArrayIndex newSize);
  787. //@{
  788. /// Access an array element (zero based index). If the array contains less
  789. /// than index element, then null value are inserted in the array so that
  790. /// its size is index+1.
  791. /// (You may need to say 'value[0u]' to get your compiler to distinguish
  792. /// this from the operator[] which takes a string.)
  793. Value& operator[](ArrayIndex index);
  794. Value& operator[](int index);
  795. //@}
  796. //@{
  797. /// Access an array element (zero based index).
  798. /// (You may need to say 'value[0u]' to get your compiler to distinguish
  799. /// this from the operator[] which takes a string.)
  800. const Value& operator[](ArrayIndex index) const;
  801. const Value& operator[](int index) const;
  802. //@}
  803. /// If the array contains at least index+1 elements, returns the element
  804. /// value, otherwise returns defaultValue.
  805. Value get(ArrayIndex index, const Value& defaultValue) const;
  806. /// Return true if index < size().
  807. bool isValidIndex(ArrayIndex index) const;
  808. /// \brief Append value to array at the end.
  809. ///
  810. /// Equivalent to jsonvalue[jsonvalue.size()] = value;
  811. Value& append(const Value& value);
  812. Value& append(Value&& value);
  813. /// \brief Insert value in array at specific index
  814. bool insert(ArrayIndex index, const Value& newValue);
  815. bool insert(ArrayIndex index, Value&& newValue);
  816. /// Access an object value by name, create a null member if it does not exist.
  817. /// \note Because of our implementation, keys are limited to 2^30 -1 chars.
  818. /// Exceeding that will cause an exception.
  819. Value& operator[](const char* key);
  820. /// Access an object value by name, returns null if there is no member with
  821. /// that name.
  822. const Value& operator[](const char* key) const;
  823. /// Access an object value by name, create a null member if it does not exist.
  824. /// \param key may contain embedded nulls.
  825. Value& operator[](const String& key);
  826. /// Access an object value by name, returns null if there is no member with
  827. /// that name.
  828. /// \param key may contain embedded nulls.
  829. const Value& operator[](const String& key) const;
  830. /** \brief Access an object value by name, create a null member if it does not
  831. * exist.
  832. *
  833. * If the object has no entry for that name, then the member name used to
  834. * store the new entry is not duplicated.
  835. * Example of use:
  836. * \code
  837. * Json::Value object;
  838. * static const StaticString code("code");
  839. * object[code] = 1234;
  840. * \endcode
  841. */
  842. Value& operator[](const StaticString& key);
  843. /// Return the member named key if it exist, defaultValue otherwise.
  844. /// \note deep copy
  845. Value get(const char* key, const Value& defaultValue) const;
  846. /// Return the member named key if it exist, defaultValue otherwise.
  847. /// \note deep copy
  848. /// \note key may contain embedded nulls.
  849. Value get(const char* begin, const char* end,
  850. const Value& defaultValue) const;
  851. /// Return the member named key if it exist, defaultValue otherwise.
  852. /// \note deep copy
  853. /// \param key may contain embedded nulls.
  854. Value get(const String& key, const Value& defaultValue) const;
  855. /// Most general and efficient version of isMember()const, get()const,
  856. /// and operator[]const
  857. /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
  858. Value const* find(char const* begin, char const* end) const;
  859. /// Most general and efficient version of object-mutators.
  860. /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
  861. /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
  862. Value* demand(char const* begin, char const* end);
  863. /// \brief Remove and return the named member.
  864. ///
  865. /// Do nothing if it did not exist.
  866. /// \pre type() is objectValue or nullValue
  867. /// \post type() is unchanged
  868. void removeMember(const char* key);
  869. /// Same as removeMember(const char*)
  870. /// \param key may contain embedded nulls.
  871. void removeMember(const String& key);
  872. /// Same as removeMember(const char* begin, const char* end, Value* removed),
  873. /// but 'key' is null-terminated.
  874. bool removeMember(const char* key, Value* removed);
  875. /** \brief Remove the named map member.
  876. *
  877. * Update 'removed' iff removed.
  878. * \param key may contain embedded nulls.
  879. * \return true iff removed (no exceptions)
  880. */
  881. bool removeMember(String const& key, Value* removed);
  882. /// Same as removeMember(String const& key, Value* removed)
  883. bool removeMember(const char* begin, const char* end, Value* removed);
  884. /** \brief Remove the indexed array element.
  885. *
  886. * O(n) expensive operations.
  887. * Update 'removed' iff removed.
  888. * \return true if removed (no exceptions)
  889. */
  890. bool removeIndex(ArrayIndex index, Value* removed);
  891. /// Return true if the object has a member named key.
  892. /// \note 'key' must be null-terminated.
  893. bool isMember(const char* key) const;
  894. /// Return true if the object has a member named key.
  895. /// \param key may contain embedded nulls.
  896. bool isMember(const String& key) const;
  897. /// Same as isMember(String const& key)const
  898. bool isMember(const char* begin, const char* end) const;
  899. /// \brief Return a list of the member names.
  900. ///
  901. /// If null, return an empty list.
  902. /// \pre type() is objectValue or nullValue
  903. /// \post if type() was nullValue, it remains nullValue
  904. Members getMemberNames() const;
  905. /// \deprecated Always pass len.
  906. JSONCPP_DEPRECATED("Use setComment(String const&) instead.")
  907. void setComment(const char* comment, CommentPlacement placement) {
  908. setComment(String(comment, strlen(comment)), placement);
  909. }
  910. /// Comments must be //... or /* ... */
  911. void setComment(const char* comment, size_t len, CommentPlacement placement) {
  912. setComment(String(comment, len), placement);
  913. }
  914. /// Comments must be //... or /* ... */
  915. void setComment(String comment, CommentPlacement placement);
  916. bool hasComment(CommentPlacement placement) const;
  917. /// Include delimiters and embedded newlines.
  918. String getComment(CommentPlacement placement) const;
  919. String toStyledString() const;
  920. const_iterator begin() const;
  921. const_iterator end() const;
  922. iterator begin();
  923. iterator end();
  924. // Accessors for the [start, limit) range of bytes within the JSON text from
  925. // which this value was parsed, if any.
  926. void setOffsetStart(ptrdiff_t start);
  927. void setOffsetLimit(ptrdiff_t limit);
  928. ptrdiff_t getOffsetStart() const;
  929. ptrdiff_t getOffsetLimit() const;
  930. private:
  931. void setType(ValueType v) {
  932. bits_.value_type_ = static_cast<unsigned char>(v);
  933. }
  934. bool isAllocated() const { return bits_.allocated_; }
  935. void setIsAllocated(bool v) { bits_.allocated_ = v; }
  936. void initBasic(ValueType type, bool allocated = false);
  937. void dupPayload(const Value& other);
  938. void releasePayload();
  939. void dupMeta(const Value& other);
  940. Value& resolveReference(const char* key);
  941. Value& resolveReference(const char* key, const char* end);
  942. // struct MemberNamesTransform
  943. //{
  944. // typedef const char *result_type;
  945. // const char *operator()( const CZString &name ) const
  946. // {
  947. // return name.c_str();
  948. // }
  949. //};
  950. union ValueHolder {
  951. LargestInt int_;
  952. LargestUInt uint_;
  953. double real_;
  954. bool bool_;
  955. char* string_; // if allocated_, ptr to { unsigned, char[] }.
  956. ObjectValues* map_;
  957. } value_;
  958. struct {
  959. // Really a ValueType, but types should agree for bitfield packing.
  960. unsigned int value_type_ : 8;
  961. // Unless allocated_, string_ must be null-terminated.
  962. unsigned int allocated_ : 1;
  963. } bits_;
  964. class Comments {
  965. public:
  966. Comments() = default;
  967. Comments(const Comments& that);
  968. Comments(Comments&& that) noexcept;
  969. Comments& operator=(const Comments& that);
  970. Comments& operator=(Comments&& that) noexcept;
  971. bool has(CommentPlacement slot) const;
  972. String get(CommentPlacement slot) const;
  973. void set(CommentPlacement slot, String comment);
  974. private:
  975. using Array = std::array<String, numberOfCommentPlacement>;
  976. std::unique_ptr<Array> ptr_;
  977. };
  978. Comments comments_;
  979. // [start, limit) byte offsets in the source JSON text from which this Value
  980. // was extracted.
  981. ptrdiff_t start_;
  982. ptrdiff_t limit_;
  983. };
  984. template <> inline bool Value::as<bool>() const { return asBool(); }
  985. template <> inline bool Value::is<bool>() const { return isBool(); }
  986. template <> inline Int Value::as<Int>() const { return asInt(); }
  987. template <> inline bool Value::is<Int>() const { return isInt(); }
  988. template <> inline UInt Value::as<UInt>() const { return asUInt(); }
  989. template <> inline bool Value::is<UInt>() const { return isUInt(); }
  990. #if defined(JSON_HAS_INT64)
  991. template <> inline Int64 Value::as<Int64>() const { return asInt64(); }
  992. template <> inline bool Value::is<Int64>() const { return isInt64(); }
  993. template <> inline UInt64 Value::as<UInt64>() const { return asUInt64(); }
  994. template <> inline bool Value::is<UInt64>() const { return isUInt64(); }
  995. #endif
  996. template <> inline double Value::as<double>() const { return asDouble(); }
  997. template <> inline bool Value::is<double>() const { return isDouble(); }
  998. template <> inline String Value::as<String>() const { return asString(); }
  999. template <> inline bool Value::is<String>() const { return isString(); }
  1000. /// These `as` specializations are type conversions, and do not have a
  1001. /// corresponding `is`.
  1002. template <> inline float Value::as<float>() const { return asFloat(); }
  1003. template <> inline const char* Value::as<const char*>() const {
  1004. return asCString();
  1005. }
  1006. /** \brief Experimental and untested: represents an element of the "path" to
  1007. * access a node.
  1008. */
  1009. class JSON_API PathArgument {
  1010. public:
  1011. friend class Path;
  1012. PathArgument();
  1013. PathArgument(ArrayIndex index);
  1014. PathArgument(const char* key);
  1015. PathArgument(String key);
  1016. private:
  1017. enum Kind { kindNone = 0, kindIndex, kindKey };
  1018. String key_;
  1019. ArrayIndex index_{};
  1020. Kind kind_{kindNone};
  1021. };
  1022. /** \brief Experimental and untested: represents a "path" to access a node.
  1023. *
  1024. * Syntax:
  1025. * - "." => root node
  1026. * - ".[n]" => elements at index 'n' of root node (an array value)
  1027. * - ".name" => member named 'name' of root node (an object value)
  1028. * - ".name1.name2.name3"
  1029. * - ".[0][1][2].name1[3]"
  1030. * - ".%" => member name is provided as parameter
  1031. * - ".[%]" => index is provided as parameter
  1032. */
  1033. class JSON_API Path {
  1034. public:
  1035. Path(const String& path, const PathArgument& a1 = PathArgument(),
  1036. const PathArgument& a2 = PathArgument(),
  1037. const PathArgument& a3 = PathArgument(),
  1038. const PathArgument& a4 = PathArgument(),
  1039. const PathArgument& a5 = PathArgument());
  1040. const Value& resolve(const Value& root) const;
  1041. Value resolve(const Value& root, const Value& defaultValue) const;
  1042. /// Creates the "path" to access the specified node and returns a reference on
  1043. /// the node.
  1044. Value& make(Value& root) const;
  1045. private:
  1046. using InArgs = std::vector<const PathArgument*>;
  1047. using Args = std::vector<PathArgument>;
  1048. void makePath(const String& path, const InArgs& in);
  1049. void addPathInArg(const String& path, const InArgs& in,
  1050. InArgs::const_iterator& itInArg, PathArgument::Kind kind);
  1051. static void invalidPath(const String& path, int location);
  1052. Args args_;
  1053. };
  1054. /** \brief base class for Value iterators.
  1055. *
  1056. */
  1057. class JSON_API ValueIteratorBase {
  1058. public:
  1059. using iterator_category = std::bidirectional_iterator_tag;
  1060. using size_t = unsigned int;
  1061. using difference_type = int;
  1062. using SelfType = ValueIteratorBase;
  1063. bool operator==(const SelfType& other) const { return isEqual(other); }
  1064. bool operator!=(const SelfType& other) const { return !isEqual(other); }
  1065. difference_type operator-(const SelfType& other) const {
  1066. return other.computeDistance(*this);
  1067. }
  1068. /// Return either the index or the member name of the referenced value as a
  1069. /// Value.
  1070. Value key() const;
  1071. /// Return the index of the referenced Value, or -1 if it is not an
  1072. /// arrayValue.
  1073. UInt index() const;
  1074. /// Return the member name of the referenced Value, or "" if it is not an
  1075. /// objectValue.
  1076. /// \note Avoid `c_str()` on result, as embedded zeroes are possible.
  1077. String name() const;
  1078. /// Return the member name of the referenced Value. "" if it is not an
  1079. /// objectValue.
  1080. /// \deprecated This cannot be used for UTF-8 strings, since there can be
  1081. /// embedded nulls.
  1082. JSONCPP_DEPRECATED("Use `key = name();` instead.")
  1083. char const* memberName() const;
  1084. /// Return the member name of the referenced Value, or NULL if it is not an
  1085. /// objectValue.
  1086. /// \note Better version than memberName(). Allows embedded nulls.
  1087. char const* memberName(char const** end) const;
  1088. protected:
  1089. /*! Internal utility functions to assist with implementing
  1090. * other iterator functions. The const and non-const versions
  1091. * of the "deref" protected methods expose the protected
  1092. * current_ member variable in a way that can often be
  1093. * optimized away by the compiler.
  1094. */
  1095. const Value& deref() const;
  1096. Value& deref();
  1097. void increment();
  1098. void decrement();
  1099. difference_type computeDistance(const SelfType& other) const;
  1100. bool isEqual(const SelfType& other) const;
  1101. void copy(const SelfType& other);
  1102. private:
  1103. Value::ObjectValues::iterator current_;
  1104. // Indicates that iterator is for a null value.
  1105. bool isNull_{true};
  1106. public:
  1107. // For some reason, BORLAND needs these at the end, rather
  1108. // than earlier. No idea why.
  1109. ValueIteratorBase();
  1110. explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
  1111. };
  1112. /** \brief const iterator for object and array value.
  1113. *
  1114. */
  1115. class JSON_API ValueConstIterator : public ValueIteratorBase {
  1116. friend class Value;
  1117. public:
  1118. using value_type = const Value;
  1119. // typedef unsigned int size_t;
  1120. // typedef int difference_type;
  1121. using reference = const Value&;
  1122. using pointer = const Value*;
  1123. using SelfType = ValueConstIterator;
  1124. ValueConstIterator();
  1125. ValueConstIterator(ValueIterator const& other);
  1126. private:
  1127. /*! \internal Use by Value to create an iterator.
  1128. */
  1129. explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
  1130. public:
  1131. SelfType& operator=(const ValueIteratorBase& other);
  1132. SelfType operator++(int) {
  1133. SelfType temp(*this);
  1134. ++*this;
  1135. return temp;
  1136. }
  1137. SelfType operator--(int) {
  1138. SelfType temp(*this);
  1139. --*this;
  1140. return temp;
  1141. }
  1142. SelfType& operator--() {
  1143. decrement();
  1144. return *this;
  1145. }
  1146. SelfType& operator++() {
  1147. increment();
  1148. return *this;
  1149. }
  1150. reference operator*() const { return deref(); }
  1151. pointer operator->() const { return &deref(); }
  1152. };
  1153. /** \brief Iterator for object and array value.
  1154. */
  1155. class JSON_API ValueIterator : public ValueIteratorBase {
  1156. friend class Value;
  1157. public:
  1158. using value_type = Value;
  1159. using size_t = unsigned int;
  1160. using difference_type = int;
  1161. using reference = Value&;
  1162. using pointer = Value*;
  1163. using SelfType = ValueIterator;
  1164. ValueIterator();
  1165. explicit ValueIterator(const ValueConstIterator& other);
  1166. ValueIterator(const ValueIterator& other);
  1167. private:
  1168. /*! \internal Use by Value to create an iterator.
  1169. */
  1170. explicit ValueIterator(const Value::ObjectValues::iterator& current);
  1171. public:
  1172. SelfType& operator=(const SelfType& other);
  1173. SelfType operator++(int) {
  1174. SelfType temp(*this);
  1175. ++*this;
  1176. return temp;
  1177. }
  1178. SelfType operator--(int) {
  1179. SelfType temp(*this);
  1180. --*this;
  1181. return temp;
  1182. }
  1183. SelfType& operator--() {
  1184. decrement();
  1185. return *this;
  1186. }
  1187. SelfType& operator++() {
  1188. increment();
  1189. return *this;
  1190. }
  1191. /*! The return value of non-const iterators can be
  1192. * changed, so the these functions are not const
  1193. * because the returned references/pointers can be used
  1194. * to change state of the base class.
  1195. */
  1196. reference operator*() const { return const_cast<reference>(deref()); }
  1197. pointer operator->() const { return const_cast<pointer>(&deref()); }
  1198. };
  1199. inline void swap(Value& a, Value& b) { a.swap(b); }
  1200. } // namespace Json
  1201. #pragma pack(pop)
  1202. #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  1203. #pragma warning(pop)
  1204. #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  1205. #endif // JSON_H_INCLUDED
  1206. // //////////////////////////////////////////////////////////////////////
  1207. // End of content of file: include/json/value.h
  1208. // //////////////////////////////////////////////////////////////////////
  1209. // //////////////////////////////////////////////////////////////////////
  1210. // Beginning of content of file: include/json/reader.h
  1211. // //////////////////////////////////////////////////////////////////////
  1212. // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
  1213. // Distributed under MIT license, or public domain if desired and
  1214. // recognized in your jurisdiction.
  1215. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  1216. #ifndef JSON_READER_H_INCLUDED
  1217. #define JSON_READER_H_INCLUDED
  1218. #if !defined(JSON_IS_AMALGAMATION)
  1219. #include "json_features.h"
  1220. #include "value.h"
  1221. #endif // if !defined(JSON_IS_AMALGAMATION)
  1222. #include <deque>
  1223. #include <iosfwd>
  1224. #include <istream>
  1225. #include <stack>
  1226. #include <string>
  1227. // Disable warning C4251: <data member>: <type> needs to have dll-interface to
  1228. // be used by...
  1229. #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  1230. #pragma warning(push)
  1231. #pragma warning(disable : 4251)
  1232. #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  1233. #pragma pack(push, 8)
  1234. namespace Json {
  1235. /** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a
  1236. * Value.
  1237. *
  1238. * \deprecated Use CharReader and CharReaderBuilder.
  1239. */
  1240. class JSON_API Reader {
  1241. public:
  1242. using Char = char;
  1243. using Location = const Char*;
  1244. /** \brief An error tagged with where in the JSON text it was encountered.
  1245. *
  1246. * The offsets give the [start, limit) range of bytes within the text. Note
  1247. * that this is bytes, not codepoints.
  1248. */
  1249. struct StructuredError {
  1250. ptrdiff_t offset_start;
  1251. ptrdiff_t offset_limit;
  1252. String message;
  1253. };
  1254. /** \brief Constructs a Reader allowing all features for parsing.
  1255. * \deprecated Use CharReader and CharReaderBuilder.
  1256. */
  1257. Reader();
  1258. /** \brief Constructs a Reader allowing the specified feature set for parsing.
  1259. * \deprecated Use CharReader and CharReaderBuilder.
  1260. */
  1261. Reader(const Features& features);
  1262. /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
  1263. * document.
  1264. *
  1265. * \param document UTF-8 encoded string containing the document
  1266. * to read.
  1267. * \param[out] root Contains the root value of the document if it
  1268. * was successfully parsed.
  1269. * \param collectComments \c true to collect comment and allow writing
  1270. * them back during serialization, \c false to
  1271. * discard comments. This parameter is ignored
  1272. * if Features::allowComments_ is \c false.
  1273. * \return \c true if the document was successfully parsed, \c false if an
  1274. * error occurred.
  1275. */
  1276. bool parse(const std::string& document, Value& root,
  1277. bool collectComments = true);
  1278. /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
  1279. * document.
  1280. *
  1281. * \param beginDoc Pointer on the beginning of the UTF-8 encoded
  1282. * string of the document to read.
  1283. * \param endDoc Pointer on the end of the UTF-8 encoded string
  1284. * of the document to read. Must be >= beginDoc.
  1285. * \param[out] root Contains the root value of the document if it
  1286. * was successfully parsed.
  1287. * \param collectComments \c true to collect comment and allow writing
  1288. * them back during serialization, \c false to
  1289. * discard comments. This parameter is ignored
  1290. * if Features::allowComments_ is \c false.
  1291. * \return \c true if the document was successfully parsed, \c false if an
  1292. * error occurred.
  1293. */
  1294. bool parse(const char* beginDoc, const char* endDoc, Value& root,
  1295. bool collectComments = true);
  1296. /// \brief Parse from input stream.
  1297. /// \see Json::operator>>(std::istream&, Json::Value&).
  1298. bool parse(IStream& is, Value& root, bool collectComments = true);
  1299. /** \brief Returns a user friendly string that list errors in the parsed
  1300. * document.
  1301. *
  1302. * \return Formatted error message with the list of errors with their
  1303. * location in the parsed document. An empty string is returned if no error
  1304. * occurred during parsing.
  1305. * \deprecated Use getFormattedErrorMessages() instead (typo fix).
  1306. */
  1307. JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.")
  1308. String getFormatedErrorMessages() const;
  1309. /** \brief Returns a user friendly string that list errors in the parsed
  1310. * document.
  1311. *
  1312. * \return Formatted error message with the list of errors with their
  1313. * location in the parsed document. An empty string is returned if no error
  1314. * occurred during parsing.
  1315. */
  1316. String getFormattedErrorMessages() const;
  1317. /** \brief Returns a vector of structured errors encountered while parsing.
  1318. *
  1319. * \return A (possibly empty) vector of StructuredError objects. Currently
  1320. * only one error can be returned, but the caller should tolerate multiple
  1321. * errors. This can occur if the parser recovers from a non-fatal parse
  1322. * error and then encounters additional errors.
  1323. */
  1324. std::vector<StructuredError> getStructuredErrors() const;
  1325. /** \brief Add a semantic error message.
  1326. *
  1327. * \param value JSON Value location associated with the error
  1328. * \param message The error message.
  1329. * \return \c true if the error was successfully added, \c false if the Value
  1330. * offset exceeds the document size.
  1331. */
  1332. bool pushError(const Value& value, const String& message);
  1333. /** \brief Add a semantic error message with extra context.
  1334. *
  1335. * \param value JSON Value location associated with the error
  1336. * \param message The error message.
  1337. * \param extra Additional JSON Value location to contextualize the error
  1338. * \return \c true if the error was successfully added, \c false if either
  1339. * Value offset exceeds the document size.
  1340. */
  1341. bool pushError(const Value& value, const String& message, const Value& extra);
  1342. /** \brief Return whether there are any errors.
  1343. *
  1344. * \return \c true if there are no errors to report \c false if errors have
  1345. * occurred.
  1346. */
  1347. bool good() const;
  1348. private:
  1349. enum TokenType {
  1350. tokenEndOfStream = 0,
  1351. tokenObjectBegin,
  1352. tokenObjectEnd,
  1353. tokenArrayBegin,
  1354. tokenArrayEnd,
  1355. tokenString,
  1356. tokenNumber,
  1357. tokenTrue,
  1358. tokenFalse,
  1359. tokenNull,
  1360. tokenArraySeparator,
  1361. tokenMemberSeparator,
  1362. tokenComment,
  1363. tokenError
  1364. };
  1365. class Token {
  1366. public:
  1367. TokenType type_;
  1368. Location start_;
  1369. Location end_;
  1370. };
  1371. class ErrorInfo {
  1372. public:
  1373. Token token_;
  1374. String message_;
  1375. Location extra_;
  1376. };
  1377. using Errors = std::deque<ErrorInfo>;
  1378. bool readToken(Token& token);
  1379. void skipSpaces();
  1380. bool match(const Char* pattern, int patternLength);
  1381. bool readComment();
  1382. bool readCStyleComment();
  1383. bool readCppStyleComment();
  1384. bool readString();
  1385. void readNumber();
  1386. bool readValue();
  1387. bool readObject(Token& token);
  1388. bool readArray(Token& token);
  1389. bool decodeNumber(Token& token);
  1390. bool decodeNumber(Token& token, Value& decoded);
  1391. bool decodeString(Token& token);
  1392. bool decodeString(Token& token, String& decoded);
  1393. bool decodeDouble(Token& token);
  1394. bool decodeDouble(Token& token, Value& decoded);
  1395. bool decodeUnicodeCodePoint(Token& token, Location& current, Location end,
  1396. unsigned int& unicode);
  1397. bool decodeUnicodeEscapeSequence(Token& token, Location& current,
  1398. Location end, unsigned int& unicode);
  1399. bool addError(const String& message, Token& token, Location extra = nullptr);
  1400. bool recoverFromError(TokenType skipUntilToken);
  1401. bool addErrorAndRecover(const String& message, Token& token,
  1402. TokenType skipUntilToken);
  1403. void skipUntilSpace();
  1404. Value& currentValue();
  1405. Char getNextChar();
  1406. void getLocationLineAndColumn(Location location, int& line,
  1407. int& column) const;
  1408. String getLocationLineAndColumn(Location location) const;
  1409. void addComment(Location begin, Location end, CommentPlacement placement);
  1410. void skipCommentTokens(Token& token);
  1411. static bool containsNewLine(Location begin, Location end);
  1412. static String normalizeEOL(Location begin, Location end);
  1413. using Nodes = std::stack<Value*>;
  1414. Nodes nodes_;
  1415. Errors errors_;
  1416. String document_;
  1417. Location begin_{};
  1418. Location end_{};
  1419. Location current_{};
  1420. Location lastValueEnd_{};
  1421. Value* lastValue_{};
  1422. String commentsBefore_;
  1423. Features features_;
  1424. bool collectComments_{};
  1425. }; // Reader
  1426. /** Interface for reading JSON from a char array.
  1427. */
  1428. class JSON_API CharReader {
  1429. public:
  1430. virtual ~CharReader() = default;
  1431. /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
  1432. * document. The document must be a UTF-8 encoded string containing the
  1433. * document to read.
  1434. *
  1435. * \param beginDoc Pointer on the beginning of the UTF-8 encoded string
  1436. * of the document to read.
  1437. * \param endDoc Pointer on the end of the UTF-8 encoded string of the
  1438. * document to read. Must be >= beginDoc.
  1439. * \param[out] root Contains the root value of the document if it was
  1440. * successfully parsed.
  1441. * \param[out] errs Formatted error messages (if not NULL) a user
  1442. * friendly string that lists errors in the parsed
  1443. * document.
  1444. * \return \c true if the document was successfully parsed, \c false if an
  1445. * error occurred.
  1446. */
  1447. virtual bool parse(char const* beginDoc, char const* endDoc, Value* root,
  1448. String* errs) = 0;
  1449. class JSON_API Factory {
  1450. public:
  1451. virtual ~Factory() = default;
  1452. /** \brief Allocate a CharReader via operator new().
  1453. * \throw std::exception if something goes wrong (e.g. invalid settings)
  1454. */
  1455. virtual CharReader* newCharReader() const = 0;
  1456. }; // Factory
  1457. }; // CharReader
  1458. /** \brief Build a CharReader implementation.
  1459. *
  1460. * Usage:
  1461. * \code
  1462. * using namespace Json;
  1463. * CharReaderBuilder builder;
  1464. * builder["collectComments"] = false;
  1465. * Value value;
  1466. * String errs;
  1467. * bool ok = parseFromStream(builder, std::cin, &value, &errs);
  1468. * \endcode
  1469. */
  1470. class JSON_API CharReaderBuilder : public CharReader::Factory {
  1471. public:
  1472. // Note: We use a Json::Value so that we can add data-members to this class
  1473. // without a major version bump.
  1474. /** Configuration of this builder.
  1475. * These are case-sensitive.
  1476. * Available settings (case-sensitive):
  1477. * - `"collectComments": false or true`
  1478. * - true to collect comment and allow writing them back during
  1479. * serialization, false to discard comments. This parameter is ignored
  1480. * if allowComments is false.
  1481. * - `"allowComments": false or true`
  1482. * - true if comments are allowed.
  1483. * - `"allowTrailingCommas": false or true`
  1484. * - true if trailing commas in objects and arrays are allowed.
  1485. * - `"strictRoot": false or true`
  1486. * - true if root must be either an array or an object value
  1487. * - `"allowDroppedNullPlaceholders": false or true`
  1488. * - true if dropped null placeholders are allowed. (See
  1489. * StreamWriterBuilder.)
  1490. * - `"allowNumericKeys": false or true`
  1491. * - true if numeric object keys are allowed.
  1492. * - `"allowSingleQuotes": false or true`
  1493. * - true if '' are allowed for strings (both keys and values)
  1494. * - `"stackLimit": integer`
  1495. * - Exceeding stackLimit (recursive depth of `readValue()`) will cause an
  1496. * exception.
  1497. * - This is a security issue (seg-faults caused by deeply nested JSON), so
  1498. * the default is low.
  1499. * - `"failIfExtra": false or true`
  1500. * - If true, `parse()` returns false when extra non-whitespace trails the
  1501. * JSON value in the input string.
  1502. * - `"rejectDupKeys": false or true`
  1503. * - If true, `parse()` returns false when a key is duplicated within an
  1504. * object.
  1505. * - `"allowSpecialFloats": false or true`
  1506. * - If true, special float values (NaNs and infinities) are allowed and
  1507. * their values are lossfree restorable.
  1508. * - `"skipBom": false or true`
  1509. * - If true, if the input starts with the Unicode byte order mark (BOM),
  1510. * it is skipped.
  1511. *
  1512. * You can examine 'settings_` yourself to see the defaults. You can also
  1513. * write and read them just like any JSON Value.
  1514. * \sa setDefaults()
  1515. */
  1516. Json::Value settings_;
  1517. CharReaderBuilder();
  1518. ~CharReaderBuilder() override;
  1519. CharReader* newCharReader() const override;
  1520. /** \return true if 'settings' are legal and consistent;
  1521. * otherwise, indicate bad settings via 'invalid'.
  1522. */
  1523. bool validate(Json::Value* invalid) const;
  1524. /** A simple way to update a specific setting.
  1525. */
  1526. Value& operator[](const String& key);
  1527. /** Called by ctor, but you can use this to reset settings_.
  1528. * \pre 'settings' != NULL (but Json::null is fine)
  1529. * \remark Defaults:
  1530. * \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults
  1531. */
  1532. static void setDefaults(Json::Value* settings);
  1533. /** Same as old Features::strictMode().
  1534. * \pre 'settings' != NULL (but Json::null is fine)
  1535. * \remark Defaults:
  1536. * \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode
  1537. */
  1538. static void strictMode(Json::Value* settings);
  1539. };
  1540. /** Consume entire stream and use its begin/end.
  1541. * Someday we might have a real StreamReader, but for now this
  1542. * is convenient.
  1543. */
  1544. bool JSON_API parseFromStream(CharReader::Factory const&, IStream&, Value* root,
  1545. String* errs);
  1546. /** \brief Read from 'sin' into 'root'.
  1547. *
  1548. * Always keep comments from the input JSON.
  1549. *
  1550. * This can be used to read a file into a particular sub-object.
  1551. * For example:
  1552. * \code
  1553. * Json::Value root;
  1554. * cin >> root["dir"]["file"];
  1555. * cout << root;
  1556. * \endcode
  1557. * Result:
  1558. * \verbatim
  1559. * {
  1560. * "dir": {
  1561. * "file": {
  1562. * // The input stream JSON would be nested here.
  1563. * }
  1564. * }
  1565. * }
  1566. * \endverbatim
  1567. * \throw std::exception on parse error.
  1568. * \see Json::operator<<()
  1569. */
  1570. JSON_API IStream& operator>>(IStream&, Value&);
  1571. } // namespace Json
  1572. #pragma pack(pop)
  1573. #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  1574. #pragma warning(pop)
  1575. #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  1576. #endif // JSON_READER_H_INCLUDED
  1577. // //////////////////////////////////////////////////////////////////////
  1578. // End of content of file: include/json/reader.h
  1579. // //////////////////////////////////////////////////////////////////////
  1580. // //////////////////////////////////////////////////////////////////////
  1581. // Beginning of content of file: include/json/writer.h
  1582. // //////////////////////////////////////////////////////////////////////
  1583. // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
  1584. // Distributed under MIT license, or public domain if desired and
  1585. // recognized in your jurisdiction.
  1586. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  1587. #ifndef JSON_WRITER_H_INCLUDED
  1588. #define JSON_WRITER_H_INCLUDED
  1589. #if !defined(JSON_IS_AMALGAMATION)
  1590. #include "value.h"
  1591. #endif // if !defined(JSON_IS_AMALGAMATION)
  1592. #include <ostream>
  1593. #include <string>
  1594. #include <vector>
  1595. // Disable warning C4251: <data member>: <type> needs to have dll-interface to
  1596. // be used by...
  1597. #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) && defined(_MSC_VER)
  1598. #pragma warning(push)
  1599. #pragma warning(disable : 4251)
  1600. #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  1601. #pragma pack(push, 8)
  1602. namespace Json {
  1603. class Value;
  1604. /**
  1605. *
  1606. * Usage:
  1607. * \code
  1608. * using namespace Json;
  1609. * void writeToStdout(StreamWriter::Factory const& factory, Value const& value)
  1610. * { std::unique_ptr<StreamWriter> const writer( factory.newStreamWriter());
  1611. * writer->write(value, &std::cout);
  1612. * std::cout << std::endl; // add lf and flush
  1613. * }
  1614. * \endcode
  1615. */
  1616. class JSON_API StreamWriter {
  1617. protected:
  1618. OStream* sout_; // not owned; will not delete
  1619. public:
  1620. StreamWriter();
  1621. virtual ~StreamWriter();
  1622. /** Write Value into document as configured in sub-class.
  1623. * Do not take ownership of sout, but maintain a reference during function.
  1624. * \pre sout != NULL
  1625. * \return zero on success (For now, we always return zero, so check the
  1626. * stream instead.) \throw std::exception possibly, depending on
  1627. * configuration
  1628. */
  1629. virtual int write(Value const& root, OStream* sout) = 0;
  1630. /** \brief A simple abstract factory.
  1631. */
  1632. class JSON_API Factory {
  1633. public:
  1634. virtual ~Factory();
  1635. /** \brief Allocate a CharReader via operator new().
  1636. * \throw std::exception if something goes wrong (e.g. invalid settings)
  1637. */
  1638. virtual StreamWriter* newStreamWriter() const = 0;
  1639. }; // Factory
  1640. }; // StreamWriter
  1641. /** \brief Write into stringstream, then return string, for convenience.
  1642. * A StreamWriter will be created from the factory, used, and then deleted.
  1643. */
  1644. String JSON_API writeString(StreamWriter::Factory const& factory,
  1645. Value const& root);
  1646. /** \brief Build a StreamWriter implementation.
  1647. * Usage:
  1648. * \code
  1649. * using namespace Json;
  1650. * Value value = ...;
  1651. * StreamWriterBuilder builder;
  1652. * builder["commentStyle"] = "None";
  1653. * builder["indentation"] = " "; // or whatever you like
  1654. * std::unique_ptr<Json::StreamWriter> writer(
  1655. * builder.newStreamWriter());
  1656. * writer->write(value, &std::cout);
  1657. * std::cout << std::endl; // add lf and flush
  1658. * \endcode
  1659. */
  1660. class JSON_API StreamWriterBuilder : public StreamWriter::Factory {
  1661. public:
  1662. // Note: We use a Json::Value so that we can add data-members to this class
  1663. // without a major version bump.
  1664. /** Configuration of this builder.
  1665. * Available settings (case-sensitive):
  1666. * - "commentStyle": "None" or "All"
  1667. * - "indentation": "<anything>".
  1668. * - Setting this to an empty string also omits newline characters.
  1669. * - "enableYAMLCompatibility": false or true
  1670. * - slightly change the whitespace around colons
  1671. * - "dropNullPlaceholders": false or true
  1672. * - Drop the "null" string from the writer's output for nullValues.
  1673. * Strictly speaking, this is not valid JSON. But when the output is being
  1674. * fed to a browser's JavaScript, it makes for smaller output and the
  1675. * browser can handle the output just fine.
  1676. * - "useSpecialFloats": false or true
  1677. * - If true, outputs non-finite floating point values in the following way:
  1678. * NaN values as "NaN", positive infinity as "Infinity", and negative
  1679. * infinity as "-Infinity".
  1680. * - "precision": int
  1681. * - Number of precision digits for formatting of real values.
  1682. * - "precisionType": "significant"(default) or "decimal"
  1683. * - Type of precision for formatting of real values.
  1684. * - "emitUTF8": false or true
  1685. * - If true, outputs raw UTF8 strings instead of escaping them.
  1686. * You can examine 'settings_` yourself
  1687. * to see the defaults. You can also write and read them just like any
  1688. * JSON Value.
  1689. * \sa setDefaults()
  1690. */
  1691. Json::Value settings_;
  1692. StreamWriterBuilder();
  1693. ~StreamWriterBuilder() override;
  1694. /**
  1695. * \throw std::exception if something goes wrong (e.g. invalid settings)
  1696. */
  1697. StreamWriter* newStreamWriter() const override;
  1698. /** \return true if 'settings' are legal and consistent;
  1699. * otherwise, indicate bad settings via 'invalid'.
  1700. */
  1701. bool validate(Json::Value* invalid) const;
  1702. /** A simple way to update a specific setting.
  1703. */
  1704. Value& operator[](const String& key);
  1705. /** Called by ctor, but you can use this to reset settings_.
  1706. * \pre 'settings' != NULL (but Json::null is fine)
  1707. * \remark Defaults:
  1708. * \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults
  1709. */
  1710. static void setDefaults(Json::Value* settings);
  1711. };
  1712. /** \brief Abstract class for writers.
  1713. * \deprecated Use StreamWriter. (And really, this is an implementation detail.)
  1714. */
  1715. class JSON_API Writer {
  1716. public:
  1717. virtual ~Writer();
  1718. virtual String write(const Value& root) = 0;
  1719. };
  1720. /** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format
  1721. *without formatting (not human friendly).
  1722. *
  1723. * The JSON document is written in a single line. It is not intended for 'human'
  1724. *consumption,
  1725. * but may be useful to support feature such as RPC where bandwidth is limited.
  1726. * \sa Reader, Value
  1727. * \deprecated Use StreamWriterBuilder.
  1728. */
  1729. #if defined(_MSC_VER)
  1730. #pragma warning(push)
  1731. #pragma warning(disable : 4996) // Deriving from deprecated class
  1732. #endif
  1733. class JSON_API FastWriter
  1734. : public Writer {
  1735. public:
  1736. FastWriter();
  1737. ~FastWriter() override = default;
  1738. void enableYAMLCompatibility();
  1739. /** \brief Drop the "null" string from the writer's output for nullValues.
  1740. * Strictly speaking, this is not valid JSON. But when the output is being
  1741. * fed to a browser's JavaScript, it makes for smaller output and the
  1742. * browser can handle the output just fine.
  1743. */
  1744. void dropNullPlaceholders();
  1745. void omitEndingLineFeed();
  1746. public: // overridden from Writer
  1747. String write(const Value& root) override;
  1748. private:
  1749. void writeValue(const Value& value);
  1750. String document_;
  1751. bool yamlCompatibilityEnabled_{false};
  1752. bool dropNullPlaceholders_{false};
  1753. bool omitEndingLineFeed_{false};
  1754. };
  1755. #if defined(_MSC_VER)
  1756. #pragma warning(pop)
  1757. #endif
  1758. /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
  1759. *human friendly way.
  1760. *
  1761. * The rules for line break and indent are as follow:
  1762. * - Object value:
  1763. * - if empty then print {} without indent and line break
  1764. * - if not empty the print '{', line break & indent, print one value per
  1765. *line
  1766. * and then unindent and line break and print '}'.
  1767. * - Array value:
  1768. * - if empty then print [] without indent and line break
  1769. * - if the array contains no object value, empty array or some other value
  1770. *types,
  1771. * and all the values fit on one lines, then print the array on a single
  1772. *line.
  1773. * - otherwise, it the values do not fit on one line, or the array contains
  1774. * object or non empty array, then print one value per line.
  1775. *
  1776. * If the Value have comments then they are outputed according to their
  1777. *#CommentPlacement.
  1778. *
  1779. * \sa Reader, Value, Value::setComment()
  1780. * \deprecated Use StreamWriterBuilder.
  1781. */
  1782. #if defined(_MSC_VER)
  1783. #pragma warning(push)
  1784. #pragma warning(disable : 4996) // Deriving from deprecated class
  1785. #endif
  1786. class JSON_API
  1787. StyledWriter : public Writer {
  1788. public:
  1789. StyledWriter();
  1790. ~StyledWriter() override = default;
  1791. public: // overridden from Writer
  1792. /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
  1793. * \param root Value to serialize.
  1794. * \return String containing the JSON document that represents the root value.
  1795. */
  1796. String write(const Value& root) override;
  1797. private:
  1798. void writeValue(const Value& value);
  1799. void writeArrayValue(const Value& value);
  1800. bool isMultilineArray(const Value& value);
  1801. void pushValue(const String& value);
  1802. void writeIndent();
  1803. void writeWithIndent(const String& value);
  1804. void indent();
  1805. void unindent();
  1806. void writeCommentBeforeValue(const Value& root);
  1807. void writeCommentAfterValueOnSameLine(const Value& root);
  1808. static bool hasCommentForValue(const Value& value);
  1809. static String normalizeEOL(const String& text);
  1810. using ChildValues = std::vector<String>;
  1811. ChildValues childValues_;
  1812. String document_;
  1813. String indentString_;
  1814. unsigned int rightMargin_{74};
  1815. unsigned int indentSize_{3};
  1816. bool addChildValues_{false};
  1817. };
  1818. #if defined(_MSC_VER)
  1819. #pragma warning(pop)
  1820. #endif
  1821. /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
  1822. human friendly way,
  1823. to a stream rather than to a string.
  1824. *
  1825. * The rules for line break and indent are as follow:
  1826. * - Object value:
  1827. * - if empty then print {} without indent and line break
  1828. * - if not empty the print '{', line break & indent, print one value per
  1829. line
  1830. * and then unindent and line break and print '}'.
  1831. * - Array value:
  1832. * - if empty then print [] without indent and line break
  1833. * - if the array contains no object value, empty array or some other value
  1834. types,
  1835. * and all the values fit on one lines, then print the array on a single
  1836. line.
  1837. * - otherwise, it the values do not fit on one line, or the array contains
  1838. * object or non empty array, then print one value per line.
  1839. *
  1840. * If the Value have comments then they are outputed according to their
  1841. #CommentPlacement.
  1842. *
  1843. * \sa Reader, Value, Value::setComment()
  1844. * \deprecated Use StreamWriterBuilder.
  1845. */
  1846. #if defined(_MSC_VER)
  1847. #pragma warning(push)
  1848. #pragma warning(disable : 4996) // Deriving from deprecated class
  1849. #endif
  1850. class JSON_API
  1851. StyledStreamWriter {
  1852. public:
  1853. /**
  1854. * \param indentation Each level will be indented by this amount extra.
  1855. */
  1856. StyledStreamWriter(String indentation = "\t");
  1857. ~StyledStreamWriter() = default;
  1858. public:
  1859. /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
  1860. * \param out Stream to write to. (Can be ostringstream, e.g.)
  1861. * \param root Value to serialize.
  1862. * \note There is no point in deriving from Writer, since write() should not
  1863. * return a value.
  1864. */
  1865. void write(OStream& out, const Value& root);
  1866. private:
  1867. void writeValue(const Value& value);
  1868. void writeArrayValue(const Value& value);
  1869. bool isMultilineArray(const Value& value);
  1870. void pushValue(const String& value);
  1871. void writeIndent();
  1872. void writeWithIndent(const String& value);
  1873. void indent();
  1874. void unindent();
  1875. void writeCommentBeforeValue(const Value& root);
  1876. void writeCommentAfterValueOnSameLine(const Value& root);
  1877. static bool hasCommentForValue(const Value& value);
  1878. static String normalizeEOL(const String& text);
  1879. using ChildValues = std::vector<String>;
  1880. ChildValues childValues_;
  1881. OStream* document_;
  1882. String indentString_;
  1883. unsigned int rightMargin_{74};
  1884. String indentation_;
  1885. bool addChildValues_ : 1;
  1886. bool indented_ : 1;
  1887. };
  1888. #if defined(_MSC_VER)
  1889. #pragma warning(pop)
  1890. #endif
  1891. #if defined(JSON_HAS_INT64)
  1892. String JSON_API valueToString(Int value);
  1893. String JSON_API valueToString(UInt value);
  1894. #endif // if defined(JSON_HAS_INT64)
  1895. String JSON_API valueToString(LargestInt value);
  1896. String JSON_API valueToString(LargestUInt value);
  1897. String JSON_API valueToString(
  1898. double value, unsigned int precision = Value::defaultRealPrecision,
  1899. PrecisionType precisionType = PrecisionType::significantDigits);
  1900. String JSON_API valueToString(bool value);
  1901. String JSON_API valueToQuotedString(const char* value);
  1902. /// \brief Output using the StyledStreamWriter.
  1903. /// \see Json::operator>>()
  1904. JSON_API OStream& operator<<(OStream&, const Value& root);
  1905. } // namespace Json
  1906. #pragma pack(pop)
  1907. #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  1908. #pragma warning(pop)
  1909. #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  1910. #endif // JSON_WRITER_H_INCLUDED
  1911. // //////////////////////////////////////////////////////////////////////
  1912. // End of content of file: include/json/writer.h
  1913. // //////////////////////////////////////////////////////////////////////
  1914. // //////////////////////////////////////////////////////////////////////
  1915. // Beginning of content of file: include/json/assertions.h
  1916. // //////////////////////////////////////////////////////////////////////
  1917. // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
  1918. // Distributed under MIT license, or public domain if desired and
  1919. // recognized in your jurisdiction.
  1920. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  1921. #ifndef JSON_ASSERTIONS_H_INCLUDED
  1922. #define JSON_ASSERTIONS_H_INCLUDED
  1923. #include <cstdlib>
  1924. #include <sstream>
  1925. #if !defined(JSON_IS_AMALGAMATION)
  1926. #include "config.h"
  1927. #endif // if !defined(JSON_IS_AMALGAMATION)
  1928. /** It should not be possible for a maliciously designed file to
  1929. * cause an abort() or seg-fault, so these macros are used only
  1930. * for pre-condition violations and internal logic errors.
  1931. */
  1932. #if JSON_USE_EXCEPTION
  1933. // @todo <= add detail about condition in exception
  1934. #define JSON_ASSERT(condition) \
  1935. do { \
  1936. if (!(condition)) { \
  1937. Json::throwLogicError("assert json failed"); \
  1938. } \
  1939. } while (0)
  1940. #define JSON_FAIL_MESSAGE(message) \
  1941. do { \
  1942. OStringStream oss; \
  1943. oss << message; \
  1944. Json::throwLogicError(oss.str()); \
  1945. abort(); \
  1946. } while (0)
  1947. #else // JSON_USE_EXCEPTION
  1948. #define JSON_ASSERT(condition) assert(condition)
  1949. // The call to assert() will show the failure message in debug builds. In
  1950. // release builds we abort, for a core-dump or debugger.
  1951. #define JSON_FAIL_MESSAGE(message) \
  1952. { \
  1953. OStringStream oss; \
  1954. oss << message; \
  1955. assert(false && oss.str().c_str()); \
  1956. abort(); \
  1957. }
  1958. #endif
  1959. #define JSON_ASSERT_MESSAGE(condition, message) \
  1960. do { \
  1961. if (!(condition)) { \
  1962. JSON_FAIL_MESSAGE(message); \
  1963. } \
  1964. } while (0)
  1965. #endif // JSON_ASSERTIONS_H_INCLUDED
  1966. // //////////////////////////////////////////////////////////////////////
  1967. // End of content of file: include/json/assertions.h
  1968. // //////////////////////////////////////////////////////////////////////
  1969. #endif //ifndef JSON_AMALGAMATED_H_INCLUDED