--- JSON-XS/XS.xs 2007/03/23 15:57:18 1.7 +++ JSON-XS/XS.xs 2007/03/24 22:10:08 1.12 @@ -12,7 +12,6 @@ #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_SHRINK 0x00000100 @@ -20,32 +19,18 @@ #define F_DEFAULT 0 #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 256 // special-case strings of up to this size #define SB do { #define SE } while (0) -static HV *json_stash; - -// 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; +static HV *json_stash; // JSON::XS:: -// 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) @@ -60,12 +45,29 @@ shrink (SV *sv) { sv_utf8_downgrade (sv, 1); + if (SvLEN (sv) > SvCUR (sv) + 1) + { #ifdef SvPV_shrink_to_cur - SvPV_shrink_to_cur (sv); + SvPV_shrink_to_cur (sv); +#elif defined (SvPV_renew) + SvPV_renew (sv, SvCUR (sv) + 1); #endif + } } ///////////////////////////////////////////////////////////////////////////// +// encoder + +// structure used for encoding JSON +typedef struct +{ + char *cur; // SvPVX (sv) + current output position + char *end; // SvEND (sv) + SV *sv; // result scalar + UV flags; // F_* + int indent; // indentation level + int max_depth; // max. recursion level +} enc_t; static void need (enc_t *enc, STRLEN len) @@ -135,7 +137,7 @@ { uch = utf8n_to_uvuni (str, end - str, &clen, UTF8_CHECK_ONLY); if (clen == (STRLEN)-1) - croak ("malformed UTF-8 character in string, cannot convert to JSON"); + croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str); } else { @@ -143,14 +145,17 @@ 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", - (uch - 0x10000) / 0x400 + 0xD800, - (uch - 0x10000) % 0x400 + 0xDC00); + (int)((uch - 0x10000) / 0x400 + 0xD800), + (int)((uch - 0x10000) % 0x400 + 0xDC00)); enc->cur += 12; } else @@ -178,7 +183,7 @@ } else { - need (enc, len += 10); // never more than 11 bytes needed + need (enc, len += UTF8_MAX_LEN - 1); // never more than 11 bytes needed enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); ++str; } @@ -190,25 +195,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); @@ -217,22 +243,22 @@ { int i, len = av_len (av); - encode_ch (enc, '['); NL; + 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 @@ -256,9 +282,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)); } @@ -274,8 +300,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; } @@ -292,7 +318,7 @@ { int count, i; - encode_ch (enc, '{'); NL; ++enc->indent; + encode_ch (enc, '{'); encode_nl (enc); ++enc->indent; if ((count = hv_iterinit (hv))) { @@ -302,7 +328,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; @@ -319,28 +345,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 { @@ -349,20 +379,20 @@ 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, '}'); } static void @@ -394,39 +424,41 @@ } else if (SvROK (sv)) { - if (!--enc->max_recurse) - croak ("data structure too deep (hit recursion limit)"); + SV *rv = SvRV (sv); - sv = SvRV (sv); + if (enc->indent >= enc->max_depth) + croak ("data structure too deep (hit recursion limit)"); - switch (SvTYPE (sv)) + switch (SvTYPE (rv)) { - case SVt_PVAV: encode_av (enc, (AV *)sv); break; - case SVt_PVHV: encode_hv (enc, (HV *)sv); break; + case SVt_PVAV: encode_av (enc, (AV *)rv); break; + case SVt_PVHV: encode_hv (enc, (HV *)rv); break; default: - croak ("JSON can only represent references to arrays or hashes"); + croak ("encountered %s, but JSON can only represent references to arrays or hashes", + SvPV_nolen (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) { 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.max_depth = 0x7fffffffUL; SvPOK_only (enc.sv); encode_sv (&enc, scalar); @@ -443,16 +475,31 @@ } ///////////////////////////////////////////////////////////////////////////// +// decoder -#define WS \ - for (;;) \ - { \ - char ch = *dec->cur; \ - if (ch > 0x20 \ - || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)) \ - break; \ - ++dec->cur; \ +// 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 + UV flags; // F_* +} 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; + + ++dec->cur; } +} #define ERR(reason) SB dec->err = reason; goto fail; SE #define EXPECT_CH(ch) SB \ @@ -469,15 +516,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; @@ -490,136 +534,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; + 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; - hi = decode_4hex (dec); - if (hi == (UV)-1) - goto fail; - - // possibly a surrogate pair - if (hi >= 0xd800 && hi < 0xdc00) + case 'u': { - if (dec->cur [0] != '\\' || dec->cur [1] != 'u') - ERR ("missing low surrogate character in surrogate pair"); - - dec->cur += 2; + UV lo, hi; + ++dec->cur; - 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"); + // 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"); - hi = (hi - 0xD800) * 0x400 + (lo - 0xDC00) + 0x10000; + if (hi >= 0x80) + { + utf8 = 1; + + cur = (char *)uvuni_to_utf8_flags (cur, hi, 0); + } + else + *cur++ = hi; } - else if (hi >= 0xdc00 && hi < 0xe000) - ERR ("missing high surrogate character in surrogate pair"); + 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 = utf8n_to_uvuni (dec->cur, dec->end - dec->cur, &clen, UTF8_CHECK_ONLY); + if (clen == (STRLEN)-1) + ERR ("malformed UTF-8 character in JSON string"); + + do + { + *cur++ = *dec->cur++; } - break; + while (--clen); - default: - --dec->cur; - ERR ("illegal backslash escape sequence in string"); + 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) - { - STRLEN clen; - UV uch = utf8n_to_uvuni (dec->cur, dec->end - dec->cur, &clen, UTF8_CHECK_ONLY); - if (clen == (STRLEN)-1) - ERR ("malformed UTF-8 character in JSON string"); + while (cur < buf + SHORT_STRING_LEN); - APPEND_GROW (clen); - do - { - *cur++ = *dec->cur++; - } - while (--clen); + STRLEN len = cur - buf; - utf8 = 1; + if (sv) + { + SvGROW (sv, SvCUR (sv) + len + 1); + memcpy (SvPVX (sv) + SvCUR (sv), buf, len); + SvCUR_set (sv, SvCUR (sv) + len); } - else if (dec->cur == dec->end) - ERR ("unexpected end of string while parsing json string"); 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 (utf8) - SvUTF8_on (sv); + if (sv) + { + SvPOK_only (sv); + *SvEND (sv) = 0; - if (dec->flags & F_SHRINK) - shrink (sv); + if (utf8) + SvUTF8_on (sv); + } + else + sv = newSVpvn ("", 0); return sv; fail: - SvREFCNT_dec (sv); return 0; } @@ -710,7 +760,7 @@ { AV *av = newAV (); - WS; + decode_ws (dec); if (*dec->cur == ']') ++dec->cur; else @@ -724,7 +774,7 @@ av_push (av, value); - WS; + decode_ws (dec); if (*dec->cur == ']') { @@ -750,7 +800,7 @@ { HV *hv = newHV (); - WS; + decode_ws (dec); if (*dec->cur == '}') ++dec->cur; else @@ -758,13 +808,13 @@ { SV *key, *value; - WS; EXPECT_CH ('"'); + decode_ws (dec); EXPECT_CH ('"'); key = decode_str (dec); if (!key) goto fail; - WS; EXPECT_CH (':'); + decode_ws (dec); EXPECT_CH (':'); value = decode_sv (dec); if (!value) @@ -776,7 +826,7 @@ //TODO: optimise hv_store_ent (hv, key, value, 0); - WS; + decode_ws (dec); if (*dec->cur == '}') { @@ -800,7 +850,7 @@ static SV * decode_sv (dec_t *dec) { - WS; + decode_ws (dec); switch (*dec->cur) { case '"': ++dec->cur; return decode_str (dec); @@ -880,14 +930,16 @@ ? 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; - memset (&cop, 0, sizeof (cop)); + 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); + LEAVE; + croak ("%s, at character offset %d (%s)", dec.err, (int)offset, @@ -897,11 +949,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: @@ -937,7 +992,6 @@ 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