--- JSON-XS/XS.xs 2007/07/02 00:48:18 1.51 +++ JSON-XS/XS.xs 2007/11/25 19:02:42 1.66 @@ -2,10 +2,11 @@ #include "perl.h" #include "XSUB.h" -#include "assert.h" -#include "string.h" -#include "stdlib.h" -#include "stdio.h" +#include +#include +#include +#include +#include #if defined(__BORLANDC__) || defined(_MSC_VER) # define snprintf _snprintf // C compilers have this in stdio.h @@ -28,6 +29,8 @@ #define F_SHRINK 0x00000200UL #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 @@ -59,12 +62,21 @@ #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, *cb_sk_object; + SV *cb_object; + HV *cb_sk_object; } JSON; ///////////////////////////////////////////////////////////////////////////// @@ -302,26 +314,35 @@ 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) + encode_ch (enc, '['); + + if (len >= 0) { - encode_indent (enc); - encode_sv (enc, *av_fetch (av, i, 0)); + encode_nl (enc); ++enc->indent; - if (i < len) - encode_comma (enc); - } + for (i = 0; i <= len; ++i) + { + SV **svp = av_fetch (av, i, 0); - encode_nl (enc); + encode_indent (enc); - --enc->indent; - encode_indent (enc); encode_ch (enc, ']'); + if (svp) + encode_sv (enc, *svp); + else + encode_str (enc, "null", 4, 0); + + if (i < len) + encode_comma (enc); + } + + encode_nl (enc); --enc->indent; encode_indent (enc); + } + + encode_ch (enc, ']'); } static void -encode_he (enc_t *enc, HE *he) +encode_hk (enc_t *enc, HE *he) { encode_ch (enc, '"'); @@ -344,7 +365,6 @@ if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc); encode_ch (enc, ':'); if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc); - encode_sv (enc, HeVAL (he)); } // compare hash entries, used when all keys are bytestrings @@ -359,8 +379,8 @@ STRLEN la = HeKLEN (a); STRLEN lb = HeKLEN (b); - if (!(cmp = memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb))) - cmp = la - lb; + if (!(cmp = memcmp (HeKEY (b), HeKEY (a), lb < la ? lb : la))) + cmp = lb - la; return cmp; } @@ -369,29 +389,45 @@ static int he_cmp_slow (const void *a, const void *b) { - return sv_cmp (HeSVKEY_force (*(HE **)a), HeSVKEY_force (*(HE **)b)); + return sv_cmp (HeSVKEY_force (*(HE **)b), HeSVKEY_force (*(HE **)a)); } static void encode_hv (enc_t *enc, HV *hv) { - int count, i; + HE *he; + int count; if (enc->indent >= enc->maxdepth) croak ("data structure too deep (hit recursion limit)"); - encode_ch (enc, '{'); encode_nl (enc); ++enc->indent; + encode_ch (enc, '{'); - if ((count = hv_iterinit (hv))) + // 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. + // that randomises hash orderings + if (enc->json.flags & F_CANONICAL) { - // 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. - // that randomises hash orderings - if (enc->json.flags & F_CANONICAL) + int count = hv_iterinit (hv); + + if (SvMAGICAL (hv)) { - int fast = 1; - HE *he; + // need to count by iterating. could improve by dynamically building the vector below + // but I don't care for the speed of this special case. + // note also that we will run into undefined behaviour when the two iterations + // do not result in the same count, something I might care for in some later release. + + count = 0; + while (hv_iternext (hv)) + ++count; + + hv_iterinit (hv); + } + + if (count) + { + int i, fast = 1; #if defined(__BORLANDC__) || defined(_MSC_VER) HE **hes = _alloca (count * sizeof (HE)); #else @@ -428,37 +464,46 @@ LEAVE; } - for (i = 0; i < count; ++i) + encode_nl (enc); ++enc->indent; + + while (count--) { encode_indent (enc); - encode_he (enc, hes [i]); + he = hes [count]; + encode_hk (enc, he); + encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he)); - if (i < count - 1) + if (count) encode_comma (enc); } - encode_nl (enc); + encode_nl (enc); --enc->indent; encode_indent (enc); } - else - { - HE *he = hv_iternext (hv); + } + else + { + if (hv_iterinit (hv) || SvMAGICAL (hv)) + if ((he = hv_iternext (hv))) + { + encode_nl (enc); ++enc->indent; - for (;;) - { - encode_indent (enc); - encode_he (enc, he); + for (;;) + { + encode_indent (enc); + encode_hk (enc, he); + encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he)); - if (!(he = hv_iternext (hv))) - break; + if (!(he = hv_iternext (hv))) + break; - encode_comma (enc); - } + encode_comma (enc); + } - encode_nl (enc); - } + encode_nl (enc); --enc->indent; encode_indent (enc); + } } - --enc->indent; encode_indent (enc); encode_ch (enc, '}'); + encode_ch (enc, '}'); } // encode objects, arrays and special \0=false and \1=true values. @@ -472,7 +517,11 @@ if (expect_false (SvOBJECT (sv))) { - if (SvSTASH (sv) == json_boolean_stash) + 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); @@ -490,20 +539,28 @@ 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", 1); + GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 0); if (to_json) { - dSP; ENTER; SAVETMPS; PUSHMARK (SP); + dSP; + + ENTER; SAVETMPS; PUSHMARK (SP); XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv))); - // calling with G_SCALAR ensures that we always get a 1 reutrn value - // check anyways. + // calling with G_SCALAR ensures that we always get a 1 return value PUTBACK; - assert (1 == call_sv ((SV *)GvCV (to_json), G_SCALAR)); + call_sv ((SV *)GvCV (to_json), G_SCALAR); SPAGAIN; - encode_sv (enc, POPs); + // 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; } @@ -656,15 +713,35 @@ } dec_t; inline void +decode_comment (dec_t *dec) +{ + // only '#'-style comments allowed a.t.m. + + while (*dec->cur && *dec->cur != 0x0a && *dec->cur != 0x0d) + ++dec->cur; +} + +inline void decode_ws (dec_t *dec) { for (;;) { char ch = *dec->cur; - if (ch > 0x20 - || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)) - break; + if (ch > 0x20) + { + if (expect_false (ch == '#')) + { + if (dec->json.flags & F_RELAXED) + decode_comment (dec); + else + break; + } + else + break; + } + else if (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09) + break; // parse error, but let higher level handle it, gives better error messages ++dec->cur; } @@ -923,9 +1000,11 @@ if (!is_nv) { + int len = dec->cur - start; + // special case the rather common 1..4-digit-int case, assumes 32 bit ints or so if (*start == '-') - switch (dec->cur - start) + switch (len) { case 2: return newSViv (-( start [1] - '0' * 1)); case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11)); @@ -933,7 +1012,7 @@ case 5: return newSViv (-(start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111)); } else - switch (dec->cur - start) + switch (len) { case 1: return newSViv ( start [0] - '0' * 1); case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11); @@ -943,7 +1022,7 @@ { UV uv; - int numtype = grok_number (start, dec->cur - start, &uv); + int numtype = grok_number (start, len, &uv); if (numtype & IS_NUMBER_IN_UV) if (numtype & IS_NUMBER_NEG) { @@ -952,12 +1031,24 @@ } else return newSVuv (uv); - - // here would likely be the place for bigint support } + + 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); } - // if we ever support bigint or bigfloat, this is the place for bigfloat + // loss of precision here return newSVnv (Atof (start)); fail: @@ -997,6 +1088,14 @@ ERR (", or ] expected while parsing array"); ++dec->cur; + + decode_ws (dec); + + if (*dec->cur == ']' && dec->json.flags & F_RELAXED) + { + ++dec->cur; + break; + } } DEC_DEC_DEPTH; @@ -1022,7 +1121,7 @@ else for (;;) { - decode_ws (dec); EXPECT_CH ('"'); + EXPECT_CH ('"'); // heuristic: assume that // a) decode_str + hv_store_ent are abysmally slow. @@ -1046,6 +1145,7 @@ decode_ws (dec); EXPECT_CH (':'); + decode_ws (dec); value = decode_sv (dec); if (!value) { @@ -1067,6 +1167,7 @@ decode_ws (dec); EXPECT_CH (':'); + decode_ws (dec); value = decode_sv (dec); if (!value) goto fail; @@ -1092,6 +1193,14 @@ ERR (", or } expected while parsing object/hash"); ++dec->cur; + + decode_ws (dec); + + if (*dec->cur == '}' && dec->json.flags & F_RELAXED) + { + ++dec->cur; + break; + } } DEC_DEC_DEPTH; @@ -1100,31 +1209,45 @@ // check filter callbacks if (dec->json.flags & F_HOOK) { - ENTER; SAVETMPS; - if (dec->json.cb_sk_object && HvKEYS (hv) == 1) { - int count; + HE *cb, *he; - dSP; PUSHMARK (SP); - XPUSHs (sv_2mortal (sv)); + hv_iterinit (hv); + he = hv_iternext (hv); + hv_iterinit (hv); - PUTBACK; count = call_sv (dec->json.cb_sk_object, G_ARRAY); SPAGAIN; + // 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 (count == 1) + if (cb) { - sv = newSVsv (POPs); - goto filter_ok; - } + dSP; + int count; - SvREFCNT_inc (sv); + 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; - dSP; ENTER; SAVETMPS; PUSHMARK (SP); + ENTER; SAVETMPS; PUSHMARK (SP); XPUSHs (sv_2mortal (sv)); PUTBACK; count = call_sv (dec->json.cb_object, G_ARRAY); SPAGAIN; @@ -1132,14 +1255,13 @@ if (count == 1) { sv = newSVsv (POPs); - goto filter_ok; + FREETMPS; LEAVE; + return sv; } SvREFCNT_inc (sv); + FREETMPS; LEAVE; } - -filter_ok: - FREETMPS; LEAVE; } return sv; @@ -1153,8 +1275,6 @@ static SV * decode_sv (dec_t *dec) { - decode_ws (dec); - // the beauty of JSON: you need exactly one character lookahead // to parse anything. switch (*dec->cur) @@ -1172,6 +1292,9 @@ if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) { dec->cur += 4; +#if JSON_SLOW + json_true = get_sv ("JSON::XS::true", 1); SvREADONLY_on (json_true); +#endif return SvREFCNT_inc (json_true); } else @@ -1183,6 +1306,9 @@ if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) { dec->cur += 5; +#if JSON_SLOW + json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false); +#endif return SvREFCNT_inc (json_false); } else @@ -1242,6 +1368,8 @@ dec.json.flags |= F_HOOK; *dec.end = 0; // this should basically be a nop, too, but make sure it's there + + decode_ws (&dec); sv = decode_sv (&dec); if (!(offset_return || !sv)) @@ -1319,6 +1447,11 @@ PROTOTYPES: DISABLE +void CLONE (...) + CODE: + json_stash = 0; + json_boolean_stash = 0; + void new (char *klass) PPCODE: { @@ -1326,7 +1459,7 @@ SvPOK_only (pv); Zero (SvPVX (pv), 1, JSON); ((JSON *)SvPVX (pv))->flags = F_DEFAULT; - XPUSHs (sv_2mortal (sv_bless (newRV_noinc (pv), json_stash))); + XPUSHs (sv_2mortal (sv_bless (newRV_noinc (pv), JSON_STASH))); } void ascii (JSON *self, int enable = 1) @@ -1343,6 +1476,7 @@ shrink = F_SHRINK allow_blessed = F_ALLOW_BLESSED convert_blessed = F_CONV_BLESSED + relaxed = F_RELAXED PPCODE: { if (enable) @@ -1353,6 +1487,24 @@ XPUSHs (ST (0)); } +void get_ascii (JSON *self) + ALIAS: + get_ascii = F_ASCII + get_latin1 = F_LATIN1 + get_utf8 = F_UTF8 + get_indent = F_INDENT + 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 + PPCODE: + XPUSHs (boolSV (self->flags & ix)); + void max_depth (JSON *self, UV max_depth = 0x80000000UL) PPCODE: { @@ -1368,6 +1520,12 @@ XPUSHs (ST (0)); } +int get_max_depth (JSON *self) + CODE: + RETVAL = DEC_DEPTH (self->flags); + OUTPUT: + RETVAL + void max_size (JSON *self, UV max_size = 0) PPCODE: { @@ -1384,28 +1542,39 @@ XPUSHs (ST (0)); } +int get_max_size (JSON *self) + CODE: + RETVAL = DEC_SIZE (self->flags); + OUTPUT: + RETVAL + void filter_json_object (JSON *self, SV *cb = &PL_sv_undef) - ALIAS: - filter_json_single_key_object = 1 PPCODE: { - SV **svp; + SvREFCNT_dec (self->cb_object); + self->cb_object = SvOK (cb) ? newSVsv (cb) : 0; - if (!SvOK (cb)) - cb = 0; - else - cb = newSVsv (cb); + XPUSHs (ST (0)); +} - switch (ix) - { - case 0: svp = &self->cb_object ; break; - case 1: svp = &self->cb_sk_object; break; - } +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 (*svp) - SvREFCNT_dec (*svp); + if (SvOK (cb)) + hv_store_ent (self->cb_sk_object, key, newSVsv (cb), 0); + else + { + hv_delete_ent (self->cb_sk_object, key, G_DISCARD, 0); - *svp = cb; + if (!HvKEYS (self->cb_sk_object)) + { + SvREFCNT_dec (self->cb_sk_object); + self->cb_sk_object = 0; + } + } XPUSHs (ST (0)); } @@ -1427,6 +1596,11 @@ 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)