picojson.h 27 KB

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