json.h 71 KB

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