--- JSON-XS/XS.xs 2007/11/25 19:02:42 1.66 +++ JSON-XS/XS.xs 2018/11/15 20:13:03 1.134 @@ -6,18 +6,34 @@ #include #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. +// guarantees, though. if it breaks, you get to keep the pieces. #ifndef UTF8_MAXBYTES # define UTF8_MAXBYTES 13 #endif +// compatibility with perl <5.18 +#ifndef HvNAMELEN_get +# define HvNAMELEN_get(hv) strlen (HvNAME (hv)) +#endif +#ifndef HvNAMELEN +# define HvNAMELEN(hv) HvNAMELEN_get (hv) +#endif +#ifndef HvNAMEUTF8 +# define HvNAMEUTF8(hv) 0 +#endif + +// three extra for rounding, sign, and end of string +#define IVUV_MAXCHARS (sizeof (UV) * CHAR_BIT * 28 / 93 + 3) + #define F_ASCII 0x00000001UL #define F_LATIN1 0x00000002UL #define F_UTF8 0x00000004UL @@ -30,62 +46,110 @@ #define F_ALLOW_BLESSED 0x00000400UL #define F_CONV_BLESSED 0x00000800UL #define F_RELAXED 0x00001000UL - -#define F_MAXDEPTH 0xf8000000UL -#define S_MAXDEPTH 27 -#define F_MAXSIZE 0x01f00000UL -#define S_MAXSIZE 20 +#define F_ALLOW_UNKNOWN 0x00002000UL +#define F_ALLOW_TAGS 0x00004000UL #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 (9UL << S_MAXDEPTH) -#define INIT_SIZE 32 // initial scalar size to be allocated +#define INIT_SIZE 64 // 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 DECODE_WANTS_OCTETS(json) ((json)->flags & F_UTF8) + #define SB do { #define SE } while (0) #if __GNUC__ >= 3 -# define expect(expr,value) __builtin_expect ((expr),(value)) -# define inline inline +# define expect(expr,value) __builtin_expect ((expr), (value)) +# define INLINE static inline #else # define expect(expr,value) (expr) -# define inline static +# define INLINE static #endif #define expect_false(expr) expect ((expr) != 0, 0) #define expect_true(expr) expect ((expr) != 0, 1) +#define IN_RANGE_INC(type,val,beg,end) \ + ((unsigned type)((unsigned type)(val) - (unsigned type)(beg)) \ + <= (unsigned type)((unsigned type)(end) - (unsigned type)(beg))) + +#define ERR_NESTING_EXCEEDED "json text or perl structure exceeds maximum nesting level (max_depth set too low?)" + #ifdef USE_ITHREADS -# define JSON_SLOW 1 -# define JSON_STASH (json_stash ? json_stash : gv_stashpv ("JSON::XS", 1)) +# define JSON_STASH (expect_true (json_stash) ? json_stash : gv_stashpv ("JSON::XS", 1)) +# define BOOL_STASH (expect_true (bool_stash) ? bool_stash : gv_stashpv ("Types::Serialiser::Boolean", 1)) +# define GET_BOOL(value) (expect_true (bool_ ## value) ? bool_ ## value : get_bool ("Types::Serialiser::" # value)) #else -# define JSON_SLOW 0 # define JSON_STASH json_stash +# define BOOL_STASH bool_stash +# define GET_BOOL(value) bool_ ## value #endif -static HV *json_stash, *json_boolean_stash; // JSON::XS:: -static SV *json_true, *json_false; +// the amount of HEs to allocate on the stack, when sorting keys +#define STACK_HES 64 + +static HV *json_stash, *bool_stash; // JSON::XS::, Types::Serialiser::Boolean:: +static SV *bool_false, *bool_true; +static SV *sv_json; + +enum { + INCR_M_WS = 0, // initial whitespace skipping, must be 0 + INCR_M_STR, // inside string + INCR_M_BS, // inside backslash + INCR_M_C0, // inside comment in initial whitespace sequence + INCR_M_C1, // inside comment in other places + INCR_M_JSON // outside anything, count nesting +}; + +#define INCR_DONE(json) ((json)->incr_nest <= 0 && (json)->incr_mode == INCR_M_JSON) typedef struct { U32 flags; + U32 max_depth; + STRLEN max_size; + SV *cb_object; HV *cb_sk_object; + + // for the incremental parser + SV *incr_text; // the source text so far + STRLEN incr_pos; // the current offset into the text + int incr_nest; // {[]}-nesting level + unsigned char incr_mode; + + SV *v_false, *v_true; } JSON; +INLINE void +json_init (JSON *json) +{ + Zero (json, 1, JSON); + json->max_depth = 512; +} + ///////////////////////////////////////////////////////////////////////////// // utility functions -inline void +INLINE SV * +get_bool (const char *name) +{ + SV *sv = get_sv (name, 1); + + SvREADONLY_on (sv); + SvREADONLY_on (SvRV (sv)); + + return sv; +} + +INLINE void shrink (SV *sv) { sv_utf8_downgrade (sv, 1); + if (SvLEN (sv) > SvCUR (sv) + 1) { #ifdef SvPV_shrink_to_cur @@ -96,26 +160,219 @@ } } -// decode an utf-8 character and return it, or (UV)-1 in +/* adds two STRLENs together, slow, and with paranoia */ +STRLEN +strlen_sum (STRLEN l1, STRLEN l2) +{ + size_t sum = l1 + l2; + + if (sum < (size_t)l2 || sum != (size_t)(STRLEN)sum) + croak ("JSON::XS: string size overflow"); + + return sum; +} + +/* similar to SvGROW, but somewhat safer and guarantees exponential realloc strategy */ +static char * +json_sv_grow (SV *sv, size_t len1, size_t len2) +{ + len1 = strlen_sum (len1, len2); + len1 = strlen_sum (len1, len1 >> 1); + + if (len1 > 4096 - 24) + len1 = (len1 | 4095) - 24; + + return SvGROW (sv, len1); +} + +// decode a 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 +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) + if (expect_true (len >= 2 + && IN_RANGE_INC (char, s[0], 0xc2, 0xdf) + && IN_RANGE_INC (char, s[1], 0x80, 0xbf))) { *clen = 2; return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f); } else + return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY); +} + +// likewise for encoding, also never called for ascii codepoints +// this function takes advantage of this fact, although current gccs +// seem to optimise the check for >= 0x80 away anyways +INLINE unsigned char * +encode_utf8 (unsigned char *s, UV ch) +{ + if (expect_false (ch < 0x000080)) + *s++ = ch; + else if (expect_true (ch < 0x000800)) + *s++ = 0xc0 | ( ch >> 6), + *s++ = 0x80 | ( ch & 0x3f); + else if ( ch < 0x010000) + *s++ = 0xe0 | ( ch >> 12), + *s++ = 0x80 | ((ch >> 6) & 0x3f), + *s++ = 0x80 | ( ch & 0x3f); + else if ( ch < 0x110000) + *s++ = 0xf0 | ( ch >> 18), + *s++ = 0x80 | ((ch >> 12) & 0x3f), + *s++ = 0x80 | ((ch >> 6) & 0x3f), + *s++ = 0x80 | ( ch & 0x3f); + + return s; +} + +// convert offset pointer to character index, sv must be string +static STRLEN +ptr_to_index (SV *sv, char *offset) +{ + return SvUTF8 (sv) + ? utf8_distance (offset, SvPVX (sv)) + : offset - SvPVX (sv); +} + +///////////////////////////////////////////////////////////////////////////// +// fp hell + +// scan a group of digits, and a trailing exponent +static void +json_atof_scan1 (const char *s, NV *accum, int *expo, int postdp, int maxdepth) +{ + UV uaccum = 0; + int eaccum = 0; + + // if we recurse too deep, skip all remaining digits + // to avoid a stack overflow attack + if (expect_false (--maxdepth <= 0)) + while (((U8)*s - '0') < 10) + ++s; + + for (;;) + { + U8 dig = (U8)*s - '0'; + + if (expect_false (dig >= 10)) + { + if (dig == (U8)((U8)'.' - (U8)'0')) + { + ++s; + json_atof_scan1 (s, accum, expo, 1, maxdepth); + } + else if ((dig | ' ') == 'e' - '0') + { + int exp2 = 0; + int neg = 0; + + ++s; + + if (*s == '-') + { + ++s; + neg = 1; + } + else if (*s == '+') + ++s; + + while ((dig = (U8)*s - '0') < 10) + exp2 = exp2 * 10 + *s++ - '0'; + + *expo += neg ? -exp2 : exp2; + } + + break; + } + + ++s; + + uaccum = uaccum * 10 + dig; + ++eaccum; + + // if we have too many digits, then recurse for more + // we actually do this for rather few digits + if (uaccum >= (UV_MAX - 9) / 10) + { + if (postdp) *expo -= eaccum; + json_atof_scan1 (s, accum, expo, postdp, maxdepth); + if (postdp) *expo += eaccum; + + break; + } + } + + // this relies greatly on the quality of the pow () + // implementation of the platform, but a good + // implementation is hard to beat. + // (IEEE 754 conformant ones are required to be exact) + if (postdp) *expo -= eaccum; + *accum += uaccum * Perl_pow (10., *expo); + *expo += eaccum; +} + +static NV +json_atof (const char *s) +{ + NV accum = 0.; + int expo = 0; + int neg = 0; + + if (*s == '-') + { + ++s; + neg = 1; + } + + // a recursion depth of ten gives us >>500 bits + json_atof_scan1 (s, &accum, &expo, 0, 10); + + return neg ? -accum : accum; +} + +// target of scalar reference is bool? -1 == nope, 0 == false, 1 == true +static int +ref_bool_type (SV *sv) +{ + svtype svt = SvTYPE (sv); + + if (svt < SVt_PVAV) + { + STRLEN len = 0; + char *pv = svt ? SvPV (sv, len) : 0; + + if (len == 1) + if (*pv == '1') + return 1; + else if (*pv == '0') + return 0; + } + + return -1; +} + +// returns whether scalar is not a reference in the sense of allow_nonref +static int +json_nonref (SV *scalar) +{ + if (!SvROK (scalar)) + return 1; + + scalar = SvRV (scalar); + + if (SvTYPE (scalar) >= SVt_PVMG) { - *clen = (STRLEN)-1; - return (UV)-1; + if (SvSTASH (scalar) == bool_stash) + return 1; + + if (!SvOBJECT (scalar) && ref_bool_type (scalar) >= 0) + return 1; } + + return 0; } ///////////////////////////////////////////////////////////////////////////// @@ -129,22 +386,22 @@ SV *sv; // result scalar JSON json; U32 indent; // indentation level - U32 maxdepth; // max. indentation/recursion level + UV limit; // escape character values >= this value when encoding } enc_t; -inline void +INLINE void need (enc_t *enc, STRLEN len) { - if (expect_false (enc->cur + len >= enc->end)) + if (expect_false ((uintptr_t)(enc->end - enc->cur) < len)) { - 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) - 1; + STRLEN cur = enc->cur - (char *)SvPVX (enc->sv); + char *buf = json_sv_grow (enc->sv, cur, len); + enc->cur = buf + cur; + enc->end = buf + SvLEN (enc->sv) - 1; } } -inline void +INLINE void encode_ch (enc_t *enc, char ch) { need (enc, 1); @@ -166,13 +423,13 @@ { if (expect_false (ch == '"')) // but with slow exceptions { - need (enc, len += 1); + need (enc, len + 1); *enc->cur++ = '\\'; *enc->cur++ = '"'; } else if (expect_false (ch == '\\')) { - need (enc, len += 1); + need (enc, len + 1); *enc->cur++ = '\\'; *enc->cur++ = '\\'; } @@ -185,11 +442,11 @@ { switch (ch) { - 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; + 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: { @@ -208,14 +465,14 @@ 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 < 0x80/*0x20*/ || uch >= enc->limit) { - if (uch > 0xFFFFUL) + if (uch >= 0x10000UL) { - need (enc, len += 11); + if (uch >= 0x110000UL) + croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch); + + need (enc, len + 11); sprintf (enc->cur, "\\u%04x\\u%04x", (int)((uch - 0x10000) / 0x400 + 0xD800), (int)((uch - 0x10000) % 0x400 + 0xDC00)); @@ -223,14 +480,13 @@ } else { - static char hexdigit [16] = "0123456789abcdef"; - need (enc, len += 5); + 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]; + *enc->cur++ = PL_hexdigit [ uch >> 12 ]; + *enc->cur++ = PL_hexdigit [(uch >> 8) & 15]; + *enc->cur++ = PL_hexdigit [(uch >> 4) & 15]; + *enc->cur++ = PL_hexdigit [(uch >> 0) & 15]; } str += clen; @@ -242,7 +498,7 @@ } else if (is_utf8) { - need (enc, len += clen); + need (enc, len + clen); do { *enc->cur++ = *str++; @@ -251,8 +507,8 @@ } else { - need (enc, len += UTF8_MAXBYTES - 1); // never more than 11 bytes needed - enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); + need (enc, len + UTF8_MAXBYTES - 1); // never more than 11 bytes needed + enc->cur = encode_utf8 (enc->cur, uch); ++str; } } @@ -263,7 +519,7 @@ } } -inline void +INLINE void encode_indent (enc_t *enc) { if (enc->json.flags & F_INDENT) @@ -276,14 +532,14 @@ } } -inline void +INLINE void encode_space (enc_t *enc) { need (enc, 1); encode_ch (enc, ' '); } -inline void +INLINE void encode_nl (enc_t *enc) { if (enc->json.flags & F_INDENT) @@ -293,7 +549,7 @@ } } -inline void +INLINE void encode_comma (enc_t *enc) { encode_ch (enc, ','); @@ -311,11 +567,11 @@ { int i, len = av_len (av); - if (enc->indent >= enc->maxdepth) - croak ("data structure too deep (hit recursion limit)"); + if (enc->indent >= enc->json.max_depth) + croak (ERR_NESTING_EXCEEDED); encode_ch (enc, '['); - + if (len >= 0) { encode_nl (enc); ++enc->indent; @@ -337,7 +593,7 @@ encode_nl (enc); --enc->indent; encode_indent (enc); } - + encode_ch (enc, ']'); } @@ -351,7 +607,7 @@ SV *sv = HeSVKEY (he); STRLEN len; char *str; - + SvGETMAGIC (sv); str = SvPV (sv, len); @@ -396,18 +652,17 @@ encode_hv (enc_t *enc, HV *hv) { HE *he; - int count; - if (enc->indent >= enc->maxdepth) - croak ("data structure too deep (hit recursion limit)"); + if (enc->indent >= enc->json.max_depth) + croak (ERR_NESTING_EXCEEDED); encode_ch (enc, '{'); // for canonical output we have to sort by keys first // actually, this is mostly due to the stupid so-called - // security workaround added somewhere in 5.8.x. + // security workaround added somewhere in 5.8.x // that randomises hash orderings - if (enc->json.flags & F_CANONICAL) + if (enc->json.flags & F_CANONICAL && !SvRMAGICAL (hv)) { int count = hv_iterinit (hv); @@ -428,11 +683,15 @@ if (count) { int i, fast = 1; -#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 + HE *hes_stack [STACK_HES]; + HE **hes = hes_stack; + + // allocate larger arrays on the heap + if (count > STACK_HES) + { + SV *sv = sv_2mortal (NEWSV (0, count * sizeof (*hes))); + hes = (HE **)SvPVX (sv); + } i = 0; while ((he = hv_iternext (hv))) @@ -511,71 +770,95 @@ encode_rv (enc_t *enc, SV *sv) { svtype svt; + GV *method; 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); + HV *stash = SvSTASH (sv); - if (SvSTASH (sv) == stash) + if (stash == bool_stash) { - if (SvIV (sv)) - encode_str (enc, "true", 4, 0); - else - encode_str (enc, "false", 5, 0); + if (SvIV (sv)) encode_str (enc, "true" , 4, 0); + else encode_str (enc, "false", 5, 0); } - else + else if ((enc->json.flags & F_ALLOW_TAGS) && (method = gv_fetchmethod_autoload (stash, "FREEZE", 0))) { -#if 0 - if (0 && sv_derived_from (rv, "JSON::Literal")) - { - // not yet - } -#endif - if (enc->json.flags & F_CONV_BLESSED) + int count; + dSP; + + ENTER; SAVETMPS; + PUSHMARK (SP); + EXTEND (SP, 2); + // we re-bless the reference to get overload and other niceties right + PUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), stash)); + PUSHs (sv_json); + + PUTBACK; + count = call_sv ((SV *)GvCV (method), G_ARRAY); + SPAGAIN; + + // catch this surprisingly common error + if (SvROK (TOPs) && SvRV (TOPs) == sv) + croak ("%s::FREEZE method returned same object as was passed instead of a new one", HvNAME (SvSTASH (sv))); + + encode_ch (enc, '('); + encode_ch (enc, '"'); + encode_str (enc, HvNAME (stash), HvNAMELEN (stash), HvNAMEUTF8 (stash)); + encode_ch (enc, '"'); + encode_ch (enc, ')'); + encode_ch (enc, '['); + + if (count) { - // we re-bless the reference to get overload and other niceties right - GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 0); + int i; - if (to_json) + for (i = 0; i < count - 1; ++i) { - dSP; + encode_sv (enc, SP[i + 1 - count]); + encode_ch (enc, ','); + } - ENTER; SAVETMPS; PUSHMARK (SP); - XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv))); + encode_sv (enc, TOPs); + SP -= count; + } - // calling with G_SCALAR ensures that we always get a 1 return value - PUTBACK; - call_sv ((SV *)GvCV (to_json), G_SCALAR); - SPAGAIN; + encode_ch (enc, ']'); - // 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))); + FREETMPS; LEAVE; + } + else if ((enc->json.flags & F_CONV_BLESSED) && (method = gv_fetchmethod_autoload (stash, "TO_JSON", 0))) + { + dSP; - sv = POPs; - PUTBACK; + ENTER; SAVETMPS; + PUSHMARK (SP); + // we re-bless the reference to get overload and other niceties right + XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), stash)); + + // calling with G_SCALAR ensures that we always get a 1 return value + PUTBACK; + call_sv ((SV *)GvCV (method), 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))); - encode_sv (enc, sv); + sv = POPs; + PUTBACK; - 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)))); + 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, convert_blessed nor allow_tags settings are enabled (or TO_JSON/FREEZE method missing)", + SvPV_nolen (sv_2mortal (newRV_inc (sv)))); } else if (svt == SVt_PVHV) encode_hv (enc, (HV *)sv); @@ -583,17 +866,20 @@ encode_av (enc, (AV *)sv); else if (svt < SVt_PVAV) { - STRLEN len = 0; - char *pv = svt ? SvPV (sv, len) : 0; + int bool_type = ref_bool_type (sv); - if (len == 1 && *pv == '1') + if (bool_type == 1) encode_str (enc, "true", 4, 0); - else if (len == 1 && *pv == '0') + else if (bool_type == 0) encode_str (enc, "false", 5, 0); + else if (enc->json.flags & F_ALLOW_UNKNOWN) + encode_str (enc, "null", 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 if (enc->json.flags & F_ALLOW_UNKNOWN) + encode_str (enc, "null", 4, 0); else croak ("encountered %s, but JSON can only represent references to arrays or hashes", SvPV_nolen (sv_2mortal (newRV_inc (sv)))); @@ -621,21 +907,16 @@ } else if (SvIOKp (sv)) { - // we assume we can always read an IV as a UV - if (SvUV (sv) & ~(UV)0x7fff) - { - // 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 + // we assume we can always read an IV as a UV and vice versa + // we assume two's complement + // we assume no aliasing issues in the union + if (SvIsUV (sv) ? SvUVX (sv) <= 59000 + : SvIVX (sv) <= 59000 && SvIVX (sv) >= -59000) { // optimise the "small number case" // code will likely be branchless and use only a single multiplication - I32 i = SvIV (sv); + // works for numbers up to 59074 + I32 i = SvIVX (sv); U32 u; char digit, nz = 0; @@ -651,21 +932,30 @@ // 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; + // the pointer, to enable the use of conditional move instructions. + digit = u >> 28; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0xfffffffUL) * 5; + digit = u >> 27; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x7ffffffUL) * 5; + digit = u >> 26; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x3ffffffUL) * 5; + digit = u >> 25; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x1ffffffUL) * 5; digit = u >> 24; *enc->cur = digit + '0'; enc->cur += 1; // correctly generate '0' } + else + { + // large integer, use the (rather slow) snprintf way. + need (enc, IVUV_MAXCHARS); + enc->cur += + SvIsUV(sv) + ? snprintf (enc->cur, IVUV_MAXCHARS, "%"UVuf, (UV)SvUVX (sv)) + : snprintf (enc->cur, IVUV_MAXCHARS, "%"IVdf, (IV)SvIVX (sv)); + } } else if (SvROK (sv)) encode_rv (enc, SvRV (sv)); - else if (!SvOK (sv)) + else if (!SvOK (sv) || enc->json.flags & F_ALLOW_UNKNOWN) encode_str (enc, "null", 4, 0); else - croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this", - SvPV_nolen (sv), SvFLAGS (sv)); + croak ("encountered perl type (%s,0x%x) that JSON cannot handle, check your input data", + SvPV_nolen (sv), (unsigned int)SvFLAGS (sv)); } static SV * @@ -673,7 +963,7 @@ { enc_t enc; - if (!(json->flags & F_ALLOW_NONREF) && !SvROK (scalar)) + if (!(json->flags & F_ALLOW_NONREF) && json_nonref (scalar)) croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)"); enc.json = *json; @@ -681,10 +971,13 @@ enc.cur = SvPVX (enc.sv); enc.end = SvEND (enc.sv); enc.indent = 0; - enc.maxdepth = DEC_DEPTH (enc.json.flags); + enc.limit = enc.json.flags & F_ASCII ? 0x000080UL + : enc.json.flags & F_LATIN1 ? 0x000100UL + : 0x110000UL; SvPOK_only (enc.sv); encode_sv (&enc, scalar); + encode_nl (&enc); SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings @@ -712,7 +1005,7 @@ U32 maxdepth; // recursion depth limit } dec_t; -inline void +INLINE void decode_comment (dec_t *dec) { // only '#'-style comments allowed a.t.m. @@ -721,7 +1014,7 @@ ++dec->cur; } -inline void +INLINE void decode_ws (dec_t *dec) { for (;;) @@ -755,7 +1048,7 @@ ++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_INC_DEPTH if (++dec->depth > dec->json.max_depth) ERR (ERR_NESTING_EXCEEDED) #define DEC_DEC_DEPTH --dec->depth static SV *decode_sv (dec_t *dec); @@ -857,7 +1150,7 @@ { utf8 = 1; - cur = (char *)uvuni_to_utf8_flags (cur, hi, 0); + cur = encode_utf8 (cur, hi); } else *cur++ = hi; @@ -869,16 +1162,15 @@ ERR ("illegal backslash escape sequence in string"); } } - else if (expect_true (ch >= 0x20 && ch <= 0x7f)) + else if (expect_true (ch >= 0x20 && ch < 0x80)) *cur++ = ch; else if (ch >= 0x80) { STRLEN clen; - UV uch; --dec_cur; - uch = decode_utf8 (dec_cur, dec->end - dec_cur, &clen); + decode_utf8 (dec_cur, dec->end - dec_cur, &clen); if (clen == (STRLEN)-1) ERR ("malformed UTF-8 character in JSON string"); @@ -888,6 +1180,8 @@ utf8 = 1; } + else if (ch == '\t' && dec->json.flags & F_RELAXED) + *cur++ = ch; else { --dec_cur; @@ -905,7 +1199,11 @@ if (sv) { - SvGROW (sv, SvCUR (sv) + len + 1); + STRLEN cur = SvCUR (sv); + + if (SvLEN (sv) - cur <= len) + json_sv_grow (sv, cur, len); + memcpy (SvPVX (sv) + SvCUR (sv), buf, len); SvCUR_set (sv, SvCUR (sv) + len); } @@ -1002,22 +1300,24 @@ { int len = dec->cur - start; - // special case the rather common 1..4-digit-int case, assumes 32 bit ints or so + // special case the rather common 1..5-digit-int case if (*start == '-') switch (len) { - 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)); + case 2: return newSViv (-(IV)( start [1] - '0' * 1)); + case 3: return newSViv (-(IV)( start [1] * 10 + start [2] - '0' * 11)); + case 4: return newSViv (-(IV)( start [1] * 100 + start [2] * 10 + start [3] - '0' * 111)); + case 5: return newSViv (-(IV)( start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111)); + case 6: return newSViv (-(IV)(start [1] * 10000 + start [2] * 1000 + start [3] * 100 + start [4] * 10 + start [5] - '0' * 11111)); } 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); + 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); + case 5: return newSViv ( start [0] * 10000 + start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 11111); } { @@ -1036,20 +1336,16 @@ 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 - ) + if (len <= NV_DIG) // fits into NV without loss of precision - return newSVnv (Atof (start)); + return newSVnv (json_atof (start)); // everything else fails, convert it to a string return newSVpvn (start, dec->cur - start); } // loss of precision here - return newSVnv (Atof (start)); + return newSVnv (json_atof (start)); fail: return 0; @@ -1083,7 +1379,7 @@ ++dec->cur; break; } - + if (*dec->cur != ',') ERR (", or ] expected while parsing array"); @@ -1135,7 +1431,7 @@ for (;;) { - // the >= 0x80 is true on most architectures + // the >= 0x80 is false on most architectures if (p == e || *p < 0x20 || *p >= 0x80 || *p == '\\') { // slow path, back up and use decode_str @@ -1217,7 +1513,7 @@ he = hv_iternext (hv); hv_iterinit (hv); - // the next line creates a mortal sv each time its called. + // the next line creates a mortal sv each time it's called. // might want to optimise this for common cases. cb = hv_fetch_ent (dec->json.cb_sk_object, hv_iterkeysv (he), 0, 0); @@ -1226,8 +1522,10 @@ dSP; int count; - ENTER; SAVETMPS; PUSHMARK (SP); + ENTER; SAVETMPS; + PUSHMARK (SP); XPUSHs (HeVAL (he)); + sv_2mortal (sv); PUTBACK; count = call_sv (HeVAL (cb), G_ARRAY); SPAGAIN; @@ -1237,7 +1535,10 @@ FREETMPS; LEAVE; return sv; } + else if (count) + croak ("filter_json_single_key_object callbacks must not return more than one scalar"); + SvREFCNT_inc (sv); FREETMPS; LEAVE; } } @@ -1247,7 +1548,8 @@ dSP; int count; - ENTER; SAVETMPS; PUSHMARK (SP); + ENTER; SAVETMPS; + PUSHMARK (SP); XPUSHs (sv_2mortal (sv)); PUTBACK; count = call_sv (dec->json.cb_object, G_ARRAY); SPAGAIN; @@ -1258,6 +1560,8 @@ FREETMPS; LEAVE; return sv; } + else if (count) + croak ("filter_json_object callbacks must not return more than one scalar"); SvREFCNT_inc (sv); FREETMPS; LEAVE; @@ -1273,46 +1577,132 @@ } static SV * +decode_tag (dec_t *dec) +{ + SV *tag = 0; + SV *val = 0; + + if (!(dec->json.flags & F_ALLOW_TAGS)) + ERR ("malformed JSON string, neither array, object, number, string or atom"); + + ++dec->cur; + + decode_ws (dec); + + tag = decode_sv (dec); + if (!tag) + goto fail; + + if (!SvPOK (tag)) + ERR ("malformed JSON string, (tag) must be a string"); + + decode_ws (dec); + + if (*dec->cur != ')') + ERR (") expected after tag"); + + ++dec->cur; + + decode_ws (dec); + + val = decode_sv (dec); + if (!val) + goto fail; + + if (!SvROK (val) || SvTYPE (SvRV (val)) != SVt_PVAV) + ERR ("malformed JSON string, tag value must be an array"); + + { + AV *av = (AV *)SvRV (val); + int i, len = av_len (av) + 1; + HV *stash = gv_stashsv (tag, 0); + SV *sv; + + if (!stash) + ERR ("cannot decode perl-object (package does not exist)"); + + GV *method = gv_fetchmethod_autoload (stash, "THAW", 0); + + if (!method) + ERR ("cannot decode perl-object (package does not have a THAW method)"); + + dSP; + + ENTER; SAVETMPS; + PUSHMARK (SP); + EXTEND (SP, len + 2); + // we re-bless the reference to get overload and other niceties right + PUSHs (tag); + PUSHs (sv_json); + + for (i = 0; i < len; ++i) + PUSHs (*av_fetch (av, i, 1)); + + PUTBACK; + call_sv ((SV *)GvCV (method), G_SCALAR); + SPAGAIN; + + SvREFCNT_dec (tag); + SvREFCNT_dec (val); + sv = SvREFCNT_inc (POPs); + + PUTBACK; + + FREETMPS; LEAVE; + + return sv; + } + +fail: + SvREFCNT_dec (tag); + SvREFCNT_dec (val); + return 0; +} + +static SV * decode_sv (dec_t *dec) { // the beauty of JSON: you need exactly one character lookahead - // to parse anything. + // to parse everything. switch (*dec->cur) { - case '"': ++dec->cur; return decode_str (dec); - case '[': ++dec->cur; return decode_av (dec); - case '{': ++dec->cur; return decode_hv (dec); + case '"': ++dec->cur; return decode_str (dec); + case '[': ++dec->cur; return decode_av (dec); + case '{': ++dec->cur; return decode_hv (dec); + case '(': return decode_tag (dec); case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return decode_num (dec); - case 't': - if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) + case 'f': + if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) { - dec->cur += 4; -#if JSON_SLOW - json_true = get_sv ("JSON::XS::true", 1); SvREADONLY_on (json_true); -#endif - return SvREFCNT_inc (json_true); + dec->cur += 5; + + if (expect_false (!dec->json.v_false)) + dec->json.v_false = GET_BOOL (false); + + return newSVsv (dec->json.v_false); } else - ERR ("'true' expected"); + ERR ("'false' expected"); break; - case 'f': - if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) + case 't': + if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) { - dec->cur += 5; -#if JSON_SLOW - json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false); -#endif - return SvREFCNT_inc (json_false); + dec->cur += 4; + + if (expect_false (!dec->json.v_true)) + dec->json.v_true = GET_BOOL (true); + + return newSVsv (dec->json.v_true); } else - ERR ("'false' expected"); + ERR ("'true' expected"); break; @@ -1328,7 +1718,7 @@ break; default: - ERR ("malformed JSON string, neither array, object, number, string or atom"); + ERR ("malformed JSON string, neither tag, array, object, number, string or atom"); break; } @@ -1337,32 +1727,59 @@ } static SV * -decode_json (SV *string, JSON *json, UV *offset_return) +decode_json (SV *string, JSON *json, STRLEN *offset_return) { dec_t dec; - UV offset; SV *sv; - SvGETMAGIC (string); + /* work around bugs in 5.10 where manipulating magic values + * makes perl ignore the magic in subsequent accesses. + * also make a copy of non-PV values, to get them into a clean + * state (SvPV should do that, but it's buggy, see below). + * + * SvIsCOW_shared_hash works around a bug in perl (possibly 5.16), + * as reported by Reini Urban. + */ + /*SvGETMAGIC (string);*/ + if (SvMAGICAL (string) || !SvPOK (string) || SvIsCOW_shared_hash (string)) + string = sv_2mortal (newSVsv (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)); + /* work around a bug in perl 5.10, which causes SvCUR to fail an + * assertion with -DDEBUGGING, although SvCUR is documented to + * return the xpv_cur field which certainly exists after upgrading. + * according to nicholas clark, calling SvPOK fixes this. + * But it doesn't fix it, so try another workaround, call SvPV_nolen + * and hope for the best. + * Damnit, SvPV_nolen still trips over yet another assertion. This + * assertion business is seriously broken, try yet another workaround + * for the broken -DDEBUGGING. + */ + { +#ifdef DEBUGGING + STRLEN offset = SvOK (string) ? sv_len (string) : 0; +#else + STRLEN offset = SvCUR (string); +#endif + + if (offset > json->max_size && json->max_size) + croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu", + (unsigned long)SvCUR (string), (unsigned long)json->max_size); + } - if (json->flags & F_UTF8) + if (DECODE_WANTS_OCTETS (json)) sv_utf8_downgrade (string, 0); else sv_utf8_upgrade (string); SvGROW (string, SvCUR (string) + 1); // should basically be a NOP - dec.json = *json; - dec.cur = SvPVX (string); - dec.end = SvEND (string); - dec.err = 0; - dec.depth = 0; - dec.maxdepth = DEC_DEPTH (dec.json.flags); + dec.json = *json; + dec.cur = SvPVX (string); + dec.end = SvEND (string); + dec.err = 0; + dec.depth = 0; if (dec.json.cb_object || dec.json.cb_sk_object) dec.json.flags |= F_HOOK; @@ -1372,7 +1789,9 @@ decode_ws (&dec); sv = decode_sv (&dec); - if (!(offset_return || !sv)) + if (offset_return) + *offset_return = dec.cur - SvPVX (string); + else if (sv) { // check for trailing garbage decode_ws (&dec); @@ -1385,16 +1804,6 @@ } } - 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) { SV *uni = sv_newmortal (); @@ -1408,21 +1817,179 @@ pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ); LEAVE; - croak ("%s, at character offset %d [\"%s\"]", + croak ("%s, at character offset %d (before \"%s\")", dec.err, - (int)offset, + (int)ptr_to_index (string, dec.cur), dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); } sv = sv_2mortal (sv); - if (!(dec.json.flags & F_ALLOW_NONREF) && !SvROK (sv)) + if (!(dec.json.flags & F_ALLOW_NONREF) && json_nonref (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; } ///////////////////////////////////////////////////////////////////////////// +// incremental parser + +static void +incr_parse (JSON *self) +{ + const char *p = SvPVX (self->incr_text) + self->incr_pos; + + // the state machine here is a bit convoluted and could be simplified a lot + // but this would make it slower, so... + + for (;;) + { + //printf ("loop pod %d *p<%c><%s>, mode %d nest %d\n", p - SvPVX (self->incr_text), *p, p, self->incr_mode, self->incr_nest);//D + switch (self->incr_mode) + { + // only used for initial whitespace skipping + case INCR_M_WS: + for (;;) + { + if (*p > 0x20) + { + if (*p == '#') + { + self->incr_mode = INCR_M_C0; + goto incr_m_c; + } + else + { + self->incr_mode = INCR_M_JSON; + goto incr_m_json; + } + } + else if (!*p) + goto interrupt; + + ++p; + } + + // skip a single char inside a string (for \\-processing) + case INCR_M_BS: + if (!*p) + goto interrupt; + + ++p; + self->incr_mode = INCR_M_STR; + goto incr_m_str; + + // inside #-style comments + case INCR_M_C0: + case INCR_M_C1: + incr_m_c: + for (;;) + { + if (*p == '\n') + { + self->incr_mode = self->incr_mode == INCR_M_C0 ? INCR_M_WS : INCR_M_JSON; + break; + } + else if (!*p) + goto interrupt; + + ++p; + } + + break; + + // inside a string + case INCR_M_STR: + incr_m_str: + for (;;) + { + if (*p == '"') + { + ++p; + self->incr_mode = INCR_M_JSON; + + if (!self->incr_nest) + goto interrupt; + + goto incr_m_json; + } + else if (*p == '\\') + { + ++p; // "virtually" consumes character after \ + + if (!*p) // if at end of string we have to switch modes + { + self->incr_mode = INCR_M_BS; + goto interrupt; + } + } + else if (!*p) + goto interrupt; + + ++p; + } + + // after initial ws, outside string + case INCR_M_JSON: + incr_m_json: + for (;;) + { + switch (*p++) + { + case 0: + --p; + goto interrupt; + + case 0x09: + case 0x0a: + case 0x0d: + case 0x20: + if (!self->incr_nest) + { + --p; // do not eat the whitespace, let the next round do it + goto interrupt; + } + break; + + case '"': + self->incr_mode = INCR_M_STR; + goto incr_m_str; + + case '[': + case '{': + case '(': + if (++self->incr_nest > self->max_depth) + croak (ERR_NESTING_EXCEEDED); + break; + + case ']': + case '}': + if (--self->incr_nest <= 0) + goto interrupt; + break; + + case ')': + --self->incr_nest; + break; + + case '#': + self->incr_mode = INCR_M_C1; + goto incr_m_c; + } + } + } + + modechange: + ; + } + +interrupt: + self->incr_pos = p - SvPVX (self->incr_text); + //printf ("interrupt<%.*s>\n", self->incr_pos, SvPVX(self->incr_text));//D + //printf ("return pos %d mode %d nest %d\n", self->incr_pos, self->incr_mode, self->incr_nest);//D +} + +///////////////////////////////////////////////////////////////////////////// // XS interface functions MODULE = JSON::XS PACKAGE = JSON::XS @@ -1438,30 +2005,56 @@ : i >= 'A' && i <= 'F' ? i - 'A' + 10 : -1; - json_stash = gv_stashpv ("JSON::XS" , 1); - json_boolean_stash = gv_stashpv ("JSON::XS::Boolean", 1); + json_stash = gv_stashpv ("JSON::XS" , 1); + bool_stash = gv_stashpv ("Types::Serialiser::Boolean", 1); + bool_false = get_bool ("Types::Serialiser::false"); + bool_true = get_bool ("Types::Serialiser::true"); + + sv_json = newSVpv ("JSON", 0); + SvREADONLY_on (sv_json); - json_true = get_sv ("JSON::XS::true" , 1); SvREADONLY_on (json_true ); - json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false); + CvNODEBUG_on (get_cv ("JSON::XS::incr_text", 0)); /* the debugger completely breaks lvalue subs */ } PROTOTYPES: DISABLE void CLONE (...) CODE: - json_stash = 0; - json_boolean_stash = 0; + // as long as these writes are atomic, the race should not matter + // as existing threads either already use 0, or use the old value, + // which is sitll correct for the initial thread. + json_stash = 0; + bool_stash = 0; + bool_false = 0; + bool_true = 0; void new (char *klass) PPCODE: { - SV *pv = NEWSV (0, sizeof (JSON)); + 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))); + json_init ((JSON *)SvPVX (pv)); + XPUSHs (sv_2mortal (sv_bless ( + newRV_noinc (pv), + strEQ (klass, "JSON::XS") ? JSON_STASH : gv_stashpv (klass, 1) + ))); } +void boolean_values (JSON *self, SV *v_false = 0, SV *v_true = 0) + PPCODE: + self->v_false = newSVsv (v_false); + self->v_true = newSVsv (v_true); + XPUSHs (ST (0)); + +void get_boolean_values (JSON *self) + PPCODE: + if (self->v_false && self->v_true) + { + EXTEND (SP, 2); + PUSHs (self->v_false); + PUSHs (self->v_true); + } + void ascii (JSON *self, int enable = 1) ALIAS: ascii = F_ASCII @@ -1477,6 +2070,8 @@ allow_blessed = F_ALLOW_BLESSED convert_blessed = F_CONV_BLESSED relaxed = F_RELAXED + allow_unknown = F_ALLOW_UNKNOWN + allow_tags = F_ALLOW_TAGS PPCODE: { if (enable) @@ -1496,55 +2091,35 @@ get_canonical = F_CANONICAL get_space_before = F_SPACE_BEFORE get_space_after = F_SPACE_AFTER - get_pretty = F_PRETTY get_allow_nonref = F_ALLOW_NONREF get_shrink = F_SHRINK get_allow_blessed = F_ALLOW_BLESSED get_convert_blessed = F_CONV_BLESSED get_relaxed = F_RELAXED + get_allow_unknown = F_ALLOW_UNKNOWN + get_allow_tags = F_ALLOW_TAGS PPCODE: XPUSHs (boolSV (self->flags & ix)); -void max_depth (JSON *self, UV max_depth = 0x80000000UL) +void max_depth (JSON *self, U32 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); - + self->max_depth = max_depth; XPUSHs (ST (0)); -} -int get_max_depth (JSON *self) +U32 get_max_depth (JSON *self) CODE: - RETVAL = DEC_DEPTH (self->flags); + RETVAL = self->max_depth; OUTPUT: RETVAL -void max_size (JSON *self, UV max_size = 0) +void max_size (JSON *self, U32 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); - + self->max_size = max_size; XPUSHs (ST (0)); -} int get_max_size (JSON *self) CODE: - RETVAL = DEC_SIZE (self->flags); + RETVAL = self->max_size; OUTPUT: RETVAL @@ -1560,7 +2135,7 @@ void filter_json_single_key_object (JSON *self, SV *key, SV *cb = &PL_sv_undef) PPCODE: { - if (!self->cb_sk_object) + if (!self->cb_sk_object) self->cb_sk_object = newHV (); if (SvOK (cb)) @@ -1581,39 +2156,175 @@ void encode (JSON *self, SV *scalar) PPCODE: - XPUSHs (encode_json (scalar, self)); + PUTBACK; scalar = encode_json (scalar, self); SPAGAIN; + XPUSHs (scalar); void decode (JSON *self, SV *jsonstr) PPCODE: - XPUSHs (decode_json (jsonstr, self, 0)); + PUTBACK; jsonstr = decode_json (jsonstr, self, 0); SPAGAIN; + XPUSHs (jsonstr); void decode_prefix (JSON *self, SV *jsonstr) PPCODE: { - UV offset; + SV *sv; + STRLEN offset; + PUTBACK; sv = decode_json (jsonstr, self, &offset); SPAGAIN; EXTEND (SP, 2); - PUSHs (decode_json (jsonstr, self, &offset)); - PUSHs (sv_2mortal (newSVuv (offset))); + PUSHs (sv); + PUSHs (sv_2mortal (newSVuv (ptr_to_index (jsonstr, SvPV_nolen (jsonstr) + offset)))); +} + +void incr_parse (JSON *self, SV *jsonstr = 0) + PPCODE: +{ + if (!self->incr_text) + self->incr_text = newSVpvn ("", 0); + + /* if utf8-ness doesn't match the decoder, need to upgrade/downgrade */ + if (!DECODE_WANTS_OCTETS (self) == !SvUTF8 (self->incr_text)) + if (DECODE_WANTS_OCTETS (self)) + { + if (self->incr_pos) + self->incr_pos = utf8_length ((U8 *)SvPVX (self->incr_text), + (U8 *)SvPVX (self->incr_text) + self->incr_pos); + + sv_utf8_downgrade (self->incr_text, 0); + } + else + { + sv_utf8_upgrade (self->incr_text); + + if (self->incr_pos) + self->incr_pos = utf8_hop ((U8 *)SvPVX (self->incr_text), self->incr_pos) + - (U8 *)SvPVX (self->incr_text); + } + + // append data, if any + if (jsonstr) + { + /* make sure both strings have same encoding */ + if (SvUTF8 (jsonstr) != SvUTF8 (self->incr_text)) + if (SvUTF8 (jsonstr)) + sv_utf8_downgrade (jsonstr, 0); + else + sv_utf8_upgrade (jsonstr); + + /* and then just blindly append */ + { + STRLEN len; + const char *str = SvPV (jsonstr, len); + STRLEN cur = SvCUR (self->incr_text); + + if (SvLEN (self->incr_text) - cur <= len) + json_sv_grow (self->incr_text, cur, len); + + Move (str, SvEND (self->incr_text), len, char); + SvCUR_set (self->incr_text, SvCUR (self->incr_text) + len); + *SvEND (self->incr_text) = 0; // this should basically be a nop, too, but make sure it's there + } + } + + if (GIMME_V != G_VOID) + do + { + SV *sv; + STRLEN offset; + + if (!INCR_DONE (self)) + { + incr_parse (self); + + if (self->incr_pos > self->max_size && self->max_size) + croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu", + (unsigned long)self->incr_pos, (unsigned long)self->max_size); + + if (!INCR_DONE (self)) + { + // as an optimisation, do not accumulate white space in the incr buffer + if (self->incr_mode == INCR_M_WS && self->incr_pos) + { + self->incr_pos = 0; + SvCUR_set (self->incr_text, 0); + } + + break; + } + } + + PUTBACK; sv = decode_json (self->incr_text, self, &offset); SPAGAIN; + XPUSHs (sv); + + self->incr_pos -= offset; + self->incr_nest = 0; + self->incr_mode = 0; + + sv_chop (self->incr_text, SvPVX (self->incr_text) + offset); + } + while (GIMME_V == G_ARRAY); +} + +SV *incr_text (JSON *self) + ATTRS: lvalue + CODE: +{ + if (self->incr_pos) + croak ("incr_text can not be called when the incremental parser already started parsing"); + + RETVAL = self->incr_text ? SvREFCNT_inc (self->incr_text) : &PL_sv_undef; +} + OUTPUT: + RETVAL + +void incr_skip (JSON *self) + CODE: +{ + if (self->incr_pos) + { + sv_chop (self->incr_text, SvPV_nolen (self->incr_text) + self->incr_pos); + self->incr_pos = 0; + self->incr_nest = 0; + self->incr_mode = 0; + } +} + +void incr_reset (JSON *self) + CODE: +{ + SvREFCNT_dec (self->incr_text); + self->incr_text = 0; + self->incr_pos = 0; + self->incr_nest = 0; + self->incr_mode = 0; } void DESTROY (JSON *self) CODE: + SvREFCNT_dec (self->v_false); + SvREFCNT_dec (self->v_true); SvREFCNT_dec (self->cb_sk_object); SvREFCNT_dec (self->cb_object); + SvREFCNT_dec (self->incr_text); PROTOTYPES: ENABLE -void to_json (SV *scalar) +void encode_json (SV *scalar) PPCODE: { - JSON json = { F_DEFAULT | F_UTF8 }; - XPUSHs (encode_json (scalar, &json)); + JSON json; + json_init (&json); + json.flags |= F_UTF8; + PUTBACK; scalar = encode_json (scalar, &json); SPAGAIN; + XPUSHs (scalar); } -void from_json (SV *jsonstr) +void decode_json (SV *jsonstr) PPCODE: { - JSON json = { F_DEFAULT | F_UTF8 }; - XPUSHs (decode_json (jsonstr, &json, 0)); + JSON json; + json_init (&json); + json.flags |= F_UTF8; + PUTBACK; jsonstr = decode_json (jsonstr, &json, 0); SPAGAIN; + XPUSHs (jsonstr); }