45 #define SNPRINTF _snprintf_s
47 #pragma warning(disable : 4244) // conversion from int to char
49 #define SNPRINTF snprintf
67 typedef std::vector<value> array;
68 typedef std::map<std::string, value> object;
80 value(
int type,
bool);
81 explicit value(
bool b);
82 explicit value(
double n);
83 explicit value(
const std::string& s);
84 explicit value(
const array& a);
85 explicit value(
const object& o);
86 explicit value(
const char* s);
87 value(
const char* s,
size_t len);
91 template <
typename T>
bool is()
const;
92 template <
typename T>
const T&
get()
const;
93 template <
typename T> T&
get();
94 bool evaluate_as_boolean()
const;
95 const value&
get(
size_t idx)
const;
96 const value&
get(
const std::string& key)
const;
97 bool contains(
size_t idx)
const;
98 bool contains(
const std::string& key)
const;
99 std::string to_str()
const;
100 template <
typename Iter>
void serialize(Iter os)
const;
101 std::string serialize()
const;
103 template <
typename T>
value(
const T*);
106 typedef value::array array;
107 typedef value::object object;
109 inline value::value() : type_(null_type) {}
111 inline value::value(
int type,
bool) : type_(type) {
113 #define INIT(p, v) case p##type: p = v; break
114 INIT(boolean_,
false);
116 INIT(string_,
new std::string());
117 INIT(array_,
new array());
118 INIT(object_,
new object());
124 inline value::value(
bool b) : type_(boolean_type) {
128 inline value::value(
double n) : type_(number_type) {
132 inline value::value(
const std::string& s) : type_(string_type) {
133 string_ =
new std::string(s);
136 inline value::value(
const array& a) : type_(array_type) {
137 array_ =
new array(a);
140 inline value::value(
const object& o) : type_(object_type) {
141 object_ =
new object(o);
144 inline value::value(
const char* s) : type_(string_type) {
145 string_ =
new std::string(s);
148 inline value::value(
const char* s,
size_t len) : type_(string_type) {
149 string_ =
new std::string(s, len);
152 inline value::~value() {
154 #define DEINIT(p) case p##type: delete p; break
163 inline value::value(
const value& x) : type_(x.type_) {
165 #define INIT(p, v) case p##type: p = v; break
166 INIT(boolean_, x.boolean_);
167 INIT(number_, x.number_);
168 INIT(string_,
new std::string(*x.string_));
169 INIT(array_,
new array(*x.array_));
170 INIT(object_,
new object(*x.object_));
176 inline value& value::operator=(
const value& x) {
184 #define IS(ctype, jtype) \
185 template <> inline bool value::is<ctype>() const { \
186 return type_ == jtype##_type; \
192 IS(std::
string,
string)
197 #define GET(ctype, var) \
198 template <> inline const ctype& value::get<ctype>() const { \
199 assert("type mismatch! call vis<type>() before get<type>()" \
203 template <> inline ctype& value::get<ctype>() { \
204 assert("type mismatch! call is<type>() before get<type>()" \
210 GET(std::
string, *string_)
212 GET(
object, *object_)
215 inline bool value::evaluate_as_boolean()
const {
224 return ! string_->empty();
230 inline const value& value::get(
size_t idx)
const {
233 return idx < array_->size() ? (*array_)[idx] : s_null;
236 inline const value& value::get(
const std::string& key)
const {
238 assert(is<object>());
239 object::const_iterator i = object_->find(key);
240 return i != object_->end() ? i->second : s_null;
243 inline bool value::contains(
size_t idx)
const {
245 return idx < array_->size();
248 inline bool value::contains(
const std::string& key)
const {
249 assert(is<object>());
250 object::const_iterator i = object_->find(key);
251 return i != object_->end();
254 inline std::string value::to_str()
const {
256 case null_type:
return "null";
257 case boolean_type:
return boolean_ ?
"true" :
"false";
261 SNPRINTF(buf,
sizeof(buf), modf(number_, &tmp) == 0 ?
"%.f" :
"%f", number_);
264 case string_type:
return *string_;
265 case array_type:
return "array";
266 case object_type:
return "object";
274 template <
typename Iter>
void copy(
const std::string& s, Iter oi) {
275 std::copy(s.begin(), s.end(), oi);
278 template <
typename Iter>
void serialize_str(
const std::string& s, Iter oi) {
280 for (std::string::const_iterator i = s.begin(); i != s.end(); ++i) {
282 #define MAP(val, sym) case val: copy(sym, oi); break
293 if ((
unsigned char)*i < 0x20 || *i == 0x7f) {
295 SNPRINTF(buf,
sizeof(buf),
"\\u%04x", *i & 0xff);
296 copy(buf, buf + 6, oi);
306 template <
typename Iter>
void value::serialize(Iter oi)
const {
309 serialize_str(*string_, oi);
313 for (array::const_iterator i = array_->begin(); i != array_->end(); ++i) {
314 if (i != array_->begin()) {
324 for (object::const_iterator i = object_->begin();
327 if (i != object_->begin()) {
330 serialize_str(i->first, oi);
332 i->second.serialize(oi);
343 inline std::string value::serialize()
const {
345 serialize(std::back_inserter(s));
349 template <
typename Iter>
class input {
356 input(
const Iter& first,
const Iter& last) : cur_(first), end_(last), last_ch_(-1), ungot_(
false), line_(1) {}
366 if (last_ch_ ==
'\n') {
369 last_ch_ = *cur_++ & 0xff;
373 if (last_ch_ != -1) {
378 Iter cur()
const {
return cur_; }
379 int line()
const {
return line_; }
383 if (! (ch ==
' ' || ch ==
'\t' || ch ==
'\n' || ch ==
'\r')) {
389 int expect(
int expect) {
391 if (getc() != expect) {
397 bool match(
const std::string& pattern) {
398 for (std::string::const_iterator pi(pattern.begin());
410 template<
typename Iter>
inline int _parse_quadhex(
input<Iter> &in) {
412 for (
int i = 0; i < 4; i++) {
413 if ((hex = in.getc()) == -1) {
416 if (
'0' <= hex && hex <=
'9') {
418 }
else if (
'A' <= hex && hex <=
'F') {
420 }
else if (
'a' <= hex && hex <=
'f') {
426 uni_ch = uni_ch * 16 + hex;
431 template<
typename String,
typename Iter>
inline bool _parse_codepoint(String& out, input<Iter>& in) {
433 if ((uni_ch = _parse_quadhex(in)) == -1) {
436 if (0xd800 <= uni_ch && uni_ch <= 0xdfff) {
437 if (0xdc00 <= uni_ch) {
442 if (in.getc() !=
'\\' || in.getc() !=
'u') {
446 int second = _parse_quadhex(in);
447 if (! (0xdc00 <= second && second <= 0xdfff)) {
450 uni_ch = ((uni_ch - 0xd800) << 10) | ((second - 0xdc00) & 0x3ff);
454 out.push_back(uni_ch);
456 if (uni_ch < 0x800) {
457 out.push_back(0xc0 | (uni_ch >> 6));
459 if (uni_ch < 0x10000) {
460 out.push_back(0xe0 | (uni_ch >> 12));
462 out.push_back(0xf0 | (uni_ch >> 18));
463 out.push_back(0x80 | ((uni_ch >> 12) & 0x3f));
465 out.push_back(0x80 | ((uni_ch >> 6) & 0x3f));
467 out.push_back(0x80 | (uni_ch & 0x3f));
472 template<
typename String,
typename Iter>
inline bool _parse_string(String& out, input<Iter>& in) {
478 }
else if (ch ==
'"') {
480 }
else if (ch ==
'\\') {
481 if ((ch = in.getc()) == -1) {
485 #define MAP(sym, val) case sym: out.push_back(val); break
496 if (! _parse_codepoint(out, in)) {
510 template <
typename Context,
typename Iter>
inline bool _parse_array(Context& ctx, input<Iter>& in) {
511 if (! ctx.parse_array_start()) {
514 if (in.expect(
']')) {
519 if (! ctx.parse_array_item(in, idx)) {
523 }
while (in.expect(
','));
524 return in.expect(
']');
527 template <
typename Context,
typename Iter>
inline bool _parse_object(Context& ctx, input<Iter>& in) {
528 if (! ctx.parse_object_start()) {
531 if (in.expect(
'}')) {
537 || ! _parse_string(key, in)
538 || ! in.expect(
':')) {
541 if (! ctx.parse_object_item(in, key)) {
544 }
while (in.expect(
','));
545 return in.expect(
'}');
548 template <
typename Iter>
inline bool _parse_number(
double& out, input<Iter>& in) {
552 if ((
'0' <= ch && ch <=
'9') || ch ==
'+' || ch ==
'-' || ch ==
'.'
553 || ch ==
'e' || ch ==
'E') {
554 num_str.push_back(ch);
561 out = strtod(num_str.c_str(), &endp);
562 return endp == num_str.c_str() + num_str.size();
565 template <
typename Context,
typename Iter>
inline bool _parse(Context& ctx, input<Iter>& in) {
569 #define IS(ch, text, op) case ch: \
570 if (in.match(text) && op) { \
575 IS(
'n',
"ull", ctx.set_null());
576 IS(
'f',
"alse", ctx.set_bool(
false));
577 IS(
't',
"rue", ctx.set_bool(
true));
580 return ctx.parse_string(in);
582 return _parse_array(ctx, in);
584 return _parse_object(ctx, in);
586 if ((
'0' <= ch && ch <=
'9') || ch ==
'-') {
589 if (_parse_number(f, in)) {
604 bool set_null() {
return false; }
605 bool set_bool(
bool) {
return false; }
606 bool set_number(
double) {
return false; }
607 template <
typename Iter>
bool parse_string(
input<Iter>&) {
return false; }
608 bool parse_array_start() {
return false; }
609 template <
typename Iter>
bool parse_array_item(
input<Iter>&,
size_t) {
612 bool parse_object_start() {
return false; }
613 template <
typename Iter>
bool parse_object_item(
input<Iter>&,
const std::string&) {
627 bool set_bool(
bool b) {
631 bool set_number(
double f) {
635 template<
typename Iter>
bool parse_string(
input<Iter>& in) {
636 *out_ =
value(string_type,
false);
637 return _parse_string(out_->get<std::string>(), in);
639 bool parse_array_start() {
640 *out_ =
value(array_type,
false);
643 template <
typename Iter>
bool parse_array_item(
input<Iter>& in,
size_t) {
644 array& a = out_->get<array>();
645 a.push_back(
value());
647 return _parse(ctx, in);
649 bool parse_object_start() {
650 *out_ =
value(object_type,
false);
653 template <
typename Iter>
bool parse_object_item(
input<Iter>& in,
const std::string& key) {
654 object& o = out_->get<
object>();
656 return _parse(ctx, in);
666 void push_back(
int) {}
670 bool set_null() {
return true; }
671 bool set_bool(
bool) {
return true; }
672 bool set_number(
double) {
return true; }
673 template <
typename Iter>
bool parse_string(input<Iter>& in) {
675 return _parse_string(s, in);
677 bool parse_array_start() {
return true; }
678 template <
typename Iter>
bool parse_array_item(input<Iter>& in,
size_t) {
679 return _parse(*
this, in);
681 bool parse_object_start() {
return true; }
682 template <
typename Iter>
bool parse_object_item(input<Iter>& in,
const std::string&) {
683 return _parse(*
this, in);
686 null_parse_context(
const null_parse_context&);
687 null_parse_context& operator=(
const null_parse_context&);
691 template <
typename Iter>
inline std::string parse(value& out, Iter& pos,
const Iter& last) {
693 pos = parse(out, pos, last, &err);
697 template <
typename Context,
typename Iter>
inline Iter _parse(Context& ctx,
const Iter& first,
const Iter& last, std::string* err) {
698 input<Iter> in(first, last);
699 if (! _parse(ctx, in) && err != NULL) {
701 SNPRINTF(buf,
sizeof(buf),
"syntax error at line %d near: ", in.line());
705 if (ch == -1 || ch ==
'\n') {
707 }
else if (ch >=
' ') {
715 template <
typename Iter>
inline Iter parse(value& out,
const Iter& first,
const Iter& last, std::string* err) {
716 default_parse_context ctx(&out);
717 return _parse(ctx, first, last, err);
720 inline std::string parse(value& out, std::istream& is) {
722 parse(out, std::istreambuf_iterator<char>(is.rdbuf()),
723 std::istreambuf_iterator<char>(), &err);
728 static std::string s;
732 inline void set_last_error(
const std::string& s) {
736 inline const std::string& get_last_error() {
737 return last_error_t<bool>::s;
740 inline bool operator==(
const value& x,
const value& y) {
743 #define PICOJSON_CMP(type) \
745 return y.is<type>() && x.get<type>() == y.get<type>()
747 PICOJSON_CMP(
double);
748 PICOJSON_CMP(std::string);
750 PICOJSON_CMP(
object);
759 inline bool operator!=(
const value& x,
const value& y) {
766 picojson::set_last_error(std::string());
767 std::string err = picojson::parse(x, is);
769 picojson::set_last_error(err);
770 is.setstate(std::ios::failbit);
775 inline std::ostream& operator<<(std::ostream& os,
const picojson::value& x)
777 x.serialize(std::ostream_iterator<char>(os));
787 #pragma warning(disable : 4127) // conditional expression is constant
792 static void plan(
int num)
794 printf(
"1..%d\n", num);
797 static bool success =
true;
799 static void ok(
bool b,
const char* name =
"")
804 printf(
"%s %d - %s\n", b ?
"ok" :
"ng", n++, name);
807 template <
typename T>
void is(
const T& x,
const T& y,
const char* name =
"")
823 #define TEST(expr, expected) \
824 is(picojson::value expr .serialize(), string(expected), "picojson::value" #expr)
826 TEST( (
true),
"true");
827 TEST( (
false),
"false");
829 TEST( (
string(
"hello")),
"\"hello\"");
830 TEST( (
"hello"),
"\"hello\"");
831 TEST( (
"hello", 4),
"\"hell\"");
835 #define TEST(in, type, cmp, serialize_test) { \
837 const char* s = in; \
838 string err = picojson::parse(v, s, s + strlen(s)); \
839 ok(err.empty(), in " no error"); \
840 ok(v.is<type>(), in " check type"); \
841 is<type>(v.get<type>(), cmp, in " correct output"); \
842 is(*s, '\0', in " read to eof"); \
843 if (serialize_test) { \
844 is(v.serialize(), string(in), in " serialize"); \
847 TEST(
"false",
bool,
false,
true);
848 TEST(
"true",
bool,
true,
true);
849 TEST(
"90.5",
double, 90.5,
false);
850 TEST(
"\"hello\"",
string,
string(
"hello"),
true);
851 TEST(
"\"\\\"\\\\\\/\\b\\f\\n\\r\\t\"",
string,
string(
"\"\\/\b\f\n\r\t"),
853 TEST(
"\"\\u0061\\u30af\\u30ea\\u30b9\"",
string,
854 string(
"a\xe3\x82\xaf\xe3\x83\xaa\xe3\x82\xb9"),
false);
855 TEST(
"\"\\ud840\\udc0b\"",
string,
string(
"\xf0\xa0\x80\x8b"),
false);
858 #define TEST(type, expr) { \
860 const char *s = expr; \
861 string err = picojson::parse(v, s, s + strlen(s)); \
862 ok(err.empty(), "empty " #type " no error"); \
863 ok(v.is<picojson::type>(), "empty " #type " check type"); \
864 ok(v.get<picojson::type>().empty(), "check " #type " array size"); \
872 const char *s =
"[1,true,\"hello\"]";
873 string err = picojson::parse(v, s, s + strlen(s));
874 ok(err.empty(),
"array no error");
875 ok(v.is<picojson::array>(),
"array check type");
876 is(v.get<picojson::array>().size(), size_t(3),
"check array size");
877 ok(v.contains(0),
"check contains array[0]");
878 ok(v.get(0).is<
double>(),
"check array[0] type");
879 is(v.get(0).get<
double>(), 1.0,
"check array[0] value");
880 ok(v.contains(1),
"check contains array[1]");
881 ok(v.get(1).is<
bool>(),
"check array[1] type");
882 ok(v.get(1).get<
bool>(),
"check array[1] value");
883 ok(v.contains(2),
"check contains array[2]");
884 ok(v.get(2).is<
string>(),
"check array[2] type");
885 is(v.get(2).get<
string>(),
string(
"hello"),
"check array[2] value");
886 ok(!v.contains(3),
"check not contains array[3]");
891 const char *s =
"{ \"a\": true }";
892 string err = picojson::parse(v, s, s + strlen(s));
893 ok(err.empty(),
"object no error");
894 ok(v.is<picojson::object>(),
"object check type");
895 is(v.get<picojson::object>().size(), size_t(1),
"check object size");
896 ok(v.contains(
"a"),
"check contains property");
897 ok(v.get(
"a").is<
bool>(),
"check bool property exists");
898 is(v.get(
"a").get<
bool>(),
true,
"check bool property value");
899 is(v.serialize(), string(
"{\"a\":true}"),
"serialize object");
900 ok(!v.contains(
"z"),
"check not contains property");
903 #define TEST(json, msg) do { \
905 const char *s = json; \
906 string err = picojson::parse(v, s, s + strlen(s)); \
907 is(err, string("syntax error at line " msg), msg); \
909 TEST(
"falsoa",
"1 near: oa");
910 TEST(
"{]",
"1 near: ]");
911 TEST(
"\n\bbell",
"2 near: bell");
912 TEST(
"\"abc\nd\"",
"1 near: ");
919 s =
"{ \"b\": true, \"a\": [1,2,\"three\"], \"d\": 2 }";
920 err = picojson::parse(v1, s, s + strlen(s));
921 s =
"{ \"d\": 2.0, \"b\": true, \"a\": [1,2,\"three\"] }";
922 err = picojson::parse(v2, s, s + strlen(s));
923 ok((v1 == v2),
"check == operator in deep comparison");
930 s =
"{ \"b\": true, \"a\": [1,2,\"three\"], \"d\": 2 }";
931 err = picojson::parse(v1, s, s + strlen(s));
932 s =
"{ \"d\": 2.0, \"a\": [1,\"three\"], \"b\": true }";
933 err = picojson::parse(v2, s, s + strlen(s));
934 ok((v1 != v2),
"check != operator for array in deep comparison");
941 s =
"{ \"b\": true, \"a\": [1,2,\"three\"], \"d\": 2 }";
942 err = picojson::parse(v1, s, s + strlen(s));
943 s =
"{ \"d\": 2.0, \"a\": [1,2,\"three\"], \"b\": false }";
944 err = picojson::parse(v2, s, s + strlen(s));
945 ok((v1 != v2),
"check != operator for object in deep comparison");
952 s =
"{ \"b\": true, \"a\": [1,2,\"three\"], \"d\": 2 }";
953 err = picojson::parse(v1, s, s + strlen(s));
954 picojson::object& o = v1.get<picojson::object>();
956 picojson::array& a = o[
"a"].get<picojson::array>();
957 picojson::array::iterator i;
958 i = std::remove(a.begin(), a.end(),
picojson::value(std::string(
"three")));
960 s =
"{ \"a\": [1,2], \"d\": 2 }";
961 err = picojson::parse(v2, s, s + strlen(s));
962 ok((v1 == v2),
"check erase()");
966 "integral number should be serialized as a integer");
969 const char* s =
"{ \"a\": [1,2], \"d\": 2 }";
972 picojson::_parse(ctx, s, s + strlen(s), &err);
973 ok(err.empty(),
"null_parse_context");
976 return success ? 0 : 1;