picojson.h 32 KB

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