--- JSON-XS/XS.xs 2007/03/22 23:24:18 1.5 +++ JSON-XS/XS.xs 2007/08/13 16:14:20 1.59 @@ -2,74 +2,147 @@ #include "perl.h" #include "XSUB.h" -#include "assert.h" -#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 +#include +#include +#include +#include +#include + +#if defined(__BORLANDC__) || defined(_MSC_VER) +# define snprintf _snprintf // C compilers have this in stdio.h +#endif + +// some old perls do not have this, try to make it work, no +// guarentees, though. if it breaks, you get to keep the pieces. +#ifndef UTF8_MAXBYTES +# define UTF8_MAXBYTES 13 +#endif + +#define F_ASCII 0x00000001UL +#define F_LATIN1 0x00000002UL +#define F_UTF8 0x00000004UL +#define F_INDENT 0x00000008UL +#define F_CANONICAL 0x00000010UL +#define F_SPACE_BEFORE 0x00000020UL +#define F_SPACE_AFTER 0x00000040UL +#define F_ALLOW_NONREF 0x00000100UL +#define F_SHRINK 0x00000200UL +#define F_ALLOW_BLESSED 0x00000400UL +#define F_CONV_BLESSED 0x00000800UL +#define F_MAXDEPTH 0xf8000000UL +#define S_MAXDEPTH 27 +#define F_MAXSIZE 0x01f00000UL +#define S_MAXSIZE 20 +#define F_HOOK 0x00080000UL // some hooks exist, so slow-path processing + +#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH)) +#define DEC_SIZE(flags) (1UL << ((flags & F_MAXSIZE ) >> S_MAXSIZE )) #define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER -#define F_DEFAULT 0 +#define F_DEFAULT (9UL << S_MAXDEPTH) #define INIT_SIZE 32 // initial scalar size to be allocated +#define INDENT_STEP 3 // spaces per indentation level + +#define SHORT_STRING_LEN 16384 // 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; +#if __GNUC__ >= 3 +# define expect(expr,value) __builtin_expect ((expr),(value)) +# define inline inline +#else +# define expect(expr,value) (expr) +# define inline static +#endif + +#define expect_false(expr) expect ((expr) != 0, 0) +#define expect_true(expr) expect ((expr) != 0, 1) + +#ifdef USE_ITHREADS +# define JSON_SLOW 1 +# define JSON_STASH (json_stash ? json_stash : gv_stashpv ("JSON::XS", 1)) +#else +# define JSON_SLOW 0 +# define JSON_STASH json_stash +#endif + +static HV *json_stash, *json_boolean_stash; // JSON::XS:: +static SV *json_true, *json_false; + +typedef struct { + U32 flags; + SV *cb_object; + HV *cb_sk_object; +} JSON; -// 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) +inline void +shrink (SV *sv) { - if (!(SvROK (sv) && SvOBJECT (SvRV (sv)) && SvSTASH (SvRV (sv)) == json_stash)) - croak ("object is not of type JSON::XS"); + 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 + } +} - return &SvUVX (SvRV (sv)); +// 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 +inline UV +decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen) +{ + if (expect_false (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 + { + *clen = (STRLEN)-1; + return (UV)-1; + } } ///////////////////////////////////////////////////////////////////////////// +// encoder -static void +// structure used for encoding JSON +typedef struct +{ + char *cur; // SvPVX (sv) + current output position + char *end; // SvEND (sv) + SV *sv; // result scalar + JSON json; + U32 indent; // indentation level + U32 maxdepth; // max. indentation/recursion level +} enc_t; + +inline void need (enc_t *enc, STRLEN len) { - if (enc->cur + len >= enc->end) + if (expect_false (enc->cur + len >= enc->end)) { STRLEN cur = enc->cur - SvPVX (enc->sv); SvGROW (enc->sv, cur + len + 1); enc->cur = SvPVX (enc->sv) + cur; - enc->end = SvPVX (enc->sv) + SvLEN (enc->sv); + enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1; } } -static void +inline void encode_ch (enc_t *enc, char ch) { need (enc, 1); @@ -87,94 +160,100 @@ { 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 + if (expect_true (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 - { - STRLEN clen; - UV uch; - - if (is_utf8) + if (expect_false (ch == '"')) // but with slow exceptions { - 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"); + need (enc, len += 1); + *enc->cur++ = '\\'; + *enc->cur++ = '"'; } - else + else if (expect_false (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 - { - 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]; - } + 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; - str += clen; - } - else if (is_utf8) - { - need (enc, len += clen); - do + default: { - *enc->cur++ = *str++; + STRLEN clen; + UV uch; + + if (is_utf8) + { + 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->json.flags & F_ASCII || (enc->json.flags & F_LATIN1 && uch > 0xFF)) + { + 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 (enc->json.flags & F_LATIN1) + { + *enc->cur++ = uch; + str += clen; + } + else if (is_utf8) + { + need (enc, len += clen); + do + { + *enc->cur++ = *str++; + } + while (--clen); + } + else + { + need (enc, len += UTF8_MAXBYTES - 1); // never more than 11 bytes needed + enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); + ++str; + } } - while (--clen); - } - else - { - need (enc, 10); // never more than 11 bytes needed - enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); - ++str; } } @@ -182,25 +261,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 +inline void +encode_indent (enc_t *enc) +{ + if (enc->json.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; + } +} + +inline void +encode_space (enc_t *enc) +{ + need (enc, 1); + encode_ch (enc, ' '); +} + +inline void +encode_nl (enc_t *enc) +{ + if (enc->json.flags & F_INDENT) + { + need (enc, 1); + encode_ch (enc, '\n'); + } +} + +inline void +encode_comma (enc_t *enc) +{ + encode_ch (enc, ','); + + if (enc->json.flags & F_INDENT) + encode_nl (enc); + else if (enc->json.flags & F_SPACE_AFTER) + encode_space (enc); +} static void encode_sv (enc_t *enc, SV *sv); @@ -209,22 +309,31 @@ { 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_sv (enc, *av_fetch (av, i, 0)); + SV **svp = av_fetch (av, i, 0); + + encode_indent (enc); + + if (svp) + encode_sv (enc, *svp); + else + encode_str (enc, "null", 4, 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 @@ -248,9 +357,9 @@ encode_ch (enc, '"'); - if (enc->flags & F_SPACE_BEFORE) SPACE; + if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc); encode_ch (enc, ':'); - if (enc->flags & F_SPACE_AFTER ) SPACE; + if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc); encode_sv (enc, HeVAL (he)); } @@ -266,8 +375,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; } @@ -284,7 +393,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))) { @@ -292,10 +404,15 @@ // actually, this is mostly due to the stupid so-called // security workaround added somewhere in 5.8.x. // that randomises hash orderings - if (enc->flags & F_CANONICAL) + if (enc->json.flags & F_CANONICAL) { - HE *he, *hes [count]; int fast = 1; + HE *he; +#if defined(__BORLANDC__) || defined(_MSC_VER) + HE **hes = _alloca (count * sizeof (HE)); +#else + HE *hes [count]; // if your compiler dies here, you need to enable C99 mode +#endif i = 0; while ((he = hv_iternext (hv))) @@ -311,50 +428,146 @@ 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 { - SV *sv; HE *he = hv_iternext (hv); for (;;) { - INDENT; + encode_indent (enc); encode_he (enc, he); if (!(he = hv_iternext (hv))) break; - COMMA; + encode_comma (enc); + } + + encode_nl (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) +{ + svtype svt; + + SvGETMAGIC (sv); + svt = SvTYPE (sv); + + if (expect_false (SvOBJECT (sv))) + { + HV *stash = !JSON_SLOW || json_boolean_stash + ? json_boolean_stash + : gv_stashpv ("JSON::XS::Boolean", 1); + + if (SvSTASH (sv) == stash) + { + if (SvIV (sv)) + encode_str (enc, "true", 4, 0); + else + encode_str (enc, "false", 5, 0); + } + else + { +#if 0 + if (0 && sv_derived_from (rv, "JSON::Literal")) + { + // not yet } +#endif + if (enc->json.flags & F_CONV_BLESSED) + { + // we re-bless the reference to get overload and other niceties right + GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 0); + + if (to_json) + { + dSP; + + ENTER; SAVETMPS; PUSHMARK (SP); + XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv))); - NL; + // calling with G_SCALAR ensures that we always get a 1 return value + PUTBACK; + call_sv ((SV *)GvCV (to_json), G_SCALAR); + SPAGAIN; + + // catch this surprisingly common error + if (SvROK (TOPs) && SvRV (TOPs) == sv) + croak ("%s::TO_JSON method returned same object as was passed instead of a new one", HvNAME (SvSTASH (sv))); + + sv = POPs; + PUTBACK; + + encode_sv (enc, sv); + + FREETMPS; LEAVE; + } + else if (enc->json.flags & F_ALLOW_BLESSED) + encode_str (enc, "null", 4, 0); + else + croak ("encountered object '%s', but neither allow_blessed enabled nor TO_JSON method available on it", + SvPV_nolen (sv_2mortal (newRV_inc (sv)))); + } + else if (enc->json.flags & F_ALLOW_BLESSED) + encode_str (enc, "null", 4, 0); + else + croak ("encountered object '%s', but neither allow_blessed nor convert_blessed settings are enabled", + SvPV_nolen (sv_2mortal (newRV_inc (sv)))); } } + else if (svt == SVt_PVHV) + encode_hv (enc, (HV *)sv); + else if (svt == SVt_PVAV) + encode_av (enc, (AV *)sv); + else if (svt < SVt_PVAV) + { + STRLEN len = 0; + char *pv = svt ? SvPV (sv, len) : 0; - --enc->indent; INDENT; encode_ch (enc, '}'); + if (len == 1 && *pv == '1') + encode_str (enc, "true", 4, 0); + else if (len == 1 && *pv == '0') + encode_str (enc, "false", 5, 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 @@ -372,83 +585,130 @@ } else if (SvNOKp (sv)) { + // trust that perl will do the right thing w.r.t. JSON syntax. need (enc, NV_DIG + 32); Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur); enc->cur += strlen (enc->cur); } else if (SvIOKp (sv)) { - need (enc, 64); - enc->cur += - SvIsUV(sv) - ? snprintf (enc->cur, 64, "%"UVuf, (UV)SvUVX (sv)) - : 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)) + // we assume we can always read an IV as a UV + if (SvUV (sv) & ~(UV)0x7fff) { - 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"); + // large integer, use the (rather slow) snprintf way. + need (enc, sizeof (UV) * 3); + enc->cur += + SvIsUV(sv) + ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv)) + : snprintf (enc->cur, sizeof (UV) * 3, "%"IVdf, (IV)SvIVX (sv)); + } + else + { + // optimise the "small number case" + // code will likely be branchless and use only a single multiplication + I32 i = SvIV (sv); + U32 u; + char digit, nz = 0; + + need (enc, 6); + + *enc->cur = '-'; enc->cur += i < 0 ? 1 : 0; + u = i < 0 ? -i : i; + + // convert to 4.28 fixed-point representation + u = u * ((0xfffffff + 10000) / 10000); // 10**5, 5 fractional digits + + // now output digit by digit, each time masking out the integer part + // and multiplying by 5 while moving the decimal point one to the right, + // resulting in a net multiplication by 10. + // we always write the digit to memory but conditionally increment + // the pointer, to ease the usage of conditional move instructions. + digit = u >> 28; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0xfffffff) * 5; + digit = u >> 27; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x7ffffff) * 5; + digit = u >> 26; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x3ffffff) * 5; + digit = u >> 25; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x1ffffff) * 5; + digit = u >> 24; *enc->cur = digit + '0'; enc->cur += 1; // correctly generate '0' } } + else if (SvROK (sv)) + 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, JSON *json) { - if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar)) - croak ("hash- or arraref required (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; + + if (!(json->flags & F_ALLOW_NONREF) && !SvROK (scalar)) + croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)"); + + enc.json = *json; + 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 (enc.json.flags); SvPOK_only (enc.sv); encode_sv (&enc, scalar); - if (!(flags & (F_ASCII | F_UTF8))) + SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); + *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings + + if (!(enc.json.flags & (F_ASCII | F_LATIN1 | F_UTF8))) SvUTF8_on (enc.sv); - SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); + if (enc.json.flags & F_SHRINK) + shrink (enc.sv); + return enc.sv; } ///////////////////////////////////////////////////////////////////////////// +// 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 + JSON json; + U32 depth; // recursion depth + U32 maxdepth; // recursion depth limit +} dec_t; + +inline 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 \ 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]; @@ -457,15 +717,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 (expect_false (d1 < 0)) ERR ("exactly four hexadecimal digits expected"); + d2 = decode_hexdigit [cur [1]]; if (expect_false (d2 < 0)) ERR ("exactly four hexadecimal digits expected"); + d3 = decode_hexdigit [cur [2]]; if (expect_false (d3 < 0)) ERR ("exactly four hexadecimal digits expected"); + d4 = decode_hexdigit [cur [3]]; if (expect_false (d4 < 0)) ERR ("exactly four hexadecimal digits expected"); dec->cur += 4; @@ -478,133 +735,155 @@ 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); + char *dec_cur = dec->cur; - for (;;) + do { - unsigned char ch = *(unsigned char *)dec->cur; + char buf [SHORT_STRING_LEN + UTF8_MAXBYTES]; + char *cur = buf; - if (ch == '"') - break; - else if (ch == '\\') + do { - switch (*++dec->cur) - { - case '\\': - case '/': - case '"': APPEND_CH (*dec->cur++); break; + unsigned char ch = *(unsigned char *)dec_cur++; - 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; - - case 'u': + if (expect_false (ch == '"')) + { + --dec_cur; + break; + } + else if (expect_false (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 ("missing low surrogate character in surrogate pair"); + UV lo, hi; + ++dec_cur; - dec->cur += 2; - - lo = decode_4hex (dec); - if (lo == (UV)-1) + dec->cur = dec_cur; + hi = decode_4hex (dec); + dec_cur = dec->cur; + 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; + + dec->cur = dec_cur; + lo = decode_4hex (dec); + dec_cur = dec->cur; + 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 (hi >= 0xdc00 && hi < 0xe000) - ERR ("missing high surrogate character in surrogate pair"); - - if (hi >= 0x80) - { - utf8 = 1; + break; - APPEND_GROW (4); // at most 4 bytes for 21 bits - cur = (char *)uvuni_to_utf8_flags (cur, hi, 0); - } - else - APPEND_CH (hi); + default: + --dec_cur; + ERR ("illegal backslash escape sequence in string"); } - break; - - default: - --dec->cur; - ERR ("illegal backslash escape sequence in string"); } - } - 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 string, cannot convert to JSON"); - - APPEND_GROW (clen); - do + else if (expect_true (ch >= 0x20 && ch <= 0x7f)) + *cur++ = ch; + else if (ch >= 0x80) { - *cur++ = *dec->cur++; + STRLEN clen; + UV uch; + + --dec_cur; + + 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++; + while (--clen); + + utf8 = 1; } - while (--clen); + else + { + --dec_cur; - utf8 = 1; + if (!ch) + ERR ("unexpected end of string while parsing JSON string"); + else + ERR ("invalid character encountered while parsing JSON string"); + } } - else if (dec->cur == dec->end) - ERR ("unexpected end of string while parsing json string"); - else - ERR ("invalid character encountered"); - } + while (cur < buf + SHORT_STRING_LEN); - ++dec->cur; + { + STRLEN len = cur - buf; - SvCUR_set (sv, cur - SvPVX (sv)); + if (sv) + { + SvGROW (sv, SvCUR (sv) + len + 1); + memcpy (SvPVX (sv) + SvCUR (sv), buf, len); + SvCUR_set (sv, SvCUR (sv) + len); + } + else + sv = newSVpvn (buf, len); + } + } + while (*dec_cur != '"'); + + ++dec_cur; - 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); + dec->cur = dec_cur; return sv; fail: - SvREFCNT_dec (sv); + dec->cur = dec_cur; return 0; } @@ -672,18 +951,55 @@ if (!is_nv) { - UV uv; - int numtype = grok_number (start, dec->cur - start, &uv); - if (numtype & IS_NUMBER_IN_UV) - if (numtype & IS_NUMBER_NEG) + int len = dec->cur - start; + + // special case the rather common 1..4-digit-int case, assumes 32 bit ints or so + if (*start == '-') + switch (len) { - if (uv < (UV)IV_MIN) - return newSViv (-(IV)uv); + case 2: return newSViv (-( start [1] - '0' * 1)); + case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11)); + case 4: return newSViv (-( start [1] * 100 + start [2] * 10 + start [3] - '0' * 111)); + case 5: return newSViv (-(start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111)); } - else - return newSVuv (uv); + else + switch (len) + { + case 1: return newSViv ( start [0] - '0' * 1); + case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11); + case 3: return newSViv ( start [0] * 100 + start [1] * 10 + start [2] - '0' * 111); + case 4: return newSViv ( start [0] * 1000 + start [1] * 100 + start [2] * 10 + start [3] - '0' * 1111); + } + + { + UV uv; + int numtype = grok_number (start, len, &uv); + if (numtype & IS_NUMBER_IN_UV) + if (numtype & IS_NUMBER_NEG) + { + if (uv < (UV)IV_MIN) + return newSViv (-(IV)uv); + } + else + return newSVuv (uv); + } + + len -= *start == '-' ? 1 : 0; + + // does not fit into IV or UV, try NV + if ((sizeof (NV) == sizeof (double) && DBL_DIG >= len) + #if defined (LDBL_DIG) + || (sizeof (NV) == sizeof (long double) && LDBL_DIG >= len) + #endif + ) + // fits into NV without loss of precision + return newSVnv (Atof (start)); + + // everything else fails, convert it to a string + return newSVpvn (start, dec->cur - start); } + // loss of precision here return newSVnv (Atof (start)); fail: @@ -695,7 +1011,9 @@ { AV *av = newAV (); - WS; + DEC_INC_DEPTH; + decode_ws (dec); + if (*dec->cur == ']') ++dec->cur; else @@ -709,7 +1027,7 @@ av_push (av, value); - WS; + decode_ws (dec); if (*dec->cur == ']') { @@ -723,45 +1041,88 @@ ++dec->cur; } + DEC_DEC_DEPTH; return newRV_noinc ((SV *)av); fail: SvREFCNT_dec (av); + DEC_DEC_DEPTH; return 0; } static SV * decode_hv (dec_t *dec) { + SV *sv; HV *hv = newHV (); - WS; + DEC_INC_DEPTH; + decode_ws (dec); + if (*dec->cur == '}') ++dec->cur; else for (;;) { - SV *key, *value; + decode_ws (dec); EXPECT_CH ('"'); - WS; EXPECT_CH ('"'); + // heuristic: assume that + // a) decode_str + hv_store_ent are abysmally slow. + // b) most hash keys are short, simple ascii text. + // => try to "fast-match" such strings to avoid + // the overhead of decode_str + hv_store_ent. + { + SV *value; + char *p = dec->cur; + char *e = p + 24; // only try up to 24 bytes - key = decode_str (dec); - if (!key) - goto fail; + for (;;) + { + // the >= 0x80 is true on most architectures + if (p == e || *p < 0x20 || *p >= 0x80 || *p == '\\') + { + // slow path, back up and use decode_str + SV *key = decode_str (dec); + if (!key) + goto fail; - WS; EXPECT_CH (':'); + decode_ws (dec); EXPECT_CH (':'); - value = decode_sv (dec); - if (!value) - { - SvREFCNT_dec (key); - goto fail; - } + value = decode_sv (dec); + if (!value) + { + SvREFCNT_dec (key); + goto fail; + } - //TODO: optimise - hv_store_ent (hv, key, value, 0); + hv_store_ent (hv, key, value, 0); + SvREFCNT_dec (key); + + break; + } + else if (*p == '"') + { + // fast path, got a simple key + char *key = dec->cur; + int len = p - key; + dec->cur = p + 1; + + decode_ws (dec); EXPECT_CH (':'); + + value = decode_sv (dec); + if (!value) + goto fail; - WS; + hv_store (hv, key, len, value, 0); + + break; + } + + ++p; + } + } + + decode_ws (dec); if (*dec->cur == '}') { @@ -775,17 +1136,82 @@ ++dec->cur; } - return newRV_noinc ((SV *)hv); + DEC_DEC_DEPTH; + sv = newRV_noinc ((SV *)hv); + + // check filter callbacks + if (dec->json.flags & F_HOOK) + { + if (dec->json.cb_sk_object && HvKEYS (hv) == 1) + { + HE *cb, *he; + + hv_iterinit (hv); + he = hv_iternext (hv); + hv_iterinit (hv); + + // the next line creates a mortal sv each time its called. + // might want to optimise this for common cases. + cb = hv_fetch_ent (dec->json.cb_sk_object, hv_iterkeysv (he), 0, 0); + + if (cb) + { + dSP; + int count; + + ENTER; SAVETMPS; PUSHMARK (SP); + XPUSHs (HeVAL (he)); + + PUTBACK; count = call_sv (HeVAL (cb), G_ARRAY); SPAGAIN; + + if (count == 1) + { + sv = newSVsv (POPs); + FREETMPS; LEAVE; + return sv; + } + + FREETMPS; LEAVE; + } + } + + if (dec->json.cb_object) + { + dSP; + int count; + + ENTER; SAVETMPS; PUSHMARK (SP); + XPUSHs (sv_2mortal (sv)); + + PUTBACK; count = call_sv (dec->json.cb_object, G_ARRAY); SPAGAIN; + + if (count == 1) + { + sv = newSVsv (POPs); + FREETMPS; LEAVE; + return sv; + } + + SvREFCNT_inc (sv); + FREETMPS; LEAVE; + } + } + + return sv; fail: SvREFCNT_dec (hv); + DEC_DEC_DEPTH; return 0; } static SV * decode_sv (dec_t *dec) { - WS; + decode_ws (dec); + + // the beauty of JSON: you need exactly one character lookahead + // to parse anything. switch (*dec->cur) { case '"': ++dec->cur; return decode_str (dec); @@ -801,7 +1227,7 @@ if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) { dec->cur += 4; - return newSViv (1); + return SvREFCNT_inc (json_true); } else ERR ("'true' expected"); @@ -812,7 +1238,7 @@ if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) { dec->cur += 5; - return newSViv (0); + return SvREFCNT_inc (json_false); } else ERR ("'false' expected"); @@ -831,7 +1257,7 @@ break; default: - ERR ("malformed json string"); + ERR ("malformed JSON string, neither array, object, number, string or atom"); break; } @@ -840,38 +1266,76 @@ } static SV * -decode_json (SV *string, UV flags) +decode_json (SV *string, JSON *json, UV *offset_return) { + dec_t dec; + UV offset; SV *sv; - if (flags & F_UTF8) + SvGETMAGIC (string); + SvUPGRADE (string, SVt_PV); + + if (json->flags & F_MAXSIZE && SvCUR (string) > DEC_SIZE (json->flags)) + croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu", + (unsigned long)SvCUR (string), (unsigned long)DEC_SIZE (json->flags)); + + if (json->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.json = *json; + dec.cur = SvPVX (string); + dec.end = SvEND (string); + dec.err = 0; + dec.depth = 0; + dec.maxdepth = DEC_DEPTH (dec.json.flags); + + if (dec.json.cb_object || dec.json.cb_sk_object) + dec.json.flags |= F_HOOK; + *dec.end = 0; // this should basically be a nop, too, but make sure it's there sv = decode_sv (&dec); + if (!(offset_return || !sv)) + { + // check for trailing garbage + decode_ws (&dec); + + if (*dec.cur) + { + dec.err = "garbage after JSON object"; + SvREFCNT_dec (sv); + sv = 0; + } + } + + if (offset_return || !sv) + { + offset = dec.json.flags & F_UTF8 + ? dec.cur - SvPVX (string) + : utf8_distance (dec.cur, SvPVX (string)); + + if (offset_return) + *offset_return = offset; + } + if (!sv) { - IV offset = 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); - croak ("%s, at character offset %d (%s)", + LEAVE; + + croak ("%s, at character offset %d [\"%s\"]", dec.err, (int)offset, dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); @@ -879,78 +1343,173 @@ 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)"); + if (!(dec.json.flags & F_ALLOW_NONREF) && !SvROK (sv)) + 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: { int i; - memset (decode_hexdigit, 0xff, 256); - for (i = 10; i--; ) - decode_hexdigit ['0' + i] = 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; - for (i = 7; i--; ) - { - decode_hexdigit ['a' + i] = 10 + i; - decode_hexdigit ['A' + i] = 10 + i; - } + json_stash = gv_stashpv ("JSON::XS" , 1); + json_boolean_stash = gv_stashpv ("JSON::XS::Boolean", 1); - json_stash = gv_stashpv ("JSON::XS", 1); + json_true = get_sv ("JSON::XS::true" , 1); SvREADONLY_on (json_true ); + json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false); } PROTOTYPES: DISABLE -SV *new (char *dummy) +void CLONE (...) CODE: - RETVAL = sv_bless (newRV_noinc (newSVuv (F_DEFAULT)), json_stash); - OUTPUT: - RETVAL + json_stash = 0; + json_boolean_stash = 0; + +void new (char *klass) + PPCODE: +{ + SV *pv = NEWSV (0, sizeof (JSON)); + SvPOK_only (pv); + Zero (SvPVX (pv), 1, JSON); + ((JSON *)SvPVX (pv))->flags = F_DEFAULT; + XPUSHs (sv_2mortal (sv_bless (newRV_noinc (pv), JSON_STASH))); +} -SV *ascii (SV *self, int enable) +void ascii (JSON *self, int enable = 1) ALIAS: - ascii = F_ASCII - utf8 = F_UTF8 - indent = F_INDENT - 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 - CODE: + ascii = F_ASCII + latin1 = F_LATIN1 + utf8 = F_UTF8 + indent = F_INDENT + canonical = F_CANONICAL + space_before = F_SPACE_BEFORE + space_after = F_SPACE_AFTER + pretty = F_PRETTY + allow_nonref = F_ALLOW_NONREF + shrink = F_SHRINK + allow_blessed = F_ALLOW_BLESSED + convert_blessed = F_CONV_BLESSED + PPCODE: { - UV *uv = SvJSON (self); if (enable) - *uv |= ix; + self->flags |= ix; + else + self->flags &= ~ix; + + XPUSHs (ST (0)); +} + +void max_depth (JSON *self, UV max_depth = 0x80000000UL) + PPCODE: +{ + UV log2 = 0; + + if (max_depth > 0x80000000UL) max_depth = 0x80000000UL; + + while ((1UL << log2) < max_depth) + ++log2; + + self->flags = self->flags & ~F_MAXDEPTH | (log2 << S_MAXDEPTH); + + XPUSHs (ST (0)); +} + +void max_size (JSON *self, UV max_size = 0) + PPCODE: +{ + UV log2 = 0; + + if (max_size > 0x80000000UL) max_size = 0x80000000UL; + if (max_size == 1) max_size = 2; + + while ((1UL << log2) < max_size) + ++log2; + + self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE); + + XPUSHs (ST (0)); +} + +void filter_json_object (JSON *self, SV *cb = &PL_sv_undef) + PPCODE: +{ + SvREFCNT_dec (self->cb_object); + self->cb_object = SvOK (cb) ? newSVsv (cb) : 0; + + XPUSHs (ST (0)); +} + +void filter_json_single_key_object (JSON *self, SV *key, SV *cb = &PL_sv_undef) + PPCODE: +{ + if (!self->cb_sk_object) + self->cb_sk_object = newHV (); + + if (SvOK (cb)) + hv_store_ent (self->cb_sk_object, key, newSVsv (cb), 0); else - *uv &= ~ix; + { + hv_delete_ent (self->cb_sk_object, key, G_DISCARD, 0); - RETVAL = newSVsv (self); + if (!HvKEYS (self->cb_sk_object)) + { + SvREFCNT_dec (self->cb_sk_object); + self->cb_sk_object = 0; + } + } + + XPUSHs (ST (0)); } - OUTPUT: - RETVAL -void encode (SV *self, SV *scalar) +void encode (JSON *self, SV *scalar) + PPCODE: + XPUSHs (encode_json (scalar, self)); + +void decode (JSON *self, SV *jsonstr) PPCODE: - XPUSHs (encode_json (scalar, *SvJSON (self))); + XPUSHs (decode_json (jsonstr, self, 0)); -void decode (SV *self, SV *jsonstr) +void decode_prefix (JSON *self, SV *jsonstr) PPCODE: - XPUSHs (decode_json (jsonstr, *SvJSON (self))); +{ + UV offset; + EXTEND (SP, 2); + PUSHs (decode_json (jsonstr, self, &offset)); + PUSHs (sv_2mortal (newSVuv (offset))); +} + +void DESTROY (JSON *self) + CODE: + SvREFCNT_dec (self->cb_sk_object); + SvREFCNT_dec (self->cb_object); PROTOTYPES: ENABLE void to_json (SV *scalar) PPCODE: - XPUSHs (encode_json (scalar, F_UTF8)); +{ + JSON json = { F_DEFAULT | F_UTF8 }; + XPUSHs (encode_json (scalar, &json)); +} void from_json (SV *jsonstr) PPCODE: - XPUSHs (decode_json (jsonstr, F_UTF8)); +{ + JSON json = { F_DEFAULT | F_UTF8 }; + XPUSHs (decode_json (jsonstr, &json, 0)); +}