--- JSON-XS/XS.xs 2007/03/22 21:13:58 1.4 +++ JSON-XS/XS.xs 2007/03/29 02:45:49 1.21 @@ -6,45 +6,38 @@ #include "string.h" #include "stdlib.h" -#define F_ASCII 0x00000001 -#define F_UTF8 0x00000002 -#define F_INDENT 0x00000004 -#define F_CANONICAL 0x00000008 -#define F_SPACE_BEFORE 0x00000010 -#define F_SPACE_AFTER 0x00000020 -#define F_JSON_RPC 0x00000040 -#define F_ALLOW_NONREF 0x00000080 +#define F_ASCII 0x00000001UL +#define F_UTF8 0x00000002UL +#define F_INDENT 0x00000004UL +#define F_CANONICAL 0x00000008UL +#define F_SPACE_BEFORE 0x00000010UL +#define F_SPACE_AFTER 0x00000020UL +#define F_ALLOW_NONREF 0x00000080UL +#define F_SHRINK 0x00000100UL +#define F_MAXDEPTH 0xf8000000UL +#define S_MAXDEPTH 27 + +#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH)) + +// F_SELFCONVERT? <=> to_json/toJson +// F_BLESSED? <=> { $__class__$ => } #define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER -#define F_DEFAULT 0 +#define F_DEFAULT (12UL << S_MAXDEPTH) #define INIT_SIZE 32 // initial scalar size to be allocated +#define INDENT_STEP 3 // spaces per indentation level + +#define UTF8_MAX_LEN 11 // for perls UTF-X: max. number of octets per character +#define SHORT_STRING_LEN 512 // special-case strings of up to this size #define SB do { #define SE } while (0) -static HV *json_stash; +static HV *json_stash; // JSON::XS:: -// structure used for encoding JSON -typedef struct -{ - char *cur; - STRLEN len; // SvLEN (sv) - char *end; // SvEND (sv) - SV *sv; - UV flags; - int max_recurse; - int indent; -} enc_t; - -// structure used for decoding JSON -typedef struct -{ - char *cur; - char *end; - const char *err; - UV flags; -} dec_t; +///////////////////////////////////////////////////////////////////////////// +// utility functions static UV * SvJSON (SV *sv) @@ -55,7 +48,52 @@ return &SvUVX (SvRV (sv)); } +static void +shrink (SV *sv) +{ + sv_utf8_downgrade (sv, 1); + if (SvLEN (sv) > SvCUR (sv) + 1) + { +#ifdef SvPV_shrink_to_cur + SvPV_shrink_to_cur (sv); +#elif defined (SvPV_renew) + SvPV_renew (sv, SvCUR (sv) + 1); +#endif + } +} + +// decode an utf-8 character and return it, or (UV)-1 in +// case of an error. +// we special-case "safe" characters from U+80 .. U+7FF, +// but use the very good perl function to parse anything else. +// note that we never call this function for a ascii codepoints +static UV +decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen) +{ + if (s[0] > 0xdf || s[0] < 0xc2) + return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY); + else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf) + { + *clen = 2; + return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f); + } + else + return (UV)-1; +} + ///////////////////////////////////////////////////////////////////////////// +// encoder + +// structure used for encoding JSON +typedef struct +{ + char *cur; // SvPVX (sv) + current output position + char *end; // SvEND (sv) + SV *sv; // result scalar + U32 flags; // F_* + U32 indent; // indentation level + U32 maxdepth; // max. indentation/recursion level +} enc_t; static void need (enc_t *enc, STRLEN len) @@ -87,91 +125,96 @@ { unsigned char ch = *(unsigned char *)str; - if (ch == '"') - { - need (enc, len += 1); - *enc->cur++ = '\\'; - *enc->cur++ = '"'; - ++str; - } - else if (ch == '\\') - { - need (enc, len += 1); - *enc->cur++ = '\\'; - *enc->cur++ = '\\'; - ++str; - } - else if (ch >= 0x20 && ch < 0x80) // most common case - { - *enc->cur++ = ch; - ++str; - } - else if (ch == '\015') - { - need (enc, len += 1); - *enc->cur++ = '\\'; - *enc->cur++ = 'r'; - ++str; - } - else if (ch == '\012') - { - need (enc, len += 1); - *enc->cur++ = '\\'; - *enc->cur++ = 'n'; - ++str; - } - else + if (ch >= 0x20 && ch < 0x80) // most common case { - STRLEN clen; - UV uch; - - if (is_utf8) + if (ch == '"') // but with slow exceptions { - uch = utf8n_to_uvuni (str, end - str, &clen, UTF8_CHECK_ONLY); - if (clen < 0) - croak ("malformed UTF-8 character in string, cannot convert to JSON"); + need (enc, len += 1); + *enc->cur++ = '\\'; + *enc->cur++ = '"'; } - else + else if (ch == '\\') { - uch = ch; - clen = 1; + need (enc, len += 1); + *enc->cur++ = '\\'; + *enc->cur++ = '\\'; } + else + *enc->cur++ = ch; - if (uch < 0x80 || enc->flags & F_ASCII) + ++str; + } + else + { + switch (ch) { - if (uch > 0xFFFFUL) - { - need (enc, len += 11); - sprintf (enc->cur, "\\u%04x\\u%04x", - (uch - 0x10000) / 0x400 + 0xD800, - (uch - 0x10000) % 0x400 + 0xDC00); - enc->cur += 12; - } - else + case '\010': need (enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 'b'; ++str; break; + case '\011': need (enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 't'; ++str; break; + case '\012': need (enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 'n'; ++str; break; + case '\014': need (enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 'f'; ++str; break; + case '\015': need (enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 'r'; ++str; break; + + default: { - static char hexdigit [16] = "0123456789abcdef"; - need (enc, len += 5); - *enc->cur++ = '\\'; - *enc->cur++ = 'u'; - *enc->cur++ = hexdigit [ uch >> 12 ]; - *enc->cur++ = hexdigit [(uch >> 8) & 15]; - *enc->cur++ = hexdigit [(uch >> 4) & 15]; - *enc->cur++ = hexdigit [(uch >> 0) & 15]; - } + STRLEN clen; + UV uch; - str += clen; - } - else if (is_utf8) - { - need (enc, len += clen); - while (clen--) - *enc->cur++ = *str++; - } - else - { - need (enc, 10); // never more than 11 bytes needed - enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); - ++str; + if (is_utf8) + { + //uch = utf8n_to_uvuni (str, end - str, &clen, UTF8_CHECK_ONLY); + uch = decode_utf8 (str, end - str, &clen); + if (clen == (STRLEN)-1) + croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str); + } + else + { + uch = ch; + clen = 1; + } + + if (uch > 0x10FFFFUL) + croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch); + + if (uch < 0x80 || enc->flags & F_ASCII) + { + if (uch > 0xFFFFUL) + { + need (enc, len += 11); + sprintf (enc->cur, "\\u%04x\\u%04x", + (int)((uch - 0x10000) / 0x400 + 0xD800), + (int)((uch - 0x10000) % 0x400 + 0xDC00)); + enc->cur += 12; + } + else + { + static char hexdigit [16] = "0123456789abcdef"; + need (enc, len += 5); + *enc->cur++ = '\\'; + *enc->cur++ = 'u'; + *enc->cur++ = hexdigit [ uch >> 12 ]; + *enc->cur++ = hexdigit [(uch >> 8) & 15]; + *enc->cur++ = hexdigit [(uch >> 4) & 15]; + *enc->cur++ = hexdigit [(uch >> 0) & 15]; + } + + str += clen; + } + else if (is_utf8) + { + need (enc, len += clen); + do + { + *enc->cur++ = *str++; + } + while (--clen); + } + else + { + need (enc, len += UTF8_MAX_LEN - 1); // never more than 11 bytes needed + enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); + ++str; + } + } } } @@ -179,25 +222,46 @@ } } -#define INDENT SB \ - if (enc->flags & F_INDENT) \ - { \ - int i_; \ - need (enc, enc->indent); \ - for (i_ = enc->indent * 3; i_--; )\ - encode_ch (enc, ' '); \ - } \ - SE +static void +encode_indent (enc_t *enc) +{ + if (enc->flags & F_INDENT) + { + int spaces = enc->indent * INDENT_STEP; -#define SPACE SB need (enc, 1); encode_ch (enc, ' '); SE -#define NL SB if (enc->flags & F_INDENT) { need (enc, 1); encode_ch (enc, '\n'); } SE -#define COMMA SB \ - encode_ch (enc, ','); \ - if (enc->flags & F_INDENT) \ - NL; \ - else if (enc->flags & F_SPACE_AFTER) \ - SPACE; \ - SE + need (enc, spaces); + memset (enc->cur, ' ', spaces); + enc->cur += spaces; + } +} + +static void +encode_space (enc_t *enc) +{ + need (enc, 1); + encode_ch (enc, ' '); +} + +static void +encode_nl (enc_t *enc) +{ + if (enc->flags & F_INDENT) + { + need (enc, 1); + encode_ch (enc, '\n'); + } +} + +static void +encode_comma (enc_t *enc) +{ + encode_ch (enc, ','); + + if (enc->flags & F_INDENT) + encode_nl (enc); + else if (enc->flags & F_SPACE_AFTER) + encode_space (enc); +} static void encode_sv (enc_t *enc, SV *sv); @@ -206,22 +270,25 @@ { int i, len = av_len (av); - encode_ch (enc, '['); NL; + if (enc->indent >= enc->maxdepth) + croak ("data structure too deep (hit recursion limit)"); + + encode_ch (enc, '['); encode_nl (enc); ++enc->indent; for (i = 0; i <= len; ++i) { - INDENT; + encode_indent (enc); encode_sv (enc, *av_fetch (av, i, 0)); if (i < len) - COMMA; + encode_comma (enc); } - NL; + encode_nl (enc); --enc->indent; - INDENT; encode_ch (enc, ']'); + encode_indent (enc); encode_ch (enc, ']'); } static void @@ -245,9 +312,9 @@ encode_ch (enc, '"'); - if (enc->flags & F_SPACE_BEFORE) SPACE; + if (enc->flags & F_SPACE_BEFORE) encode_space (enc); encode_ch (enc, ':'); - if (enc->flags & F_SPACE_AFTER ) SPACE; + if (enc->flags & F_SPACE_AFTER ) encode_space (enc); encode_sv (enc, HeVAL (he)); } @@ -263,8 +330,8 @@ STRLEN la = HeKLEN (a); STRLEN lb = HeKLEN (b); - if (!(cmp == memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb))) - cmp = la < lb ? -1 : la == lb ? 0 : 1; + if (!(cmp = memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb))) + cmp = la - lb; return cmp; } @@ -281,7 +348,10 @@ { int count, i; - encode_ch (enc, '{'); NL; ++enc->indent; + if (enc->indent >= enc->maxdepth) + croak ("data structure too deep (hit recursion limit)"); + + encode_ch (enc, '{'); encode_nl (enc); ++enc->indent; if ((count = hv_iterinit (hv))) { @@ -291,7 +361,7 @@ // that randomises hash orderings if (enc->flags & F_CANONICAL) { - HE *he, *hes [count]; + HE *he, *hes [count]; // if your compiler dies here, you need to enable C99 mode int fast = 1; i = 0; @@ -308,28 +378,32 @@ qsort (hes, count, sizeof (HE *), he_cmp_fast); else { - // hack to disable "use bytes" - COP *oldcop = PL_curcop, cop; + // hack to forcefully disable "use bytes" + COP cop = *PL_curcop; cop.op_private = 0; - PL_curcop = &cop; + ENTER; SAVETMPS; + + SAVEVPTR (PL_curcop); + PL_curcop = &cop; + qsort (hes, count, sizeof (HE *), he_cmp_slow); - FREETMPS; - PL_curcop = oldcop; + FREETMPS; + LEAVE; } for (i = 0; i < count; ++i) { - INDENT; + encode_indent (enc); encode_he (enc, hes [i]); if (i < count - 1) - COMMA; + encode_comma (enc); } - NL; + encode_nl (enc); } else { @@ -338,20 +412,47 @@ for (;;) { - INDENT; + encode_indent (enc); encode_he (enc, he); if (!(he = hv_iternext (hv))) break; - COMMA; + encode_comma (enc); } - NL; + encode_nl (enc); } } - --enc->indent; INDENT; encode_ch (enc, '}'); + --enc->indent; encode_indent (enc); encode_ch (enc, '}'); +} + +// encode objects, arrays and special \0=false and \1=true values. +static void +encode_rv (enc_t *enc, SV *sv) +{ + SvGETMAGIC (sv); + + svtype svt = SvTYPE (sv); + + if (svt == SVt_PVHV) + encode_hv (enc, (HV *)sv); + else if (svt == SVt_PVAV) + encode_av (enc, (AV *)sv); + else if (svt < SVt_PVAV) + { + if (SvNIOK (sv) && SvIV (sv) == 0) + encode_str (enc, "false", 5, 0); + else if (SvNIOK (sv) && SvIV (sv) == 1) + encode_str (enc, "true", 4, 0); + else + croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1", + SvPV_nolen (sv_2mortal (newRV_inc (sv)))); + } + else + croak ("encountered %s, but JSON can only represent references to arrays or hashes", + SvPV_nolen (sv_2mortal (newRV_inc (sv)))); } static void @@ -382,40 +483,27 @@ : snprintf (enc->cur, 64, "%"IVdf, (IV)SvIVX (sv)); } else if (SvROK (sv)) - { - if (!--enc->max_recurse) - croak ("data structure too deep (hit recursion limit)"); - - sv = SvRV (sv); - - switch (SvTYPE (sv)) - { - case SVt_PVAV: encode_av (enc, (AV *)sv); break; - case SVt_PVHV: encode_hv (enc, (HV *)sv); break; - - default: - croak ("JSON can only represent references to arrays or hashes"); - } - } + encode_rv (enc, SvRV (sv)); else if (!SvOK (sv)) encode_str (enc, "null", 4, 0); else - croak ("encountered perl type that JSON cannot handle"); + croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this", + SvPV_nolen (sv), SvFLAGS (sv)); } static SV * -encode_json (SV *scalar, UV flags) +encode_json (SV *scalar, U32 flags) { if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar)) - croak ("hash- or arraref required (not a simple scalar, use allow_nonref to allow this)"); + croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)"); enc_t enc; - enc.flags = flags; - enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); - enc.cur = SvPVX (enc.sv); - enc.end = SvEND (enc.sv); - enc.max_recurse = 0; - enc.indent = 0; + enc.flags = flags; + enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); + enc.cur = SvPVX (enc.sv); + enc.end = SvEND (enc.sv); + enc.indent = 0; + enc.maxdepth = DEC_DEPTH (flags); SvPOK_only (enc.sv); encode_sv (&enc, scalar); @@ -424,28 +512,53 @@ SvUTF8_on (enc.sv); SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); + + if (enc.flags & F_SHRINK) + shrink (enc.sv); + return enc.sv; } ///////////////////////////////////////////////////////////////////////////// +// decoder + +// structure used for decoding JSON +typedef struct +{ + char *cur; // current parser pointer + char *end; // end of input string + const char *err; // parse error, if != 0 + U32 flags; // F_* + U32 depth; // recursion depth + U32 maxdepth; // recursion depth limit +} dec_t; + +static void +decode_ws (dec_t *dec) +{ + for (;;) + { + char ch = *dec->cur; + + if (ch > 0x20 + || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)) + break; -#define WS \ - for (;;) \ - { \ - char ch = *dec->cur; \ - if (ch > 0x20 \ - || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)) \ - break; \ - ++dec->cur; \ + ++dec->cur; } +} #define ERR(reason) SB dec->err = reason; goto fail; SE + #define EXPECT_CH(ch) SB \ if (*dec->cur != ch) \ ERR (# ch " expected"); \ ++dec->cur; \ SE +#define DEC_INC_DEPTH if (++dec->depth > dec->maxdepth) ERR ("json datastructure exceeds maximum nesting level (set a higher max_depth)") +#define DEC_DEC_DEPTH --dec->depth + static SV *decode_sv (dec_t *dec); static signed char decode_hexdigit[256]; @@ -454,15 +567,12 @@ decode_4hex (dec_t *dec) { signed char d1, d2, d3, d4; + unsigned char *cur = (unsigned char *)dec->cur; - d1 = decode_hexdigit [((unsigned char *)dec->cur) [0]]; - if (d1 < 0) ERR ("four hexadecimal digits expected"); - d2 = decode_hexdigit [((unsigned char *)dec->cur) [1]]; - if (d2 < 0) ERR ("four hexadecimal digits expected"); - d3 = decode_hexdigit [((unsigned char *)dec->cur) [2]]; - if (d3 < 0) ERR ("four hexadecimal digits expected"); - d4 = decode_hexdigit [((unsigned char *)dec->cur) [3]]; - if (d4 < 0) ERR ("four hexadecimal digits expected"); + d1 = decode_hexdigit [cur [0]]; if (d1 < 0) ERR ("four hexadecimal digits expected"); + d2 = decode_hexdigit [cur [1]]; if (d2 < 0) ERR ("four hexadecimal digits expected"); + d3 = decode_hexdigit [cur [2]]; if (d3 < 0) ERR ("four hexadecimal digits expected"); + d4 = decode_hexdigit [cur [3]]; if (d4 < 0) ERR ("four hexadecimal digits expected"); dec->cur += 4; @@ -475,123 +585,142 @@ return (UV)-1; } -#define APPEND_GROW(n) SB \ - if (cur + (n) >= end) \ - { \ - STRLEN ofs = cur - SvPVX (sv); \ - SvGROW (sv, ofs + (n) + 1); \ - cur = SvPVX (sv) + ofs; \ - end = SvEND (sv); \ - } \ - SE - -#define APPEND_CH(ch) SB \ - APPEND_GROW (1); \ - *cur++ = (ch); \ - SE - static SV * decode_str (dec_t *dec) { - SV *sv = NEWSV (0,2); + SV *sv = 0; int utf8 = 0; - char *cur = SvPVX (sv); - char *end = SvEND (sv); - for (;;) + do { - unsigned char ch = *(unsigned char *)dec->cur; + char buf [SHORT_STRING_LEN + UTF8_MAX_LEN]; + char *cur = buf; - if (ch == '"') - break; - else if (ch == '\\') + do { - switch (*++dec->cur) - { - case '\\': - case '/': - case '"': APPEND_CH (*dec->cur++); break; - - case 'b': APPEND_CH ('\010'); ++dec->cur; break; - case 't': APPEND_CH ('\011'); ++dec->cur; break; - case 'n': APPEND_CH ('\012'); ++dec->cur; break; - case 'f': APPEND_CH ('\014'); ++dec->cur; break; - case 'r': APPEND_CH ('\015'); ++dec->cur; break; + unsigned char ch = *(unsigned char *)dec->cur++; - case 'u': + if (ch == '"') + { + --dec->cur; + break; + } + else if (ch == '\\') + { + switch (*dec->cur) { - UV lo, hi; - ++dec->cur; - - hi = decode_4hex (dec); - if (hi == (UV)-1) - goto fail; + case '\\': + case '/': + case '"': *cur++ = *dec->cur++; break; + + case 'b': ++dec->cur; *cur++ = '\010'; break; + case 't': ++dec->cur; *cur++ = '\011'; break; + case 'n': ++dec->cur; *cur++ = '\012'; break; + case 'f': ++dec->cur; *cur++ = '\014'; break; + case 'r': ++dec->cur; *cur++ = '\015'; break; - // possibly a surrogate pair - if (hi >= 0xd800 && hi < 0xdc00) + case 'u': { - if (dec->cur [0] != '\\' || dec->cur [1] != 'u') - ERR ("illegal surrogate character"); + UV lo, hi; + ++dec->cur; - dec->cur += 2; - - lo = decode_4hex (dec); - if (lo == (UV)-1) + hi = decode_4hex (dec); + if (hi == (UV)-1) goto fail; - if (lo < 0xdc00 || lo >= 0xe000) - ERR ("surrogate pair expected"); - - hi = (hi - 0xD800) * 0x400 + (lo - 0xDC00) + 0x10000; + // possibly a surrogate pair + if (hi >= 0xd800) + if (hi < 0xdc00) + { + if (dec->cur [0] != '\\' || dec->cur [1] != 'u') + ERR ("missing low surrogate character in surrogate pair"); + + dec->cur += 2; + + lo = decode_4hex (dec); + if (lo == (UV)-1) + goto fail; + + if (lo < 0xdc00 || lo >= 0xe000) + ERR ("surrogate pair expected"); + + hi = (hi - 0xD800) * 0x400 + (lo - 0xDC00) + 0x10000; + } + else if (hi < 0xe000) + ERR ("missing high surrogate character in surrogate pair"); + + if (hi >= 0x80) + { + utf8 = 1; + + cur = (char *)uvuni_to_utf8_flags (cur, hi, 0); + } + else + *cur++ = hi; } - else if (lo >= 0xdc00 && lo < 0xe000) - ERR ("illegal surrogate character"); + break; - if (hi >= 0x80) - { - utf8 = 1; + default: + --dec->cur; + ERR ("illegal backslash escape sequence in string"); + } + } + else if (ch >= 0x20 && ch <= 0x7f) + *cur++ = ch; + else if (ch >= 0x80) + { + --dec->cur; - APPEND_GROW (4); // at most 4 bytes for 21 bits - cur = (char *)uvuni_to_utf8_flags (cur, hi, 0); - } - else - APPEND_CH (hi); + STRLEN clen; + UV uch = decode_utf8 (dec->cur, dec->end - dec->cur, &clen); + if (clen == (STRLEN)-1) + ERR ("malformed UTF-8 character in JSON string"); + + do + { + *cur++ = *dec->cur++; } - break; + while (--clen); + + utf8 = 1; } + else if (!ch) + ERR ("unexpected end of string while parsing json string"); + else + ERR ("invalid character encountered"); + } - else if (ch >= 0x20 && ch <= 0x7f) - APPEND_CH (*dec->cur++); - else if (ch >= 0x80) + while (cur < buf + SHORT_STRING_LEN); + + STRLEN len = cur - buf; + + if (sv) { - STRLEN clen; - UV uch = utf8n_to_uvuni (dec->cur, dec->end - dec->cur, &clen, UTF8_CHECK_ONLY); - if (clen < 0) - ERR ("malformed UTF-8 character in string, cannot convert to JSON"); - - APPEND_GROW (clen); - memcpy (cur, dec->cur, clen); - cur += clen; - dec->cur += clen; + SvGROW (sv, SvCUR (sv) + len + 1); + memcpy (SvPVX (sv) + SvCUR (sv), buf, len); + SvCUR_set (sv, SvCUR (sv) + len); } else - ERR ("invalid character encountered"); + sv = newSVpvn (buf, len); } + while (*dec->cur != '"'); ++dec->cur; - SvCUR_set (sv, cur - SvPVX (sv)); - - SvPOK_only (sv); - *SvEND (sv) = 0; + if (sv) + { + SvPOK_only (sv); + *SvEND (sv) = 0; - if (utf8) - SvUTF8_on (sv); + if (utf8) + SvUTF8_on (sv); + } + else + sv = newSVpvn ("", 0); return sv; fail: - SvREFCNT_dec (sv); return 0; } @@ -611,34 +740,50 @@ if (*dec->cur >= '0' && *dec->cur <= '9') ERR ("malformed number (leading zero must not be followed by another digit)"); } - - // int - while (*dec->cur >= '0' && *dec->cur <= '9') - ++dec->cur; + else if (*dec->cur < '0' || *dec->cur > '9') + ERR ("malformed number (no digits after initial minus)"); + else + do + { + ++dec->cur; + } + while (*dec->cur >= '0' && *dec->cur <= '9'); // [frac] if (*dec->cur == '.') { - is_nv = 1; + ++dec->cur; + + if (*dec->cur < '0' || *dec->cur > '9') + ERR ("malformed number (no digits after decimal point)"); do { ++dec->cur; } while (*dec->cur >= '0' && *dec->cur <= '9'); + + is_nv = 1; } // [exp] if (*dec->cur == 'e' || *dec->cur == 'E') { - is_nv = 1; - ++dec->cur; + if (*dec->cur == '-' || *dec->cur == '+') ++dec->cur; - while (*dec->cur >= '0' && *dec->cur <= '9') - ++dec->cur; + if (*dec->cur < '0' || *dec->cur > '9') + ERR ("malformed number (no digits after exp sign)"); + + do + { + ++dec->cur; + } + while (*dec->cur >= '0' && *dec->cur <= '9'); + + is_nv = 1; } if (!is_nv) @@ -666,34 +811,42 @@ { AV *av = newAV (); - for (;;) - { - SV *value; + DEC_INC_DEPTH; + decode_ws (dec); - value = decode_sv (dec); - if (!value) - goto fail; + if (*dec->cur == ']') + ++dec->cur; + else + for (;;) + { + SV *value; - av_push (av, value); + value = decode_sv (dec); + if (!value) + goto fail; - WS; + av_push (av, value); - if (*dec->cur == ']') - { - ++dec->cur; - break; - } - - if (*dec->cur != ',') - ERR (", or ] expected while parsing array"); + decode_ws (dec); - ++dec->cur; - } + if (*dec->cur == ']') + { + ++dec->cur; + break; + } + + if (*dec->cur != ',') + ERR (", or ] expected while parsing array"); + + ++dec->cur; + } + DEC_DEC_DEPTH; return newRV_noinc ((SV *)av); fail: SvREFCNT_dec (av); + DEC_DEC_DEPTH; return 0; } @@ -702,53 +855,61 @@ { HV *hv = newHV (); - for (;;) - { - SV *key, *value; + DEC_INC_DEPTH; + decode_ws (dec); - WS; EXPECT_CH ('"'); - - key = decode_str (dec); - if (!key) - goto fail; + if (*dec->cur == '}') + ++dec->cur; + else + for (;;) + { + SV *key, *value; - WS; EXPECT_CH (':'); + decode_ws (dec); EXPECT_CH ('"'); - value = decode_sv (dec); - if (!value) - { - SvREFCNT_dec (key); + key = decode_str (dec); + if (!key) goto fail; - } - //TODO: optimise - hv_store_ent (hv, key, value, 0); + decode_ws (dec); EXPECT_CH (':'); + + value = decode_sv (dec); + if (!value) + { + SvREFCNT_dec (key); + goto fail; + } - WS; + hv_store_ent (hv, key, value, 0); + SvREFCNT_dec (key); - if (*dec->cur == '}') - { - ++dec->cur; - break; - } + decode_ws (dec); - if (*dec->cur != ',') - ERR (", or } expected while parsing object/hash"); + if (*dec->cur == '}') + { + ++dec->cur; + break; + } - ++dec->cur; - } + if (*dec->cur != ',') + ERR (", or } expected while parsing object/hash"); + + ++dec->cur; + } + DEC_DEC_DEPTH; return newRV_noinc ((SV *)hv); fail: SvREFCNT_dec (hv); + DEC_DEC_DEPTH; return 0; } static SV * decode_sv (dec_t *dec) { - WS; + decode_ws (dec); switch (*dec->cur) { case '"': ++dec->cur; return decode_str (dec); @@ -786,7 +947,7 @@ if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "null", 4)) { dec->cur += 4; - return newSViv (1); + return newSVsv (&PL_sv_undef); } else ERR ("'null' expected"); @@ -794,7 +955,7 @@ break; default: - ERR ("malformed json string"); + ERR ("malformed json string, neither array, object, number, string or atom"); break; } @@ -803,32 +964,45 @@ } static SV * -decode_json (SV *string, UV flags) +decode_json (SV *string, U32 flags) { SV *sv; - if (!(flags & F_UTF8)) + if (flags & F_UTF8) + sv_utf8_downgrade (string, 0); + else sv_utf8_upgrade (string); SvGROW (string, SvCUR (string) + 1); // should basically be a NOP dec_t dec; - dec.flags = flags; - dec.cur = SvPVX (string); - dec.end = SvEND (string); - dec.err = 0; + dec.flags = flags; + dec.cur = SvPVX (string); + dec.end = SvEND (string); + dec.err = 0; + dec.depth = 0; + dec.maxdepth = DEC_DEPTH (dec.flags); - *dec.end = 1; // invalid anywhere + *dec.end = 0; // this should basically be a nop, too, but make sure its there sv = decode_sv (&dec); - *dec.end = 0; if (!sv) { - IV offset = utf8_distance (dec.cur, SvPVX (string)); + IV offset = dec.flags & F_UTF8 + ? dec.cur - SvPVX (string) + : utf8_distance (dec.cur, SvPVX (string)); SV *uni = sv_newmortal (); + // horrible hack to silence warning inside pv_uni_display + COP cop = *PL_curcop; + cop.cop_warnings = pWARN_NONE; + ENTER; + SAVEVPTR (PL_curcop); + PL_curcop = &cop; pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ); - croak ("%s, at character %d (%s)", + LEAVE; + + croak ("%s, at character offset %d (%s)", dec.err, (int)offset, dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); @@ -837,11 +1011,14 @@ sv = sv_2mortal (sv); if (!(dec.flags & F_ALLOW_NONREF) && !SvROK (sv)) - croak ("JSON object or array expected (but number, string, true, false or null found, use allow_nonref to allow this)"); + croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)"); return sv; } +///////////////////////////////////////////////////////////////////////////// +// XS interface functions + MODULE = JSON::XS PACKAGE = JSON::XS BOOT: @@ -849,14 +1026,13 @@ int i; memset (decode_hexdigit, 0xff, 256); - for (i = 10; i--; ) - decode_hexdigit ['0' + i] = i; - for (i = 7; i--; ) - { - decode_hexdigit ['a' + i] = 10 + i; - decode_hexdigit ['A' + i] = 10 + i; - } + for (i = 0; i < 256; ++i) + decode_hexdigit [i] = + i >= '0' && i <= '9' ? i - '0' + : i >= 'a' && i <= 'f' ? i - 'a' + 10 + : i >= 'A' && i <= 'F' ? i - 'A' + 10 + : -1; json_stash = gv_stashpv ("JSON::XS", 1); } @@ -869,7 +1045,7 @@ OUTPUT: RETVAL -SV *ascii (SV *self, int enable) +SV *ascii (SV *self, int enable = 1) ALIAS: ascii = F_ASCII utf8 = F_UTF8 @@ -877,9 +1053,9 @@ canonical = F_CANONICAL space_before = F_SPACE_BEFORE space_after = F_SPACE_AFTER - json_rpc = F_JSON_RPC pretty = F_PRETTY allow_nonref = F_ALLOW_NONREF + shrink = F_SHRINK CODE: { UV *uv = SvJSON (self); @@ -893,6 +1069,24 @@ OUTPUT: RETVAL +SV *max_depth (SV *self, int max_depth = 0x80000000UL) + CODE: +{ + UV *uv = SvJSON (self); + UV log2 = 0; + + if (max_depth > 0x80000000UL) max_depth = 0x80000000UL; + + while ((1UL << log2) < max_depth) + ++log2; + + *uv = *uv & ~F_MAXDEPTH | (log2 << S_MAXDEPTH); + + RETVAL = newSVsv (self); +} + OUTPUT: + RETVAL + void encode (SV *self, SV *scalar) PPCODE: XPUSHs (encode_json (scalar, *SvJSON (self))); @@ -904,10 +1098,14 @@ PROTOTYPES: ENABLE void to_json (SV *scalar) + ALIAS: + objToJson = 0 PPCODE: - XPUSHs (encode_json (scalar, F_UTF8)); + XPUSHs (encode_json (scalar, F_DEFAULT | F_UTF8)); void from_json (SV *jsonstr) + ALIAS: + jsonToObj = 0 PPCODE: - XPUSHs (decode_json (jsonstr, F_UTF8)); + XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8));