2
0

json.h 78 KB

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