2 * Copyright 2009-2010 Cybozu Labs, Inc.
3 * Copyright 2011-2014 Kazuho Oku
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
9 * 1. Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
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.
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.
44 #if __cplusplus>=201103L
50 # elif defined(__INTEL_COMPILER)
58 // experimental support for int64_t (see README.mkdn for detail)
59 #ifdef PICOJSON_USE_INT64
60 # define __STDC_FORMAT_MACROS
62 # include <inttypes.h>
65 // to disable the use of localeconv(3), set PICOJSON_USE_LOCALE to 0
66 #ifndef PICOJSON_USE_LOCALE
67 # define PICOJSON_USE_LOCALE 1
69 #if PICOJSON_USE_LOCALE
75 #ifndef PICOJSON_ASSERT
76 # define PICOJSON_ASSERT(e) do { if (! (e)) throw std::runtime_error(#e); } while (0)
80 #define SNPRINTF _snprintf_s
82 #pragma warning(disable : 4244) // conversion from int to char
83 #pragma warning(disable : 4127) // conditional expression is constant
84 #pragma warning(disable : 4702) // unreachable code
86 #define SNPRINTF snprintf
98 #ifdef PICOJSON_USE_INT64
111 typedef std::vector<value> array;
112 typedef std::map<std::string, value> object;
116 #ifdef PICOJSON_USE_INT64
119 std::string* string_;
128 value(int type, bool);
129 explicit value(bool b);
130 #ifdef PICOJSON_USE_INT64
131 explicit value(int64_t i);
133 explicit value(double n);
134 explicit value(const std::string& s);
135 explicit value(const array& a);
136 explicit value(const object& o);
137 explicit value(const char* s);
138 value(const char* s, size_t len);
140 value(const value& x);
141 value& operator=(const value& x);
143 template <typename T> bool is() const;
144 template <typename T> const T& get() const;
145 template <typename T> T& get();
146 bool evaluate_as_boolean() const;
147 const value& get(size_t idx) const;
148 const value& get(const std::string& key) const;
149 value& get(size_t idx);
150 value& get(const std::string& key);
152 bool contains(size_t idx) const;
153 bool contains(const std::string& key) const;
154 std::string to_str() const;
155 template <typename Iter> void serialize(Iter os, bool prettify = false) const;
156 std::string serialize(bool prettify = false) const;
158 template <typename T> value(const T*); // intentionally defined to block implicit conversion of pointer to bool
159 template <typename Iter> static void _indent(Iter os, int indent);
160 template <typename Iter> void _serialize(Iter os, int indent) const;
161 std::string _serialize(int indent) const;
164 typedef value::array array;
165 typedef value::object object;
167 inline value::value() : type_(null_type) {}
169 inline value::value(int type, bool) : type_(type) {
171 #define INIT(p, v) case p##type: u_.p = v; break
172 INIT(boolean_, false);
174 #ifdef PICOJSON_USE_INT64
177 INIT(string_, new std::string());
178 INIT(array_, new array());
179 INIT(object_, new object());
185 inline value::value(bool b) : type_(boolean_type) {
189 #ifdef PICOJSON_USE_INT64
190 inline value::value(int64_t i) : type_(int64_type) {
195 inline value::value(double n) : type_(number_type) {
199 #elif __cplusplus>=201103L || !(defined(isnan) && defined(isinf))
200 std::isnan(n) || std::isinf(n)
205 throw std::overflow_error("");
210 inline value::value(const std::string& s) : type_(string_type) {
211 u_.string_ = new std::string(s);
214 inline value::value(const array& a) : type_(array_type) {
215 u_.array_ = new array(a);
218 inline value::value(const object& o) : type_(object_type) {
219 u_.object_ = new object(o);
222 inline value::value(const char* s) : type_(string_type) {
223 u_.string_ = new std::string(s);
226 inline value::value(const char* s, size_t len) : type_(string_type) {
227 u_.string_ = new std::string(s, len);
230 inline value::~value() {
232 #define DEINIT(p) case p##type: delete u_.p; break
241 inline value::value(const value& x) : type_(x.type_) {
243 #define INIT(p, v) case p##type: u_.p = v; break
244 INIT(string_, new std::string(*x.u_.string_));
245 INIT(array_, new array(*x.u_.array_));
246 INIT(object_, new object(*x.u_.object_));
254 inline value& value::operator=(const value& x) {
262 inline void value::swap(value& x) {
263 std::swap(type_, x.type_);
267 #define IS(ctype, jtype) \
268 template <> inline bool value::is<ctype>() const { \
269 return type_ == jtype##_type; \
273 #ifdef PICOJSON_USE_INT64
276 IS(std::string, string)
280 template <> inline bool value::is<double>() const {
281 return type_ == number_type
282 #ifdef PICOJSON_USE_INT64
283 || type_ == int64_type
288 #define GET(ctype, var) \
289 template <> inline const ctype& value::get<ctype>() const { \
290 PICOJSON_ASSERT("type mismatch! call is<type>() before get<type>()" \
294 template <> inline ctype& value::get<ctype>() { \
295 PICOJSON_ASSERT("type mismatch! call is<type>() before get<type>()" \
299 GET(bool, u_.boolean_)
300 GET(std::string, *u_.string_)
301 GET(array, *u_.array_)
302 GET(object, *u_.object_)
303 #ifdef PICOJSON_USE_INT64
304 GET(double, (type_ == int64_type && (const_cast<value*>(this)->type_ = number_type, const_cast<value*>(this)->u_.number_ = u_.int64_), u_.number_))
305 GET(int64_t, u_.int64_)
307 GET(double, u_.number_)
311 inline bool value::evaluate_as_boolean() const {
318 return u_.number_ != 0;
320 return ! u_.string_->empty();
326 inline const value& value::get(size_t idx) const {
328 PICOJSON_ASSERT(is<array>());
329 return idx < u_.array_->size() ? (*u_.array_)[idx] : s_null;
332 inline value& value::get(size_t idx) {
334 PICOJSON_ASSERT(is<array>());
335 return idx < u_.array_->size() ? (*u_.array_)[idx] : s_null;
338 inline const value& value::get(const std::string& key) const {
340 PICOJSON_ASSERT(is<object>());
341 object::const_iterator i = u_.object_->find(key);
342 return i != u_.object_->end() ? i->second : s_null;
345 inline value& value::get(const std::string& key) {
347 PICOJSON_ASSERT(is<object>());
348 object::iterator i = u_.object_->find(key);
349 return i != u_.object_->end() ? i->second : s_null;
352 inline bool value::contains(size_t idx) const {
353 PICOJSON_ASSERT(is<array>());
354 return idx < u_.array_->size();
357 inline bool value::contains(const std::string& key) const {
358 PICOJSON_ASSERT(is<object>());
359 object::const_iterator i = u_.object_->find(key);
360 return i != u_.object_->end();
363 inline std::string value::to_str() const {
365 case null_type: return "null";
366 case boolean_type: return u_.boolean_ ? "true" : "false";
367 #ifdef PICOJSON_USE_INT64
369 char buf[sizeof("-9223372036854775808")];
370 SNPRINTF(buf, sizeof(buf), "%" PRId64, u_.int64_);
377 SNPRINTF(buf, sizeof(buf), fabs(u_.number_) < (1ULL << 53) && modf(u_.number_, &tmp) == 0 ? "%.f" : "%.17g", u_.number_);
378 #if PICOJSON_USE_LOCALE
379 char *decimal_point = localeconv()->decimal_point;
380 if (strcmp(decimal_point, ".") != 0) {
381 size_t decimal_point_len = strlen(decimal_point);
382 for (char *p = buf; *p != '\0'; ++p) {
383 if (strncmp(p, decimal_point, decimal_point_len) == 0) {
384 return std::string(buf, p) + "." + (p + decimal_point_len);
391 case string_type: return *u_.string_;
392 case array_type: return "array";
393 case object_type: return "object";
394 default: PICOJSON_ASSERT(0);
399 return std::string();
402 template <typename Iter> void copy(const std::string& s, Iter oi) {
403 std::copy(s.begin(), s.end(), oi);
406 template <typename Iter> void serialize_str(const std::string& s, Iter oi) {
408 for (std::string::const_iterator i = s.begin(); i != s.end(); ++i) {
410 #define MAP(val, sym) case val: copy(sym, oi); break
421 if (static_cast<unsigned char>(*i) < 0x20 || *i == 0x7f) {
423 SNPRINTF(buf, sizeof(buf), "\\u%04x", *i & 0xff);
424 copy(buf, buf + 6, oi);
434 template <typename Iter> void value::serialize(Iter oi, bool prettify) const {
435 return _serialize(oi, prettify ? 0 : -1);
438 inline std::string value::serialize(bool prettify) const {
439 return _serialize(prettify ? 0 : -1);
442 template <typename Iter> void value::_indent(Iter oi, int indent) {
444 for (int i = 0; i < indent * INDENT_WIDTH; ++i) {
449 template <typename Iter> void value::_serialize(Iter oi, int indent) const {
452 serialize_str(*u_.string_, oi);
459 for (array::const_iterator i = u_.array_->begin();
460 i != u_.array_->end();
462 if (i != u_.array_->begin()) {
468 i->_serialize(oi, indent);
472 if (! u_.array_->empty()) {
484 for (object::const_iterator i = u_.object_->begin();
485 i != u_.object_->end();
487 if (i != u_.object_->begin()) {
493 serialize_str(i->first, oi);
498 i->second._serialize(oi, indent);
502 if (! u_.object_->empty()) {
518 inline std::string value::_serialize(int indent) const {
520 _serialize(std::back_inserter(s), indent);
524 template <typename Iter> class input {
531 input(const Iter& first, const Iter& last) : cur_(first), end_(last), last_ch_(-1), ungot_(false), line_(1) {}
541 if (last_ch_ == '\n') {
544 last_ch_ = *cur_ & 0xff;
549 if (last_ch_ != -1) {
550 PICOJSON_ASSERT(! ungot_);
554 Iter cur() const { return cur_; }
555 int line() const { return line_; }
559 if (! (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')) {
565 bool expect(int expect) {
567 if (getc() != expect) {
573 bool match(const std::string& pattern) {
574 for (std::string::const_iterator pi(pattern.begin());
586 template<typename Iter> inline int _parse_quadhex(input<Iter> &in) {
588 for (int i = 0; i < 4; i++) {
589 if ((hex = in.getc()) == -1) {
592 if ('0' <= hex && hex <= '9') {
594 } else if ('A' <= hex && hex <= 'F') {
596 } else if ('a' <= hex && hex <= 'f') {
602 uni_ch = uni_ch * 16 + hex;
607 template<typename String, typename Iter> inline bool _parse_codepoint(String& out, input<Iter>& in) {
609 if ((uni_ch = _parse_quadhex(in)) == -1) {
612 if (0xd800 <= uni_ch && uni_ch <= 0xdfff) {
613 if (0xdc00 <= uni_ch) {
614 // a second 16-bit of a surrogate pair appeared
617 // first 16-bit of surrogate pair, get the next one
618 if (in.getc() != '\\' || in.getc() != 'u') {
622 int second = _parse_quadhex(in);
623 if (! (0xdc00 <= second && second <= 0xdfff)) {
626 uni_ch = ((uni_ch - 0xd800) << 10) | ((second - 0xdc00) & 0x3ff);
630 out.push_back(uni_ch);
632 if (uni_ch < 0x800) {
633 out.push_back(0xc0 | (uni_ch >> 6));
635 if (uni_ch < 0x10000) {
636 out.push_back(0xe0 | (uni_ch >> 12));
638 out.push_back(0xf0 | (uni_ch >> 18));
639 out.push_back(0x80 | ((uni_ch >> 12) & 0x3f));
641 out.push_back(0x80 | ((uni_ch >> 6) & 0x3f));
643 out.push_back(0x80 | (uni_ch & 0x3f));
648 template<typename String, typename Iter> inline bool _parse_string(String& out, input<Iter>& in) {
654 } else if (ch == '"') {
656 } else if (ch == '\\') {
657 if ((ch = in.getc()) == -1) {
661 #define MAP(sym, val) case sym: out.push_back(val); break
672 if (! _parse_codepoint(out, in)) {
686 template <typename Context, typename Iter> inline bool _parse_array(Context& ctx, input<Iter>& in) {
687 if (! ctx.parse_array_start()) {
691 if (in.expect(']')) {
692 return ctx.parse_array_stop(idx);
695 if (! ctx.parse_array_item(in, idx)) {
699 } while (in.expect(','));
700 return in.expect(']') && ctx.parse_array_stop(idx);
703 template <typename Context, typename Iter> inline bool _parse_object(Context& ctx, input<Iter>& in) {
704 if (! ctx.parse_object_start()) {
707 if (in.expect('}')) {
713 || ! _parse_string(key, in)
714 || ! in.expect(':')) {
717 if (! ctx.parse_object_item(in, key)) {
720 } while (in.expect(','));
721 return in.expect('}');
724 template <typename Iter> inline std::string _parse_number(input<Iter>& in) {
728 if (('0' <= ch && ch <= '9') || ch == '+' || ch == '-'
729 || ch == 'e' || ch == 'E') {
730 num_str.push_back(ch);
731 } else if (ch == '.') {
732 #if PICOJSON_USE_LOCALE
733 num_str += localeconv()->decimal_point;
735 num_str.push_back('.');
745 template <typename Context, typename Iter> inline bool _parse(Context& ctx, input<Iter>& in) {
749 #define IS(ch, text, op) case ch: \
750 if (in.match(text) && op) { \
755 IS('n', "ull", ctx.set_null());
756 IS('f', "alse", ctx.set_bool(false));
757 IS('t', "rue", ctx.set_bool(true));
760 return ctx.parse_string(in);
762 return _parse_array(ctx, in);
764 return _parse_object(ctx, in);
766 if (('0' <= ch && ch <= '9') || ch == '-') {
770 std::string num_str = _parse_number(in);
771 if (num_str.empty()) {
774 #ifdef PICOJSON_USE_INT64
777 intmax_t ival = strtoimax(num_str.c_str(), &endp, 10);
779 && std::numeric_limits<int64_t>::min() <= ival
780 && ival <= std::numeric_limits<int64_t>::max()
781 && endp == num_str.c_str() + num_str.size()) {
787 f = strtod(num_str.c_str(), &endp);
788 if (endp == num_str.c_str() + num_str.size()) {
800 class deny_parse_context {
802 bool set_null() { return false; }
803 bool set_bool(bool) { return false; }
804 #ifdef PICOJSON_USE_INT64
805 bool set_int64(int64_t) { return false; }
807 bool set_number(double) { return false; }
808 template <typename Iter> bool parse_string(input<Iter>&) { return false; }
809 bool parse_array_start() { return false; }
810 template <typename Iter> bool parse_array_item(input<Iter>&, size_t) {
813 bool parse_array_stop(size_t) { return false; }
814 bool parse_object_start() { return false; }
815 template <typename Iter> bool parse_object_item(input<Iter>&, const std::string&) {
820 class default_parse_context {
824 default_parse_context(value* out) : out_(out) {}
829 bool set_bool(bool b) {
833 #ifdef PICOJSON_USE_INT64
834 bool set_int64(int64_t i) {
839 bool set_number(double f) {
843 template<typename Iter> bool parse_string(input<Iter>& in) {
844 *out_ = value(string_type, false);
845 return _parse_string(out_->get<std::string>(), in);
847 bool parse_array_start() {
848 *out_ = value(array_type, false);
851 template <typename Iter> bool parse_array_item(input<Iter>& in, size_t) {
852 array& a = out_->get<array>();
853 a.push_back(value());
854 default_parse_context ctx(&a.back());
855 return _parse(ctx, in);
857 bool parse_array_stop(size_t) { return true; }
858 bool parse_object_start() {
859 *out_ = value(object_type, false);
862 template <typename Iter> bool parse_object_item(input<Iter>& in, const std::string& key) {
863 object& o = out_->get<object>();
864 default_parse_context ctx(&o[key]);
865 return _parse(ctx, in);
868 default_parse_context(const default_parse_context&);
869 default_parse_context& operator=(const default_parse_context&);
872 class null_parse_context {
875 void push_back(int) {}
878 null_parse_context() {}
879 bool set_null() { return true; }
880 bool set_bool(bool) { return true; }
881 #ifdef PICOJSON_USE_INT64
882 bool set_int64(int64_t) { return true; }
884 bool set_number(double) { return true; }
885 template <typename Iter> bool parse_string(input<Iter>& in) {
887 return _parse_string(s, in);
889 bool parse_array_start() { return true; }
890 template <typename Iter> bool parse_array_item(input<Iter>& in, size_t) {
891 return _parse(*this, in);
893 bool parse_array_stop(size_t) { return true; }
894 bool parse_object_start() { return true; }
895 template <typename Iter> bool parse_object_item(input<Iter>& in, const std::string&) {
896 return _parse(*this, in);
899 null_parse_context(const null_parse_context&);
900 null_parse_context& operator=(const null_parse_context&);
903 // obsolete, use the version below
904 template <typename Iter> inline std::string parse(value& out, Iter& pos, const Iter& last) {
906 pos = parse(out, pos, last, &err);
910 template <typename Context, typename Iter> inline Iter _parse(Context& ctx, const Iter& first, const Iter& last, std::string* err) {
911 input<Iter> in(first, last);
912 if (! _parse(ctx, in) && err != NULL) {
914 SNPRINTF(buf, sizeof(buf), "syntax error at line %d near: ", in.line());
918 if (ch == -1 || ch == '\n') {
920 } else if (ch >= ' ') {
928 template <typename Iter> inline Iter parse(value& out, const Iter& first, const Iter& last, std::string* err) {
929 default_parse_context ctx(&out);
930 return _parse(ctx, first, last, err);
933 inline std::string parse(value& out, const std::string& s) {
935 parse(out, s.begin(), s.end(), &err);
939 inline std::string parse(value& out, std::istream& is) {
941 parse(out, std::istreambuf_iterator<char>(is.rdbuf()),
942 std::istreambuf_iterator<char>(), &err);
946 template <typename T> struct last_error_t {
947 static std::string s;
949 template <typename T> std::string last_error_t<T>::s;
951 inline void set_last_error(const std::string& s) {
952 last_error_t<bool>::s = s;
955 inline const std::string& get_last_error() {
956 return last_error_t<bool>::s;
959 inline bool operator==(const value& x, const value& y) {
962 #define PICOJSON_CMP(type) \
964 return y.is<type>() && x.get<type>() == y.get<type>()
966 PICOJSON_CMP(double);
967 PICOJSON_CMP(std::string);
969 PICOJSON_CMP(object);
978 inline bool operator!=(const value& x, const value& y) {
984 template<> inline void swap(picojson::value& x, picojson::value& y)
990 inline std::istream& operator>>(std::istream& is, picojson::value& x)
992 picojson::set_last_error(std::string());
993 std::string err = picojson::parse(x, is);
995 picojson::set_last_error(err);
996 is.setstate(std::ios::failbit);
1001 inline std::ostream& operator<<(std::ostream& os, const picojson::value& x)
1003 x.serialize(std::ostream_iterator<char>(os));
1007 #pragma warning(pop)