picojson.h 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. /*
  2. * Copyright 2009-2010 Cybozu Labs, Inc.
  3. * Copyright 2011-2014 Kazuho Oku
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice,
  10. * this list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form must reproduce the above copyright notice,
  13. * this list of conditions and the following disclaimer in the documentation
  14. * and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  19. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  20. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  21. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  22. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  23. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  24. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  25. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  26. * POSSIBILITY OF SUCH DAMAGE.
  27. */
  28. #ifndef picojson_h
  29. #define picojson_h
  30. #include <algorithm>
  31. #include <cstdio>
  32. #include <cstdlib>
  33. #include <cstring>
  34. #include <cstddef>
  35. #include <iostream>
  36. #include <iterator>
  37. #include <limits>
  38. #include <map>
  39. #include <stdexcept>
  40. #include <string>
  41. #include <vector>
  42. #include <utility>
  43. // for isnan/isinf
  44. #if __cplusplus >= 201103L
  45. #include <cmath>
  46. #else
  47. extern "C" {
  48. #ifdef _MSC_VER
  49. #include <float.h>
  50. #elif defined(__INTEL_COMPILER)
  51. #include <mathimf.h>
  52. #else
  53. #include <math.h>
  54. #endif
  55. }
  56. #endif
  57. #ifndef PICOJSON_USE_RVALUE_REFERENCE
  58. #if (defined(__cpp_rvalue_references) && __cpp_rvalue_references >= 200610) || (defined(_MSC_VER) && _MSC_VER >= 1600)
  59. #define PICOJSON_USE_RVALUE_REFERENCE 1
  60. #else
  61. #define PICOJSON_USE_RVALUE_REFERENCE 0
  62. #endif
  63. #endif // PICOJSON_USE_RVALUE_REFERENCE
  64. #ifndef PICOJSON_NOEXCEPT
  65. #if PICOJSON_USE_RVALUE_REFERENCE
  66. #define PICOJSON_NOEXCEPT noexcept
  67. #else
  68. #define PICOJSON_NOEXCEPT throw()
  69. #endif
  70. #endif
  71. // experimental support for int64_t (see README.mkdn for detail)
  72. #ifdef PICOJSON_USE_INT64
  73. #ifndef __STDC_FORMAT_MACROS
  74. #define __STDC_FORMAT_MACROS
  75. #endif
  76. #include <cerrno>
  77. #if __cplusplus >= 201103L
  78. #include <cinttypes>
  79. #else
  80. extern "C" {
  81. #include <inttypes.h>
  82. }
  83. #endif
  84. #endif
  85. // to disable the use of localeconv(3), set PICOJSON_USE_LOCALE to 0
  86. #ifndef PICOJSON_USE_LOCALE
  87. #define PICOJSON_USE_LOCALE 1
  88. #endif
  89. #if PICOJSON_USE_LOCALE
  90. extern "C" {
  91. #include <locale.h>
  92. }
  93. #endif
  94. #ifndef PICOJSON_ASSERT
  95. #define PICOJSON_ASSERT(e) \
  96. do { \
  97. if (!(e)) \
  98. throw std::runtime_error(#e); \
  99. } while (0)
  100. #endif
  101. #ifdef _MSC_VER
  102. #define SNPRINTF _snprintf_s
  103. #pragma warning(push)
  104. #pragma warning(disable : 4244) // conversion from int to char
  105. #pragma warning(disable : 4127) // conditional expression is constant
  106. #pragma warning(disable : 4702) // unreachable code
  107. #else
  108. #define SNPRINTF snprintf
  109. #endif
  110. namespace picojson {
  111. enum {
  112. null_type,
  113. boolean_type,
  114. number_type,
  115. string_type,
  116. array_type,
  117. object_type
  118. #ifdef PICOJSON_USE_INT64
  119. ,
  120. int64_type
  121. #endif
  122. };
  123. enum { INDENT_WIDTH = 2 };
  124. struct null {};
  125. class value {
  126. public:
  127. typedef std::vector<value> array;
  128. typedef std::map<std::string, value> object;
  129. union _storage {
  130. bool boolean_;
  131. double number_;
  132. #ifdef PICOJSON_USE_INT64
  133. int64_t int64_;
  134. #endif
  135. std::string *string_;
  136. array *array_;
  137. object *object_;
  138. };
  139. protected:
  140. int type_;
  141. _storage u_;
  142. public:
  143. value();
  144. value(int type, bool);
  145. explicit value(bool b);
  146. #ifdef PICOJSON_USE_INT64
  147. explicit value(int64_t i);
  148. #endif
  149. explicit value(double n);
  150. explicit value(const std::string &s);
  151. explicit value(const array &a);
  152. explicit value(const object &o);
  153. #if PICOJSON_USE_RVALUE_REFERENCE
  154. explicit value(std::string &&s);
  155. explicit value(array &&a);
  156. explicit value(object &&o);
  157. #endif
  158. explicit value(const char *s);
  159. value(const char *s, size_t len);
  160. ~value();
  161. value(const value &x);
  162. value &operator=(const value &x);
  163. #if PICOJSON_USE_RVALUE_REFERENCE
  164. value(value &&x) PICOJSON_NOEXCEPT;
  165. value &operator=(value &&x) PICOJSON_NOEXCEPT;
  166. #endif
  167. void swap(value &x) PICOJSON_NOEXCEPT;
  168. template <typename T> bool is() const;
  169. template <typename T> const T &get() const;
  170. template <typename T> T &get();
  171. template <typename T> void set(const T &);
  172. #if PICOJSON_USE_RVALUE_REFERENCE
  173. template <typename T> void set(T &&);
  174. #endif
  175. bool evaluate_as_boolean() const;
  176. const value &get(const size_t idx) const;
  177. const value &get(const std::string &key) const;
  178. value &get(const size_t idx);
  179. value &get(const std::string &key);
  180. bool contains(const size_t idx) const;
  181. bool contains(const std::string &key) const;
  182. std::string to_str() const;
  183. template <typename Iter> void serialize(Iter os, bool prettify = false) const;
  184. std::string serialize(bool prettify = false) const;
  185. private:
  186. template <typename T> value(const T *); // intentionally defined to block implicit conversion of pointer to bool
  187. template <typename Iter> static void _indent(Iter os, int indent);
  188. template <typename Iter> void _serialize(Iter os, int indent) const;
  189. std::string _serialize(int indent) const;
  190. void clear();
  191. };
  192. typedef value::array array;
  193. typedef value::object object;
  194. inline value::value() : type_(null_type), u_() {
  195. }
  196. inline value::value(int type, bool) : type_(type), u_() {
  197. switch (type) {
  198. #define INIT(p, v) \
  199. case p##type: \
  200. u_.p = v; \
  201. break
  202. INIT(boolean_, false);
  203. INIT(number_, 0.0);
  204. #ifdef PICOJSON_USE_INT64
  205. INIT(int64_, 0);
  206. #endif
  207. INIT(string_, new std::string());
  208. INIT(array_, new array());
  209. INIT(object_, new object());
  210. #undef INIT
  211. default:
  212. break;
  213. }
  214. }
  215. inline value::value(bool b) : type_(boolean_type), u_() {
  216. u_.boolean_ = b;
  217. }
  218. #ifdef PICOJSON_USE_INT64
  219. inline value::value(int64_t i) : type_(int64_type), u_() {
  220. u_.int64_ = i;
  221. }
  222. #endif
  223. inline value::value(double n) : type_(number_type), u_() {
  224. if (
  225. #if defined(_MSC_VER) && !defined(__clang__)
  226. !_finite(n)
  227. #elif __cplusplus >= 201103L
  228. std::isnan(n) || std::isinf(n)
  229. #else
  230. isnan(n) || isinf(n)
  231. #endif
  232. ) {
  233. throw std::overflow_error("");
  234. }
  235. u_.number_ = n;
  236. }
  237. inline value::value(const std::string &s) : type_(string_type), u_() {
  238. u_.string_ = new std::string(s);
  239. }
  240. inline value::value(const array &a) : type_(array_type), u_() {
  241. u_.array_ = new array(a);
  242. }
  243. inline value::value(const object &o) : type_(object_type), u_() {
  244. u_.object_ = new object(o);
  245. }
  246. #if PICOJSON_USE_RVALUE_REFERENCE
  247. inline value::value(std::string &&s) : type_(string_type), u_() {
  248. u_.string_ = new std::string(std::move(s));
  249. }
  250. inline value::value(array &&a) : type_(array_type), u_() {
  251. u_.array_ = new array(std::move(a));
  252. }
  253. inline value::value(object &&o) : type_(object_type), u_() {
  254. u_.object_ = new object(std::move(o));
  255. }
  256. #endif
  257. inline value::value(const char *s) : type_(string_type), u_() {
  258. u_.string_ = new std::string(s);
  259. }
  260. inline value::value(const char *s, size_t len) : type_(string_type), u_() {
  261. u_.string_ = new std::string(s, len);
  262. }
  263. inline void value::clear() {
  264. switch (type_) {
  265. #define DEINIT(p) \
  266. case p##type: \
  267. delete u_.p; \
  268. break
  269. DEINIT(string_);
  270. DEINIT(array_);
  271. DEINIT(object_);
  272. #undef DEINIT
  273. default:
  274. break;
  275. }
  276. }
  277. inline value::~value() {
  278. clear();
  279. }
  280. inline value::value(const value &x) : type_(x.type_), u_() {
  281. switch (type_) {
  282. #define INIT(p, v) \
  283. case p##type: \
  284. u_.p = v; \
  285. break
  286. INIT(string_, new std::string(*x.u_.string_));
  287. INIT(array_, new array(*x.u_.array_));
  288. INIT(object_, new object(*x.u_.object_));
  289. #undef INIT
  290. default:
  291. u_ = x.u_;
  292. break;
  293. }
  294. }
  295. inline value &value::operator=(const value &x) {
  296. if (this != &x) {
  297. value t(x);
  298. swap(t);
  299. }
  300. return *this;
  301. }
  302. #if PICOJSON_USE_RVALUE_REFERENCE
  303. inline value::value(value &&x) PICOJSON_NOEXCEPT : type_(null_type), u_() {
  304. swap(x);
  305. }
  306. inline value &value::operator=(value &&x) PICOJSON_NOEXCEPT {
  307. swap(x);
  308. return *this;
  309. }
  310. #endif
  311. inline void value::swap(value &x) PICOJSON_NOEXCEPT {
  312. std::swap(type_, x.type_);
  313. std::swap(u_, x.u_);
  314. }
  315. #define IS(ctype, jtype) \
  316. template <> inline bool value::is<ctype>() const { \
  317. return type_ == jtype##_type; \
  318. }
  319. IS(null, null)
  320. IS(bool, boolean)
  321. #ifdef PICOJSON_USE_INT64
  322. IS(int64_t, int64)
  323. #endif
  324. IS(std::string, string)
  325. IS(array, array)
  326. IS(object, object)
  327. #undef IS
  328. template <> inline bool value::is<double>() const {
  329. return type_ == number_type
  330. #ifdef PICOJSON_USE_INT64
  331. || type_ == int64_type
  332. #endif
  333. ;
  334. }
  335. #define GET(ctype, var) \
  336. template <> inline const ctype &value::get<ctype>() const { \
  337. PICOJSON_ASSERT("type mismatch! call is<type>() before get<type>()" && is<ctype>()); \
  338. return var; \
  339. } \
  340. template <> inline ctype &value::get<ctype>() { \
  341. PICOJSON_ASSERT("type mismatch! call is<type>() before get<type>()" && is<ctype>()); \
  342. return var; \
  343. }
  344. GET(bool, u_.boolean_)
  345. GET(std::string, *u_.string_)
  346. GET(array, *u_.array_)
  347. GET(object, *u_.object_)
  348. #ifdef PICOJSON_USE_INT64
  349. GET(double,
  350. (type_ == int64_type && (const_cast<value *>(this)->type_ = number_type, const_cast<value *>(this)->u_.number_ = u_.int64_),
  351. u_.number_))
  352. GET(int64_t, u_.int64_)
  353. #else
  354. GET(double, u_.number_)
  355. #endif
  356. #undef GET
  357. #define SET(ctype, jtype, setter) \
  358. template <> inline void value::set<ctype>(const ctype &_val) { \
  359. clear(); \
  360. type_ = jtype##_type; \
  361. setter \
  362. }
  363. SET(bool, boolean, u_.boolean_ = _val;)
  364. SET(std::string, string, u_.string_ = new std::string(_val);)
  365. SET(array, array, u_.array_ = new array(_val);)
  366. SET(object, object, u_.object_ = new object(_val);)
  367. SET(double, number, u_.number_ = _val;)
  368. #ifdef PICOJSON_USE_INT64
  369. SET(int64_t, int64, u_.int64_ = _val;)
  370. #endif
  371. #undef SET
  372. #if PICOJSON_USE_RVALUE_REFERENCE
  373. #define MOVESET(ctype, jtype, setter) \
  374. template <> inline void value::set<ctype>(ctype && _val) { \
  375. clear(); \
  376. type_ = jtype##_type; \
  377. setter \
  378. }
  379. MOVESET(std::string, string, u_.string_ = new std::string(std::move(_val));)
  380. MOVESET(array, array, u_.array_ = new array(std::move(_val));)
  381. MOVESET(object, object, u_.object_ = new object(std::move(_val));)
  382. #undef MOVESET
  383. #endif
  384. inline bool value::evaluate_as_boolean() const {
  385. switch (type_) {
  386. case null_type:
  387. return false;
  388. case boolean_type:
  389. return u_.boolean_;
  390. case number_type:
  391. return u_.number_ != 0;
  392. #ifdef PICOJSON_USE_INT64
  393. case int64_type:
  394. return u_.int64_ != 0;
  395. #endif
  396. case string_type:
  397. return !u_.string_->empty();
  398. default:
  399. return true;
  400. }
  401. }
  402. inline const value &value::get(const size_t idx) const {
  403. static value s_null;
  404. PICOJSON_ASSERT(is<array>());
  405. return idx < u_.array_->size() ? (*u_.array_)[idx] : s_null;
  406. }
  407. inline value &value::get(const size_t idx) {
  408. static value s_null;
  409. PICOJSON_ASSERT(is<array>());
  410. return idx < u_.array_->size() ? (*u_.array_)[idx] : s_null;
  411. }
  412. inline const value &value::get(const std::string &key) const {
  413. static value s_null;
  414. PICOJSON_ASSERT(is<object>());
  415. object::const_iterator i = u_.object_->find(key);
  416. return i != u_.object_->end() ? i->second : s_null;
  417. }
  418. inline value &value::get(const std::string &key) {
  419. static value s_null;
  420. PICOJSON_ASSERT(is<object>());
  421. object::iterator i = u_.object_->find(key);
  422. return i != u_.object_->end() ? i->second : s_null;
  423. }
  424. inline bool value::contains(const size_t idx) const {
  425. PICOJSON_ASSERT(is<array>());
  426. return idx < u_.array_->size();
  427. }
  428. inline bool value::contains(const std::string &key) const {
  429. PICOJSON_ASSERT(is<object>());
  430. object::const_iterator i = u_.object_->find(key);
  431. return i != u_.object_->end();
  432. }
  433. inline std::string value::to_str() const {
  434. switch (type_) {
  435. case null_type:
  436. return "null";
  437. case boolean_type:
  438. return u_.boolean_ ? "true" : "false";
  439. #ifdef PICOJSON_USE_INT64
  440. case int64_type: {
  441. char buf[sizeof("-9223372036854775808")];
  442. #if defined(__APPLE__)
  443. SNPRINTF(buf, sizeof(buf), "%lld", u_.int64_);
  444. #else
  445. SNPRINTF(buf, sizeof(buf), "%" PRId64, u_.int64_);
  446. #endif
  447. return buf;
  448. }
  449. #endif
  450. case number_type: {
  451. char buf[256];
  452. double tmp;
  453. SNPRINTF(buf, sizeof(buf), fabs(u_.number_) < (1ULL << 53) && modf(u_.number_, &tmp) == 0 ? "%.f" : "%.17g", u_.number_);
  454. #if PICOJSON_USE_LOCALE
  455. char *decimal_point = localeconv()->decimal_point;
  456. if (strcmp(decimal_point, ".") != 0) {
  457. size_t decimal_point_len = strlen(decimal_point);
  458. for (char *p = buf; *p != '\0'; ++p) {
  459. if (strncmp(p, decimal_point, decimal_point_len) == 0) {
  460. return std::string(buf, p) + "." + (p + decimal_point_len);
  461. }
  462. }
  463. }
  464. #endif
  465. return buf;
  466. }
  467. case string_type:
  468. return *u_.string_;
  469. case array_type:
  470. return "array";
  471. case object_type:
  472. return "object";
  473. default:
  474. PICOJSON_ASSERT(0);
  475. #ifdef _MSC_VER
  476. __assume(0);
  477. #endif
  478. }
  479. return std::string();
  480. }
  481. template <typename Iter> void copy(const std::string &s, Iter oi) {
  482. std::copy(s.begin(), s.end(), oi);
  483. }
  484. template <typename Iter> struct serialize_str_char {
  485. Iter oi;
  486. void operator()(char c) {
  487. switch (c) {
  488. #define MAP(val, sym) \
  489. case val: \
  490. copy(sym, oi); \
  491. break
  492. MAP('"', "\\\"");
  493. MAP('\\', "\\\\");
  494. MAP('/', "\\/");
  495. MAP('\b', "\\b");
  496. MAP('\f', "\\f");
  497. MAP('\n', "\\n");
  498. MAP('\r', "\\r");
  499. MAP('\t', "\\t");
  500. #undef MAP
  501. default:
  502. if (static_cast<unsigned char>(c) < 0x20 || c == 0x7f) {
  503. char buf[7];
  504. SNPRINTF(buf, sizeof(buf), "\\u%04x", c & 0xff);
  505. copy(buf, buf + 6, oi);
  506. } else {
  507. *oi++ = c;
  508. }
  509. break;
  510. }
  511. }
  512. };
  513. template <typename Iter> void serialize_str(const std::string &s, Iter oi) {
  514. *oi++ = '"';
  515. serialize_str_char<Iter> process_char = {oi};
  516. std::for_each(s.begin(), s.end(), process_char);
  517. *oi++ = '"';
  518. }
  519. template <typename Iter> void value::serialize(Iter oi, bool prettify) const {
  520. return _serialize(oi, prettify ? 0 : -1);
  521. }
  522. inline std::string value::serialize(bool prettify) const {
  523. return _serialize(prettify ? 0 : -1);
  524. }
  525. template <typename Iter> void value::_indent(Iter oi, int indent) {
  526. *oi++ = '\n';
  527. for (int i = 0; i < indent * INDENT_WIDTH; ++i) {
  528. *oi++ = ' ';
  529. }
  530. }
  531. template <typename Iter> void value::_serialize(Iter oi, int indent) const {
  532. switch (type_) {
  533. case string_type:
  534. serialize_str(*u_.string_, oi);
  535. break;
  536. case array_type: {
  537. *oi++ = '[';
  538. if (indent != -1) {
  539. ++indent;
  540. }
  541. for (array::const_iterator i = u_.array_->begin(); i != u_.array_->end(); ++i) {
  542. if (i != u_.array_->begin()) {
  543. *oi++ = ',';
  544. }
  545. if (indent != -1) {
  546. _indent(oi, indent);
  547. }
  548. i->_serialize(oi, indent);
  549. }
  550. if (indent != -1) {
  551. --indent;
  552. if (!u_.array_->empty()) {
  553. _indent(oi, indent);
  554. }
  555. }
  556. *oi++ = ']';
  557. break;
  558. }
  559. case object_type: {
  560. *oi++ = '{';
  561. if (indent != -1) {
  562. ++indent;
  563. }
  564. for (object::const_iterator i = u_.object_->begin(); i != u_.object_->end(); ++i) {
  565. if (i != u_.object_->begin()) {
  566. *oi++ = ',';
  567. }
  568. if (indent != -1) {
  569. _indent(oi, indent);
  570. }
  571. serialize_str(i->first, oi);
  572. *oi++ = ':';
  573. if (indent != -1) {
  574. *oi++ = ' ';
  575. }
  576. i->second._serialize(oi, indent);
  577. }
  578. if (indent != -1) {
  579. --indent;
  580. if (!u_.object_->empty()) {
  581. _indent(oi, indent);
  582. }
  583. }
  584. *oi++ = '}';
  585. break;
  586. }
  587. default:
  588. copy(to_str(), oi);
  589. break;
  590. }
  591. if (indent == 0) {
  592. *oi++ = '\n';
  593. }
  594. }
  595. inline std::string value::_serialize(int indent) const {
  596. std::string s;
  597. _serialize(std::back_inserter(s), indent);
  598. return s;
  599. }
  600. template <typename Iter> class input {
  601. protected:
  602. Iter cur_, end_;
  603. bool consumed_;
  604. int line_;
  605. public:
  606. input(const Iter &first, const Iter &last) : cur_(first), end_(last), consumed_(false), line_(1) {
  607. }
  608. int getc() {
  609. if (consumed_) {
  610. if (*cur_ == '\n') {
  611. ++line_;
  612. }
  613. ++cur_;
  614. }
  615. if (cur_ == end_) {
  616. consumed_ = false;
  617. return -1;
  618. }
  619. consumed_ = true;
  620. return *cur_ & 0xff;
  621. }
  622. void ungetc() {
  623. consumed_ = false;
  624. }
  625. Iter cur() const {
  626. if (consumed_) {
  627. input<Iter> *self = const_cast<input<Iter> *>(this);
  628. self->consumed_ = false;
  629. ++self->cur_;
  630. }
  631. return cur_;
  632. }
  633. int line() const {
  634. return line_;
  635. }
  636. void skip_ws() {
  637. while (1) {
  638. int ch = getc();
  639. if (!(ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')) {
  640. ungetc();
  641. break;
  642. }
  643. }
  644. }
  645. bool expect(const int expected) {
  646. skip_ws();
  647. if (getc() != expected) {
  648. ungetc();
  649. return false;
  650. }
  651. return true;
  652. }
  653. bool match(const std::string &pattern) {
  654. for (std::string::const_iterator pi(pattern.begin()); pi != pattern.end(); ++pi) {
  655. if (getc() != *pi) {
  656. ungetc();
  657. return false;
  658. }
  659. }
  660. return true;
  661. }
  662. };
  663. template <typename Iter> inline int _parse_quadhex(input<Iter> &in) {
  664. int uni_ch = 0, hex;
  665. for (int i = 0; i < 4; i++) {
  666. if ((hex = in.getc()) == -1) {
  667. return -1;
  668. }
  669. if ('0' <= hex && hex <= '9') {
  670. hex -= '0';
  671. } else if ('A' <= hex && hex <= 'F') {
  672. hex -= 'A' - 0xa;
  673. } else if ('a' <= hex && hex <= 'f') {
  674. hex -= 'a' - 0xa;
  675. } else {
  676. in.ungetc();
  677. return -1;
  678. }
  679. uni_ch = uni_ch * 16 + hex;
  680. }
  681. return uni_ch;
  682. }
  683. template <typename String, typename Iter> inline bool _parse_codepoint(String &out, input<Iter> &in) {
  684. int uni_ch;
  685. if ((uni_ch = _parse_quadhex(in)) == -1) {
  686. return false;
  687. }
  688. if (0xd800 <= uni_ch && uni_ch <= 0xdfff) {
  689. if (0xdc00 <= uni_ch) {
  690. // a second 16-bit of a surrogate pair appeared
  691. return false;
  692. }
  693. // first 16-bit of surrogate pair, get the next one
  694. if (in.getc() != '\\' || in.getc() != 'u') {
  695. in.ungetc();
  696. return false;
  697. }
  698. int second = _parse_quadhex(in);
  699. if (!(0xdc00 <= second && second <= 0xdfff)) {
  700. return false;
  701. }
  702. uni_ch = ((uni_ch - 0xd800) << 10) | ((second - 0xdc00) & 0x3ff);
  703. uni_ch += 0x10000;
  704. }
  705. if (uni_ch < 0x80) {
  706. out.push_back(static_cast<char>(uni_ch));
  707. } else {
  708. if (uni_ch < 0x800) {
  709. out.push_back(static_cast<char>(0xc0 | (uni_ch >> 6)));
  710. } else {
  711. if (uni_ch < 0x10000) {
  712. out.push_back(static_cast<char>(0xe0 | (uni_ch >> 12)));
  713. } else {
  714. out.push_back(static_cast<char>(0xf0 | (uni_ch >> 18)));
  715. out.push_back(static_cast<char>(0x80 | ((uni_ch >> 12) & 0x3f)));
  716. }
  717. out.push_back(static_cast<char>(0x80 | ((uni_ch >> 6) & 0x3f)));
  718. }
  719. out.push_back(static_cast<char>(0x80 | (uni_ch & 0x3f)));
  720. }
  721. return true;
  722. }
  723. template <typename String, typename Iter> inline bool _parse_string(String &out, input<Iter> &in) {
  724. while (1) {
  725. int ch = in.getc();
  726. if (ch < ' ') {
  727. in.ungetc();
  728. return false;
  729. } else if (ch == '"') {
  730. return true;
  731. } else if (ch == '\\') {
  732. if ((ch = in.getc()) == -1) {
  733. return false;
  734. }
  735. switch (ch) {
  736. #define MAP(sym, val) \
  737. case sym: \
  738. out.push_back(val); \
  739. break
  740. MAP('"', '\"');
  741. MAP('\\', '\\');
  742. MAP('/', '/');
  743. MAP('b', '\b');
  744. MAP('f', '\f');
  745. MAP('n', '\n');
  746. MAP('r', '\r');
  747. MAP('t', '\t');
  748. #undef MAP
  749. case 'u':
  750. if (!_parse_codepoint(out, in)) {
  751. return false;
  752. }
  753. break;
  754. default:
  755. return false;
  756. }
  757. } else {
  758. out.push_back(static_cast<char>(ch));
  759. }
  760. }
  761. return false;
  762. }
  763. template <typename Context, typename Iter> inline bool _parse_array(Context &ctx, input<Iter> &in) {
  764. if (!ctx.parse_array_start()) {
  765. return false;
  766. }
  767. size_t idx = 0;
  768. if (in.expect(']')) {
  769. return ctx.parse_array_stop(idx);
  770. }
  771. do {
  772. if (!ctx.parse_array_item(in, idx)) {
  773. return false;
  774. }
  775. idx++;
  776. } while (in.expect(','));
  777. return in.expect(']') && ctx.parse_array_stop(idx);
  778. }
  779. template <typename Context, typename Iter> inline bool _parse_object(Context &ctx, input<Iter> &in) {
  780. if (!ctx.parse_object_start()) {
  781. return false;
  782. }
  783. if (in.expect('}')) {
  784. return true;
  785. }
  786. do {
  787. std::string key;
  788. if (!in.expect('"') || !_parse_string(key, in) || !in.expect(':')) {
  789. return false;
  790. }
  791. if (!ctx.parse_object_item(in, key)) {
  792. return false;
  793. }
  794. } while (in.expect(','));
  795. return in.expect('}');
  796. }
  797. template <typename Iter> inline std::string _parse_number(input<Iter> &in) {
  798. std::string num_str;
  799. while (1) {
  800. int ch = in.getc();
  801. if (('0' <= ch && ch <= '9') || ch == '+' || ch == '-' || ch == 'e' || ch == 'E') {
  802. num_str.push_back(static_cast<char>(ch));
  803. } else if (ch == '.') {
  804. #if PICOJSON_USE_LOCALE
  805. num_str += localeconv()->decimal_point;
  806. #else
  807. num_str.push_back('.');
  808. #endif
  809. } else {
  810. in.ungetc();
  811. break;
  812. }
  813. }
  814. return num_str;
  815. }
  816. template <typename Context, typename Iter> inline bool _parse(Context &ctx, input<Iter> &in) {
  817. in.skip_ws();
  818. int ch = in.getc();
  819. switch (ch) {
  820. #define IS(ch, text, op) \
  821. case ch: \
  822. if (in.match(text) && op) { \
  823. return true; \
  824. } else { \
  825. return false; \
  826. }
  827. IS('n', "ull", ctx.set_null());
  828. IS('f', "alse", ctx.set_bool(false));
  829. IS('t', "rue", ctx.set_bool(true));
  830. #undef IS
  831. case '"':
  832. return ctx.parse_string(in);
  833. case '[':
  834. return _parse_array(ctx, in);
  835. case '{':
  836. return _parse_object(ctx, in);
  837. default:
  838. if (('0' <= ch && ch <= '9') || ch == '-') {
  839. double f;
  840. char *endp;
  841. in.ungetc();
  842. std::string num_str(_parse_number(in));
  843. if (num_str.empty()) {
  844. return false;
  845. }
  846. #ifdef PICOJSON_USE_INT64
  847. {
  848. errno = 0;
  849. intmax_t ival = strtoimax(num_str.c_str(), &endp, 10);
  850. if (errno == 0 && std::numeric_limits<int64_t>::min() <= ival && ival <= std::numeric_limits<int64_t>::max() &&
  851. endp == num_str.c_str() + num_str.size()) {
  852. ctx.set_int64(ival);
  853. return true;
  854. }
  855. }
  856. #endif
  857. f = strtod(num_str.c_str(), &endp);
  858. if (endp == num_str.c_str() + num_str.size()) {
  859. ctx.set_number(f);
  860. return true;
  861. }
  862. return false;
  863. }
  864. break;
  865. }
  866. in.ungetc();
  867. return false;
  868. }
  869. class deny_parse_context {
  870. public:
  871. bool set_null() {
  872. return false;
  873. }
  874. bool set_bool(bool) {
  875. return false;
  876. }
  877. #ifdef PICOJSON_USE_INT64
  878. bool set_int64(int64_t) {
  879. return false;
  880. }
  881. #endif
  882. bool set_number(double) {
  883. return false;
  884. }
  885. template <typename Iter> bool parse_string(input<Iter> &) {
  886. return false;
  887. }
  888. bool parse_array_start() {
  889. return false;
  890. }
  891. template <typename Iter> bool parse_array_item(input<Iter> &, size_t) {
  892. return false;
  893. }
  894. bool parse_array_stop(size_t) {
  895. return false;
  896. }
  897. bool parse_object_start() {
  898. return false;
  899. }
  900. template <typename Iter> bool parse_object_item(input<Iter> &, const std::string &) {
  901. return false;
  902. }
  903. };
  904. class default_parse_context {
  905. protected:
  906. value *out_;
  907. public:
  908. default_parse_context(value *out) : out_(out) {
  909. }
  910. bool set_null() {
  911. *out_ = value();
  912. return true;
  913. }
  914. bool set_bool(bool b) {
  915. *out_ = value(b);
  916. return true;
  917. }
  918. #ifdef PICOJSON_USE_INT64
  919. bool set_int64(int64_t i) {
  920. *out_ = value(i);
  921. return true;
  922. }
  923. #endif
  924. bool set_number(double f) {
  925. *out_ = value(f);
  926. return true;
  927. }
  928. template <typename Iter> bool parse_string(input<Iter> &in) {
  929. *out_ = value(string_type, false);
  930. return _parse_string(out_->get<std::string>(), in);
  931. }
  932. bool parse_array_start() {
  933. *out_ = value(array_type, false);
  934. return true;
  935. }
  936. template <typename Iter> bool parse_array_item(input<Iter> &in, size_t) {
  937. array &a = out_->get<array>();
  938. a.push_back(value());
  939. default_parse_context ctx(&a.back());
  940. return _parse(ctx, in);
  941. }
  942. bool parse_array_stop(size_t) {
  943. return true;
  944. }
  945. bool parse_object_start() {
  946. *out_ = value(object_type, false);
  947. return true;
  948. }
  949. template <typename Iter> bool parse_object_item(input<Iter> &in, const std::string &key) {
  950. object &o = out_->get<object>();
  951. default_parse_context ctx(&o[key]);
  952. return _parse(ctx, in);
  953. }
  954. private:
  955. default_parse_context(const default_parse_context &);
  956. default_parse_context &operator=(const default_parse_context &);
  957. };
  958. class null_parse_context {
  959. public:
  960. struct dummy_str {
  961. void push_back(int) {
  962. }
  963. };
  964. public:
  965. null_parse_context() {
  966. }
  967. bool set_null() {
  968. return true;
  969. }
  970. bool set_bool(bool) {
  971. return true;
  972. }
  973. #ifdef PICOJSON_USE_INT64
  974. bool set_int64(int64_t) {
  975. return true;
  976. }
  977. #endif
  978. bool set_number(double) {
  979. return true;
  980. }
  981. template <typename Iter> bool parse_string(input<Iter> &in) {
  982. dummy_str s;
  983. return _parse_string(s, in);
  984. }
  985. bool parse_array_start() {
  986. return true;
  987. }
  988. template <typename Iter> bool parse_array_item(input<Iter> &in, size_t) {
  989. return _parse(*this, in);
  990. }
  991. bool parse_array_stop(size_t) {
  992. return true;
  993. }
  994. bool parse_object_start() {
  995. return true;
  996. }
  997. template <typename Iter> bool parse_object_item(input<Iter> &in, const std::string &) {
  998. return _parse(*this, in);
  999. }
  1000. private:
  1001. null_parse_context(const null_parse_context &);
  1002. null_parse_context &operator=(const null_parse_context &);
  1003. };
  1004. // obsolete, use the version below
  1005. template <typename Iter> inline std::string parse(value &out, Iter &pos, const Iter &last) {
  1006. std::string err;
  1007. pos = parse(out, pos, last, &err);
  1008. return err;
  1009. }
  1010. template <typename Context, typename Iter> inline Iter _parse(Context &ctx, const Iter &first, const Iter &last, std::string *err) {
  1011. input<Iter> in(first, last);
  1012. if (!_parse(ctx, in) && err != NULL) {
  1013. char buf[64];
  1014. SNPRINTF(buf, sizeof(buf), "syntax error at line %d near: ", in.line());
  1015. *err = buf;
  1016. while (1) {
  1017. int ch = in.getc();
  1018. if (ch == -1 || ch == '\n') {
  1019. break;
  1020. } else if (ch >= ' ') {
  1021. err->push_back(static_cast<char>(ch));
  1022. }
  1023. }
  1024. }
  1025. return in.cur();
  1026. }
  1027. template <typename Iter> inline Iter parse(value &out, const Iter &first, const Iter &last, std::string *err) {
  1028. default_parse_context ctx(&out);
  1029. return _parse(ctx, first, last, err);
  1030. }
  1031. inline std::string parse(value &out, const std::string &s) {
  1032. std::string err;
  1033. parse(out, s.begin(), s.end(), &err);
  1034. return err;
  1035. }
  1036. inline std::string parse(value &out, std::istream &is) {
  1037. std::string err;
  1038. parse(out, std::istreambuf_iterator<char>(is.rdbuf()), std::istreambuf_iterator<char>(), &err);
  1039. return err;
  1040. }
  1041. template <typename T> struct last_error_t { static std::string s; };
  1042. template <typename T> std::string last_error_t<T>::s;
  1043. inline void set_last_error(const std::string &s) {
  1044. last_error_t<bool>::s = s;
  1045. }
  1046. inline const std::string &get_last_error() {
  1047. return last_error_t<bool>::s;
  1048. }
  1049. inline bool operator==(const value &x, const value &y) {
  1050. if (x.is<null>())
  1051. return y.is<null>();
  1052. #define PICOJSON_CMP(type) \
  1053. if (x.is<type>()) \
  1054. return y.is<type>() && x.get<type>() == y.get<type>()
  1055. PICOJSON_CMP(bool);
  1056. PICOJSON_CMP(double);
  1057. PICOJSON_CMP(std::string);
  1058. PICOJSON_CMP(array);
  1059. PICOJSON_CMP(object);
  1060. #undef PICOJSON_CMP
  1061. PICOJSON_ASSERT(0);
  1062. #ifdef _MSC_VER
  1063. __assume(0);
  1064. #endif
  1065. return false;
  1066. }
  1067. inline bool operator!=(const value &x, const value &y) {
  1068. return !(x == y);
  1069. }
  1070. }
  1071. #if !PICOJSON_USE_RVALUE_REFERENCE
  1072. namespace std {
  1073. template <> inline void swap(picojson::value &x, picojson::value &y) {
  1074. x.swap(y);
  1075. }
  1076. }
  1077. #endif
  1078. inline std::istream &operator>>(std::istream &is, picojson::value &x) {
  1079. picojson::set_last_error(std::string());
  1080. const std::string err(picojson::parse(x, is));
  1081. if (!err.empty()) {
  1082. picojson::set_last_error(err);
  1083. is.setstate(std::ios::failbit);
  1084. }
  1085. return is;
  1086. }
  1087. inline std::ostream &operator<<(std::ostream &os, const picojson::value &x) {
  1088. x.serialize(std::ostream_iterator<char>(os));
  1089. return os;
  1090. }
  1091. #ifdef _MSC_VER
  1092. #pragma warning(pop)
  1093. #endif
  1094. #endif