1 /* Copyright 2009 Cybozu Labs, Inc.
3 * Redistribution and use in source and binary forms, with or without
4 * modification, are permitted provided that the following conditions are met:
6 * 1. Redistributions of source code must retain the above copyright notice,
7 * this list of conditions and the following disclaimer.
8 * 2. Redistributions in binary form must reproduce the above copyright notice,
9 * this list of conditions and the following disclaimer in the documentation
10 * and/or other materials provided with the distribution.
12 * THIS SOFTWARE IS PROVIDED BY CYBOZU LABS, INC. ``AS IS'' AND ANY EXPRESS OR
13 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
14 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
15 * EVENT SHALL CYBOZU LABS, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
16 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
17 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
18 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
19 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
20 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
21 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23 * The views and conclusions contained in the software and documentation are
24 * those of the authors and should not be interpreted as representing official
25 * policies, either expressed or implied, of Cybozu Labs, Inc.
42 #define SNPRINTF _snprintf_s
44 #pragma warning(disable : 4244) // conversion from int to char
46 #define SNPRINTF snprintf
64 typedef std::vector<value> array;
65 typedef std::map<std::string, value> object;
77 value(int type, bool);
78 explicit value(bool b);
79 explicit value(double n);
80 explicit value(const std::string& s);
81 explicit value(const array& a);
82 explicit value(const object& o);
84 value(const value& x);
85 value& operator=(const value& x);
86 template <typename T> bool is() const;
87 template <typename T> const T& get() const;
88 template <typename T> T& get();
89 operator bool() const;
90 const value& get(size_t idx) const;
91 const value& get(const std::string& key) const;
92 std::string to_str() const;
93 template <typename Iter> void serialize(Iter os) const;
94 std::string serialize() const;
97 typedef value::array array;
98 typedef value::object object;
100 inline value::value() : type_(null_type) {}
102 inline value::value(int type, bool) : type_(type) {
104 #define INIT(p, v) case p##type: p = v; break
105 INIT(boolean_, false);
107 INIT(string_, new std::string());
108 INIT(array_, new array());
109 INIT(object_, new object());
115 inline value::value(bool b) : type_(boolean_type) {
119 inline value::value(double n) : type_(number_type) {
123 inline value::value(const std::string& s) : type_(string_type) {
124 string_ = new std::string(s);
127 inline value::value(const array& a) : type_(array_type) {
128 array_ = new array(a);
131 inline value::value(const object& o) : type_(object_type) {
132 object_ = new object(o);
135 inline value::~value() {
137 #define DEINIT(p) case p##type: delete p; break
146 inline value::value(const value& x) : type_(x.type_) {
148 #define INIT(p, v) case p##type: p = v; break
149 INIT(boolean_, x.boolean_);
150 INIT(number_, x.number_);
151 INIT(string_, new std::string(*x.string_));
152 INIT(array_, new array(*x.array_));
153 INIT(object_, new object(*x.object_));
159 inline value& value::operator=(const value& x) {
167 #define IS(ctype, jtype) \
168 template <> inline bool value::is<ctype>() const { \
169 return type_ == jtype##_type; \
175 IS(std::string, string)
180 #define GET(ctype, var) \
181 template <> inline const ctype& value::get<ctype>() const { \
184 template <> inline ctype& value::get<ctype>() { \
189 GET(std::string, *string_)
191 GET(object, *object_)
194 inline value::operator bool() const {
203 return ! string_->empty();
209 inline const value& value::get(size_t idx) const {
212 return idx < array_->size() ? (*array_)[idx] : s_null;
215 inline const value& value::get(const std::string& key) const {
217 assert(is<object>());
218 object::const_iterator i = object_->find(key);
219 return i != object_->end() ? i->second : s_null;
222 inline std::string value::to_str() const {
224 case null_type: return "null";
225 case boolean_type: return boolean_ ? "true" : "false";
228 SNPRINTF(buf, sizeof(buf), "%f", number_);
231 case string_type: return *string_;
232 case array_type: return "array";
233 case object_type: return "object";
241 template <typename Iter> void copy(const std::string& s, Iter oi) {
242 std::copy(s.begin(), s.end(), oi);
245 template <typename Iter> void serialize_str(const std::string& s, Iter oi) {
247 for (std::string::const_iterator i = s.begin(); i != s.end(); ++i) {
249 #define MAP(val, sym) case val: copy(sym, oi); break
260 if ((unsigned char)*i < 0x20 || *i == 0x7f) {
262 SNPRINTF(buf, sizeof(buf), "\\u%04x", *i & 0xff);
263 copy(buf, buf + 6, oi);
273 template <typename Iter> void value::serialize(Iter oi) const {
276 serialize_str(*string_, oi);
280 for (array::const_iterator i = array_->begin(); i != array_->end(); ++i) {
281 if (i != array_->begin()) {
291 for (object::const_iterator i = object_->begin();
294 if (i != object_->begin()) {
297 serialize_str(i->first, oi);
299 i->second.serialize(oi);
310 inline std::string value::serialize() const {
312 serialize(std::back_inserter(s));
316 template <typename Iter> class input {
323 input(const Iter& first, const Iter& last) : cur_(first), end_(last), last_ch_(-1), ungot_(false), line_(1) {}
333 if (last_ch_ == '\n') {
336 last_ch_ = *cur_++ & 0xff;
340 if (last_ch_ != -1) {
345 Iter cur() const { return cur_; }
346 int line() const { return line_; }
350 if (! (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')) {
356 int expect(int expect) {
358 if (getc() != expect) {
364 bool match(const std::string& pattern) {
365 for (std::string::const_iterator pi(pattern.begin());
377 template<typename Iter> inline int _parse_quadhex(input<Iter> &in) {
379 for (int i = 0; i < 4; i++) {
380 if ((hex = in.getc()) == -1) {
383 if ('0' <= hex && hex <= '9') {
385 } else if ('A' <= hex && hex <= 'F') {
387 } else if ('a' <= hex && hex <= 'f') {
393 uni_ch = uni_ch * 16 + hex;
398 template<typename Iter> inline bool _parse_codepoint(std::string& out, input<Iter>& in) {
400 if ((uni_ch = _parse_quadhex(in)) == -1) {
403 if (0xd800 <= uni_ch && uni_ch <= 0xdfff) {
404 if (0xdc00 <= uni_ch) {
405 // a second 16-bit of a surrogate pair appeared
408 // first 16-bit of surrogate pair, get the next one
409 if (in.getc() != '\\' || in.getc() != 'u') {
413 int second = _parse_quadhex(in);
414 if (! (0xdc00 <= second && second <= 0xdfff)) {
417 uni_ch = ((uni_ch - 0xd800) << 10) | ((second - 0xdc00) & 0x3ff);
421 out.push_back(uni_ch);
423 if (uni_ch < 0x800) {
424 out.push_back(0xc0 | (uni_ch >> 6));
426 if (uni_ch < 0x10000) {
427 out.push_back(0xe0 | (uni_ch >> 12));
429 out.push_back(0xf0 | (uni_ch >> 18));
430 out.push_back(0x80 | ((uni_ch >> 12) & 0x3f));
432 out.push_back(0x80 | ((uni_ch >> 6) & 0x3f));
434 out.push_back(0x80 | (uni_ch & 0x3f));
439 template<typename Iter> inline bool _parse_string(value& out, input<Iter>& in) {
440 // gcc 4.1 cannot compile if the below two lines are merged into one :-(
441 out = value(string_type, false);
442 std::string& s = out.get<std::string>();
448 } else if (ch == '"') {
450 } else if (ch == '\\') {
451 if ((ch = in.getc()) == -1) {
455 #define MAP(sym, val) case sym: s.push_back(val); break
466 if (! _parse_codepoint(s, in)) {
480 template <typename Iter> inline bool _parse_array(value& out, input<Iter>& in) {
481 out = value(array_type, false);
482 array& a = out.get<array>();
483 if (in.expect(']')) {
487 a.push_back(value());
488 if (! _parse(a.back(), in)) {
491 } while (in.expect(','));
492 return in.expect(']');
495 template <typename Iter> inline bool _parse_object(value& out, input<Iter>& in) {
496 out = value(object_type, false);
497 object& o = out.get<object>();
498 if (in.expect('}')) {
504 && _parse_string(key, in)
506 && _parse(val, in)) {
507 o[key.to_str()] = val;
511 } while (in.expect(','));
512 return in.expect('}');
515 template <typename Iter> inline bool _parse_number(value& out, input<Iter>& in) {
519 if (('0' <= ch && ch <= '9') || ch == '+' || ch == '-' || ch == '.'
520 || ch == 'e' || ch == 'E') {
521 num_str.push_back(ch);
528 out = value(strtod(num_str.c_str(), &endp));
529 return endp == num_str.c_str() + num_str.size();
532 template <typename Iter> inline bool _parse(value& out, input<Iter>& in) {
536 #define IS(ch, text, val) case ch: \
537 if (in.match(text)) { \
543 IS('n', "ull", value());
544 IS('f', "alse", value(false));
545 IS('t', "rue", value(true));
548 return _parse_string(out, in);
550 return _parse_array(out, in);
552 return _parse_object(out, in);
554 if (('0' <= ch && ch <= '9') || ch == '-') {
556 return _parse_number(out, in);
564 // obsolete, use the version below
565 template <typename Iter> inline std::string parse(value& out, Iter& pos, const Iter& last) {
567 pos = parse(out, pos, last, &err);
571 template <typename Iter> inline Iter parse(value& out, const Iter& first, const Iter& last, std::string* err) {
572 input<Iter> in(first, last);
573 if (! _parse(out, in) && err != NULL) {
575 SNPRINTF(buf, sizeof(buf), "syntax error at line %d near: ", in.line());
579 if (ch == -1 || ch == '\n') {
581 } else if (ch >= ' ') {
589 inline std::string parse(value& out, std::istream& is) {
591 parse(out, std::istreambuf_iterator<char>(is.rdbuf()),
592 std::istreambuf_iterator<char>(), &err);
596 template <typename T> struct last_error_t {
597 static std::string s;
599 template <typename T> std::string last_error_t<T>::s;
601 inline void set_last_error(const std::string& s) {
602 last_error_t<bool>::s = s;
605 inline const std::string& get_last_error() {
606 return last_error_t<bool>::s;
609 bool operator==(const value& x, const value& y) {
612 #define PICOJSON_CMP(type) \
614 return y.is<type>() && x.get<type>() == y.get<type>()
616 PICOJSON_CMP(double);
617 PICOJSON_CMP(std::string);
619 PICOJSON_CMP(object);
628 inline bool operator!=(const value& x, const value& y) {
633 inline std::istream& operator>>(std::istream& is, picojson::value& x)
635 picojson::set_last_error(std::string());
636 std::string err = picojson::parse(x, is);
638 picojson::set_last_error(err);
639 is.setstate(std::ios::failbit);
644 inline std::ostream& operator<<(std::ostream& os, const picojson::value& x)
646 x.serialize(std::ostream_iterator<char>(os));
656 #pragma warning(disable : 4127) // conditional expression is constant
661 static void plan(int num)
663 printf("1..%d\n", num);
666 static void ok(bool b, const char* name = "")
669 printf("%s %d - %s\n", b ? "ok" : "ng", n++, name);
672 template <typename T> void is(const T& x, const T& y, const char* name = "")
687 #define TEST(in, type, cmp, serialize_test) { \
689 const char* s = in; \
690 string err = picojson::parse(v, s, s + strlen(s)); \
691 ok(err.empty(), in " no error"); \
692 ok(v.is<type>(), in " check type"); \
693 is(v.get<type>(), cmp, in " correct output"); \
694 is(*s, '\0', in " read to eof"); \
695 if (serialize_test) { \
696 is(v.serialize(), string(in), in " serialize"); \
699 TEST("false", bool, false, true);
700 TEST("true", bool, true, true);
701 TEST("90.5", double, 90.5, false);
702 TEST("\"hello\"", string, string("hello"), true);
703 TEST("\"\\\"\\\\\\/\\b\\f\\n\\r\\t\"", string, string("\"\\/\b\f\n\r\t"),
705 TEST("\"\\u0061\\u30af\\u30ea\\u30b9\"", string,
706 string("a\xe3\x82\xaf\xe3\x83\xaa\xe3\x82\xb9"), false);
707 TEST("\"\\ud840\\udc0b\"", string, string("\xf0\xa0\x80\x8b"), false);
710 #define TEST(type, expr) { \
712 const char *s = expr; \
713 string err = picojson::parse(v, s, s + strlen(s)); \
714 ok(err.empty(), "empty " #type " no error"); \
715 ok(v.is<picojson::type>(), "empty " #type " check type"); \
716 ok(v.get<picojson::type>().empty(), "check " #type " array size"); \
724 const char *s = "[1,true,\"hello\"]";
725 string err = picojson::parse(v, s, s + strlen(s));
726 ok(err.empty(), "array no error");
727 ok(v.is<picojson::array>(), "array check type");
728 is(v.get<picojson::array>().size(), size_t(3), "check array size");
729 ok(v.get(0).is<double>(), "check array[0] type");
730 is(v.get(0).get<double>(), 1.0, "check array[0] value");
731 ok(v.get(1).is<bool>(), "check array[1] type");
732 ok(v.get(1).get<bool>(), "check array[1] value");
733 ok(v.get(2).is<string>(), "check array[2] type");
734 is(v.get(2).get<string>(), string("hello"), "check array[2] value");
739 const char *s = "{ \"a\": true }";
740 string err = picojson::parse(v, s, s + strlen(s));
741 ok(err.empty(), "object no error");
742 ok(v.is<picojson::object>(), "object check type");
743 is(v.get<picojson::object>().size(), size_t(1), "check object size");
744 ok(v.get("a").is<bool>(), "check property exists");
745 is(v.get("a").get<bool>(), true,
746 "check property value");
747 is(v.serialize(), string("{\"a\":true}"), "serialize object");
750 #define TEST(json, msg) do { \
752 const char *s = json; \
753 string err = picojson::parse(v, s, s + strlen(s)); \
754 is(err, string("syntax error at line " msg), msg); \
756 TEST("falsoa", "1 near: oa");
757 TEST("{]", "1 near: ]");
758 TEST("\n\bbell", "2 near: bell");
759 TEST("\"abc\nd\"", "1 near: ");
763 picojson::value v1, v2;
766 s = "{ \"b\": true, \"a\": [1,2,\"three\"], \"d\": 2 }";
767 err = picojson::parse(v1, s, s + strlen(s));
768 s = "{ \"d\": 2.0, \"b\": true, \"a\": [1,2,\"three\"] }";
769 err = picojson::parse(v2, s, s + strlen(s));
770 ok((v1 == v2), "check == operator in deep comparison");
774 picojson::value v1, v2;
777 s = "{ \"b\": true, \"a\": [1,2,\"three\"], \"d\": 2 }";
778 err = picojson::parse(v1, s, s + strlen(s));
779 s = "{ \"d\": 2.0, \"a\": [1,\"three\"], \"b\": true }";
780 err = picojson::parse(v2, s, s + strlen(s));
781 ok((v1 != v2), "check != operator for array in deep comparison");
785 picojson::value v1, v2;
788 s = "{ \"b\": true, \"a\": [1,2,\"three\"], \"d\": 2 }";
789 err = picojson::parse(v1, s, s + strlen(s));
790 s = "{ \"d\": 2.0, \"a\": [1,2,\"three\"], \"b\": false }";
791 err = picojson::parse(v2, s, s + strlen(s));
792 ok((v1 != v2), "check != operator for object in deep comparison");
796 picojson::value v1, v2;
799 s = "{ \"b\": true, \"a\": [1,2,\"three\"], \"d\": 2 }";
800 err = picojson::parse(v1, s, s + strlen(s));
801 picojson::object& o = v1.get<picojson::object>();
803 picojson::array& a = o["a"].get<picojson::array>();
804 picojson::array::iterator i;
805 i = std::remove(a.begin(), a.end(), picojson::value(std::string("three")));
807 s = "{ \"a\": [1,2], \"d\": 2 }";
808 err = picojson::parse(v2, s, s + strlen(s));
809 ok((v1 == v2), "check erase()");