ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/JSON-XS/XS.xs
(Generate patch)

Comparing JSON-XS/XS.xs (file contents):
Revision 1.30 by root, Wed May 9 16:10:37 2007 UTC vs.
Revision 1.47 by root, Sun Jul 1 14:08:03 2007 UTC

9 9
10#if defined(__BORLANDC__) || defined(_MSC_VER) 10#if defined(__BORLANDC__) || defined(_MSC_VER)
11# define snprintf _snprintf // C compilers have this in stdio.h 11# define snprintf _snprintf // C compilers have this in stdio.h
12#endif 12#endif
13 13
14// some old perls do not have this, try to make it work, no
15// guarentees, though. if it breaks, you get to keep the pieces.
16#ifndef UTF8_MAXBYTES
17# define UTF8_MAXBYTES 13
18#endif
19
14#define F_ASCII 0x00000001UL 20#define F_ASCII 0x00000001UL
15#define F_LATIN1 0x00000002UL 21#define F_LATIN1 0x00000002UL
16#define F_UTF8 0x00000004UL 22#define F_UTF8 0x00000004UL
17#define F_INDENT 0x00000008UL 23#define F_INDENT 0x00000008UL
18#define F_CANONICAL 0x00000010UL 24#define F_CANONICAL 0x00000010UL
19#define F_SPACE_BEFORE 0x00000020UL 25#define F_SPACE_BEFORE 0x00000020UL
20#define F_SPACE_AFTER 0x00000040UL 26#define F_SPACE_AFTER 0x00000040UL
21#define F_ALLOW_NONREF 0x00000100UL 27#define F_ALLOW_NONREF 0x00000100UL
22#define F_SHRINK 0x00000200UL 28#define F_SHRINK 0x00000200UL
29#define F_ALLOW_BLESSED 0x00000400UL
30#define F_CONV_BLESSED 0x00000800UL // NYI
23#define F_MAXDEPTH 0xf8000000UL 31#define F_MAXDEPTH 0xf8000000UL
24#define S_MAXDEPTH 27 32#define S_MAXDEPTH 27
33#define F_MAXSIZE 0x01f00000UL
34#define S_MAXSIZE 20
25 35
26#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH)) 36#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH))
27 37#define DEC_SIZE(flags) (1UL << ((flags & F_MAXSIZE ) >> S_MAXSIZE ))
28// F_SELFCONVERT? <=> to_json/toJson
29// F_BLESSED? <=> { $__class__$ => }
30 38
31#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER 39#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER
32#define F_DEFAULT (9UL << S_MAXDEPTH) 40#define F_DEFAULT (9UL << S_MAXDEPTH)
33 41
34#define INIT_SIZE 32 // initial scalar size to be allocated 42#define INIT_SIZE 32 // initial scalar size to be allocated
35#define INDENT_STEP 3 // spaces per indentation level 43#define INDENT_STEP 3 // spaces per indentation level
36 44
37#define SHORT_STRING_LEN 512 // special-case strings of up to this size 45#define SHORT_STRING_LEN 16384 // special-case strings of up to this size
38 46
39#define SB do { 47#define SB do {
40#define SE } while (0) 48#define SE } while (0)
41 49
50#if __GNUC__ >= 3
51# define expect(expr,value) __builtin_expect ((expr),(value))
52# define inline inline
53#else
54# define expect(expr,value) (expr)
55# define inline static
56#endif
57
58#define expect_false(expr) expect ((expr) != 0, 0)
59#define expect_true(expr) expect ((expr) != 0, 1)
60
42static HV *json_stash; // JSON::XS:: 61static HV *json_stash, *json_boolean_stash; // JSON::XS::
62static SV *json_true, *json_false;
63
64typedef struct json {
65 U32 flags;
66} JSON__XS;
43 67
44///////////////////////////////////////////////////////////////////////////// 68/////////////////////////////////////////////////////////////////////////////
45// utility functions 69// utility functions
46 70
47static UV * 71static UV *
70// decode an utf-8 character and return it, or (UV)-1 in 94// decode an utf-8 character and return it, or (UV)-1 in
71// case of an error. 95// case of an error.
72// we special-case "safe" characters from U+80 .. U+7FF, 96// we special-case "safe" characters from U+80 .. U+7FF,
73// but use the very good perl function to parse anything else. 97// but use the very good perl function to parse anything else.
74// note that we never call this function for a ascii codepoints 98// note that we never call this function for a ascii codepoints
75static UV 99inline UV
76decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen) 100decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
77{ 101{
78 if (s[0] > 0xdf || s[0] < 0xc2) 102 if (expect_false (s[0] > 0xdf || s[0] < 0xc2))
79 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY); 103 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY);
80 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf) 104 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf)
81 { 105 {
82 *clen = 2; 106 *clen = 2;
83 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f); 107 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
96typedef struct 120typedef struct
97{ 121{
98 char *cur; // SvPVX (sv) + current output position 122 char *cur; // SvPVX (sv) + current output position
99 char *end; // SvEND (sv) 123 char *end; // SvEND (sv)
100 SV *sv; // result scalar 124 SV *sv; // result scalar
101 U32 flags; // F_* 125 struct json json;
102 U32 indent; // indentation level 126 U32 indent; // indentation level
103 U32 maxdepth; // max. indentation/recursion level 127 U32 maxdepth; // max. indentation/recursion level
104} enc_t; 128} enc_t;
105 129
106static void 130inline void
107need (enc_t *enc, STRLEN len) 131need (enc_t *enc, STRLEN len)
108{ 132{
109 if (enc->cur + len >= enc->end) 133 if (expect_false (enc->cur + len >= enc->end))
110 { 134 {
111 STRLEN cur = enc->cur - SvPVX (enc->sv); 135 STRLEN cur = enc->cur - SvPVX (enc->sv);
112 SvGROW (enc->sv, cur + len + 1); 136 SvGROW (enc->sv, cur + len + 1);
113 enc->cur = SvPVX (enc->sv) + cur; 137 enc->cur = SvPVX (enc->sv) + cur;
114 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1; 138 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
115 } 139 }
116} 140}
117 141
118static void 142inline void
119encode_ch (enc_t *enc, char ch) 143encode_ch (enc_t *enc, char ch)
120{ 144{
121 need (enc, 1); 145 need (enc, 1);
122 *enc->cur++ = ch; 146 *enc->cur++ = ch;
123} 147}
131 155
132 while (str < end) 156 while (str < end)
133 { 157 {
134 unsigned char ch = *(unsigned char *)str; 158 unsigned char ch = *(unsigned char *)str;
135 159
136 if (ch >= 0x20 && ch < 0x80) // most common case 160 if (expect_true (ch >= 0x20 && ch < 0x80)) // most common case
137 { 161 {
138 if (ch == '"') // but with slow exceptions 162 if (expect_false (ch == '"')) // but with slow exceptions
139 { 163 {
140 need (enc, len += 1); 164 need (enc, len += 1);
141 *enc->cur++ = '\\'; 165 *enc->cur++ = '\\';
142 *enc->cur++ = '"'; 166 *enc->cur++ = '"';
143 } 167 }
144 else if (ch == '\\') 168 else if (expect_false (ch == '\\'))
145 { 169 {
146 need (enc, len += 1); 170 need (enc, len += 1);
147 *enc->cur++ = '\\'; 171 *enc->cur++ = '\\';
148 *enc->cur++ = '\\'; 172 *enc->cur++ = '\\';
149 } 173 }
167 STRLEN clen; 191 STRLEN clen;
168 UV uch; 192 UV uch;
169 193
170 if (is_utf8) 194 if (is_utf8)
171 { 195 {
172 //uch = utf8n_to_uvuni (str, end - str, &clen, UTF8_CHECK_ONLY);
173 uch = decode_utf8 (str, end - str, &clen); 196 uch = decode_utf8 (str, end - str, &clen);
174 if (clen == (STRLEN)-1) 197 if (clen == (STRLEN)-1)
175 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str); 198 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str);
176 } 199 }
177 else 200 else
181 } 204 }
182 205
183 if (uch > 0x10FFFFUL) 206 if (uch > 0x10FFFFUL)
184 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch); 207 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
185 208
186 if (uch < 0x80 || enc->flags & F_ASCII || (enc->flags & F_LATIN1 && uch > 0xFF)) 209 if (uch < 0x80 || enc->json.flags & F_ASCII || (enc->json.flags & F_LATIN1 && uch > 0xFF))
187 { 210 {
188 if (uch > 0xFFFFUL) 211 if (uch > 0xFFFFUL)
189 { 212 {
190 need (enc, len += 11); 213 need (enc, len += 11);
191 sprintf (enc->cur, "\\u%04x\\u%04x", 214 sprintf (enc->cur, "\\u%04x\\u%04x",
205 *enc->cur++ = hexdigit [(uch >> 0) & 15]; 228 *enc->cur++ = hexdigit [(uch >> 0) & 15];
206 } 229 }
207 230
208 str += clen; 231 str += clen;
209 } 232 }
210 else if (enc->flags & F_LATIN1) 233 else if (enc->json.flags & F_LATIN1)
211 { 234 {
212 *enc->cur++ = uch; 235 *enc->cur++ = uch;
213 str += clen; 236 str += clen;
214 } 237 }
215 else if (is_utf8) 238 else if (is_utf8)
233 256
234 --len; 257 --len;
235 } 258 }
236} 259}
237 260
238static void 261inline void
239encode_indent (enc_t *enc) 262encode_indent (enc_t *enc)
240{ 263{
241 if (enc->flags & F_INDENT) 264 if (enc->json.flags & F_INDENT)
242 { 265 {
243 int spaces = enc->indent * INDENT_STEP; 266 int spaces = enc->indent * INDENT_STEP;
244 267
245 need (enc, spaces); 268 need (enc, spaces);
246 memset (enc->cur, ' ', spaces); 269 memset (enc->cur, ' ', spaces);
247 enc->cur += spaces; 270 enc->cur += spaces;
248 } 271 }
249} 272}
250 273
251static void 274inline void
252encode_space (enc_t *enc) 275encode_space (enc_t *enc)
253{ 276{
254 need (enc, 1); 277 need (enc, 1);
255 encode_ch (enc, ' '); 278 encode_ch (enc, ' ');
256} 279}
257 280
258static void 281inline void
259encode_nl (enc_t *enc) 282encode_nl (enc_t *enc)
260{ 283{
261 if (enc->flags & F_INDENT) 284 if (enc->json.flags & F_INDENT)
262 { 285 {
263 need (enc, 1); 286 need (enc, 1);
264 encode_ch (enc, '\n'); 287 encode_ch (enc, '\n');
265 } 288 }
266} 289}
267 290
268static void 291inline void
269encode_comma (enc_t *enc) 292encode_comma (enc_t *enc)
270{ 293{
271 encode_ch (enc, ','); 294 encode_ch (enc, ',');
272 295
273 if (enc->flags & F_INDENT) 296 if (enc->json.flags & F_INDENT)
274 encode_nl (enc); 297 encode_nl (enc);
275 else if (enc->flags & F_SPACE_AFTER) 298 else if (enc->json.flags & F_SPACE_AFTER)
276 encode_space (enc); 299 encode_space (enc);
277} 300}
278 301
279static void encode_sv (enc_t *enc, SV *sv); 302static void encode_sv (enc_t *enc, SV *sv);
280 303
323 else 346 else
324 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he)); 347 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he));
325 348
326 encode_ch (enc, '"'); 349 encode_ch (enc, '"');
327 350
328 if (enc->flags & F_SPACE_BEFORE) encode_space (enc); 351 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc);
329 encode_ch (enc, ':'); 352 encode_ch (enc, ':');
330 if (enc->flags & F_SPACE_AFTER ) encode_space (enc); 353 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc);
331 encode_sv (enc, HeVAL (he)); 354 encode_sv (enc, HeVAL (he));
332} 355}
333 356
334// compare hash entries, used when all keys are bytestrings 357// compare hash entries, used when all keys are bytestrings
335static int 358static int
370 { 393 {
371 // for canonical output we have to sort by keys first 394 // for canonical output we have to sort by keys first
372 // actually, this is mostly due to the stupid so-called 395 // actually, this is mostly due to the stupid so-called
373 // security workaround added somewhere in 5.8.x. 396 // security workaround added somewhere in 5.8.x.
374 // that randomises hash orderings 397 // that randomises hash orderings
375 if (enc->flags & F_CANONICAL) 398 if (enc->json.flags & F_CANONICAL)
376 { 399 {
377 HE *he, *hes [count]; // if your compiler dies here, you need to enable C99 mode
378 int fast = 1; 400 int fast = 1;
401 HE *he;
402#if defined(__BORLANDC__) || defined(_MSC_VER)
403 HE **hes = _alloca (count * sizeof (HE));
404#else
405 HE *hes [count]; // if your compiler dies here, you need to enable C99 mode
406#endif
379 407
380 i = 0; 408 i = 0;
381 while ((he = hv_iternext (hv))) 409 while ((he = hv_iternext (hv)))
382 { 410 {
383 hes [i++] = he; 411 hes [i++] = he;
447 svtype svt; 475 svtype svt;
448 476
449 SvGETMAGIC (sv); 477 SvGETMAGIC (sv);
450 svt = SvTYPE (sv); 478 svt = SvTYPE (sv);
451 479
480 if (expect_false (SvOBJECT (sv)))
481 {
482 if (SvSTASH (sv) == json_boolean_stash)
483 {
484 if (SvIV (sv) == 0)
485 encode_str (enc, "false", 5, 0);
486 else
487 encode_str (enc, "true", 4, 0);
488 }
489 else
490 {
491#if 0
492 if (0 && sv_derived_from (rv, "JSON::Literal"))
493 {
494 // not yet
495 }
496#endif
497 if (enc->json.flags & F_CONV_BLESSED)
498 {
499 // we re-bless the reference to get overload and other niceties right
500 GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 1);
501
502 if (to_json)
503 {
504 dSP;
505 ENTER;
506 SAVETMPS;
507 PUSHMARK (SP);
508 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv)));
509
510 // calling with G_SCALAR ensures that we always get a 1 reutrn value
511 // check anyways.
512 PUTBACK;
513 assert (1 == call_sv ((SV *)GvCV (to_json), G_SCALAR));
514 SPAGAIN;
515
516 encode_sv (enc, POPs);
517
518 FREETMPS;
519 LEAVE;
520 }
521 else if (enc->json.flags & F_ALLOW_BLESSED)
522 encode_str (enc, "null", 4, 0);
523 else
524 croak ("encountered object '%s', but neither allow_blessed enabled nor TO_JSON method available on it",
525 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
526 }
527 else if (enc->json.flags & F_ALLOW_BLESSED)
528 encode_str (enc, "null", 4, 0);
529 else
530 croak ("encountered object '%s', but neither allow_blessed nor convert_blessed settings are enabled",
531 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
532 }
533 }
452 if (svt == SVt_PVHV) 534 else if (svt == SVt_PVHV)
453 encode_hv (enc, (HV *)sv); 535 encode_hv (enc, (HV *)sv);
454 else if (svt == SVt_PVAV) 536 else if (svt == SVt_PVAV)
455 encode_av (enc, (AV *)sv); 537 encode_av (enc, (AV *)sv);
456 else if (svt < SVt_PVAV) 538 else if (svt < SVt_PVAV)
457 { 539 {
481 encode_str (enc, str, len, SvUTF8 (sv)); 563 encode_str (enc, str, len, SvUTF8 (sv));
482 encode_ch (enc, '"'); 564 encode_ch (enc, '"');
483 } 565 }
484 else if (SvNOKp (sv)) 566 else if (SvNOKp (sv))
485 { 567 {
568 // trust that perl will do the right thing w.r.t. JSON syntax.
486 need (enc, NV_DIG + 32); 569 need (enc, NV_DIG + 32);
487 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur); 570 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
488 enc->cur += strlen (enc->cur); 571 enc->cur += strlen (enc->cur);
489 } 572 }
490 else if (SvIOKp (sv)) 573 else if (SvIOKp (sv))
491 { 574 {
492 need (enc, 64); 575 // we assume we can always read an IV as a UV
576 if (SvUV (sv) & ~(UV)0x7fff)
577 {
578 // large integer, use the (rather slow) snprintf way.
579 need (enc, sizeof (UV) * 3);
493 enc->cur += 580 enc->cur +=
494 SvIsUV(sv) 581 SvIsUV(sv)
495 ? snprintf (enc->cur, 64, "%"UVuf, (UV)SvUVX (sv)) 582 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv))
496 : snprintf (enc->cur, 64, "%"IVdf, (IV)SvIVX (sv)); 583 : snprintf (enc->cur, sizeof (UV) * 3, "%"IVdf, (IV)SvIVX (sv));
584 }
585 else
586 {
587 // optimise the "small number case"
588 // code will likely be branchless and use only a single multiplication
589 I32 i = SvIV (sv);
590 U32 u;
591 char digit, nz = 0;
592
593 need (enc, 6);
594
595 *enc->cur = '-'; enc->cur += i < 0 ? 1 : 0;
596 u = i < 0 ? -i : i;
597
598 // convert to 4.28 fixed-point representation
599 u = u * ((0xfffffff + 10000) / 10000); // 10**5, 5 fractional digits
600
601 // now output digit by digit, each time masking out the integer part
602 // and multiplying by 5 while moving the decimal point one to the right,
603 // resulting in a net multiplication by 10.
604 // we always write the digit to memory but conditionally increment
605 // the pointer, to ease the usage of conditional move instructions.
606 digit = u >> 28; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0xfffffff) * 5;
607 digit = u >> 27; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x7ffffff) * 5;
608 digit = u >> 26; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x3ffffff) * 5;
609 digit = u >> 25; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x1ffffff) * 5;
610 digit = u >> 24; *enc->cur = digit + '0'; enc->cur += 1; // correctly generate '0'
611 }
497 } 612 }
498 else if (SvROK (sv)) 613 else if (SvROK (sv))
499 encode_rv (enc, SvRV (sv)); 614 encode_rv (enc, SvRV (sv));
500 else if (!SvOK (sv)) 615 else if (!SvOK (sv))
501 encode_str (enc, "null", 4, 0); 616 encode_str (enc, "null", 4, 0);
503 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this", 618 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this",
504 SvPV_nolen (sv), SvFLAGS (sv)); 619 SvPV_nolen (sv), SvFLAGS (sv));
505} 620}
506 621
507static SV * 622static SV *
508encode_json (SV *scalar, U32 flags) 623encode_json (SV *scalar, struct json *json)
509{ 624{
510 enc_t enc; 625 enc_t enc;
511 626
512 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar)) 627 if (!(json->flags & F_ALLOW_NONREF) && !SvROK (scalar))
513 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)"); 628 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)");
514 629
515 enc.flags = flags; 630 enc.json = *json;
516 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 631 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
517 enc.cur = SvPVX (enc.sv); 632 enc.cur = SvPVX (enc.sv);
518 enc.end = SvEND (enc.sv); 633 enc.end = SvEND (enc.sv);
519 enc.indent = 0; 634 enc.indent = 0;
520 enc.maxdepth = DEC_DEPTH (flags); 635 enc.maxdepth = DEC_DEPTH (enc.json.flags);
521 636
522 SvPOK_only (enc.sv); 637 SvPOK_only (enc.sv);
523 encode_sv (&enc, scalar); 638 encode_sv (&enc, scalar);
524 639
525 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); 640 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
526 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings 641 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings
527 642
528 if (!(flags & (F_ASCII | F_LATIN1 | F_UTF8))) 643 if (!(enc.json.flags & (F_ASCII | F_LATIN1 | F_UTF8)))
529 SvUTF8_on (enc.sv); 644 SvUTF8_on (enc.sv);
530 645
531 if (enc.flags & F_SHRINK) 646 if (enc.json.flags & F_SHRINK)
532 shrink (enc.sv); 647 shrink (enc.sv);
533 648
534 return enc.sv; 649 return enc.sv;
535} 650}
536 651
541typedef struct 656typedef struct
542{ 657{
543 char *cur; // current parser pointer 658 char *cur; // current parser pointer
544 char *end; // end of input string 659 char *end; // end of input string
545 const char *err; // parse error, if != 0 660 const char *err; // parse error, if != 0
546 U32 flags; // F_* 661 struct json json;
547 U32 depth; // recursion depth 662 U32 depth; // recursion depth
548 U32 maxdepth; // recursion depth limit 663 U32 maxdepth; // recursion depth limit
549} dec_t; 664} dec_t;
550 665
551static void 666inline void
552decode_ws (dec_t *dec) 667decode_ws (dec_t *dec)
553{ 668{
554 for (;;) 669 for (;;)
555 { 670 {
556 char ch = *dec->cur; 671 char ch = *dec->cur;
582decode_4hex (dec_t *dec) 697decode_4hex (dec_t *dec)
583{ 698{
584 signed char d1, d2, d3, d4; 699 signed char d1, d2, d3, d4;
585 unsigned char *cur = (unsigned char *)dec->cur; 700 unsigned char *cur = (unsigned char *)dec->cur;
586 701
587 d1 = decode_hexdigit [cur [0]]; if (d1 < 0) ERR ("four hexadecimal digits expected"); 702 d1 = decode_hexdigit [cur [0]]; if (expect_false (d1 < 0)) ERR ("exactly four hexadecimal digits expected");
588 d2 = decode_hexdigit [cur [1]]; if (d2 < 0) ERR ("four hexadecimal digits expected"); 703 d2 = decode_hexdigit [cur [1]]; if (expect_false (d2 < 0)) ERR ("exactly four hexadecimal digits expected");
589 d3 = decode_hexdigit [cur [2]]; if (d3 < 0) ERR ("four hexadecimal digits expected"); 704 d3 = decode_hexdigit [cur [2]]; if (expect_false (d3 < 0)) ERR ("exactly four hexadecimal digits expected");
590 d4 = decode_hexdigit [cur [3]]; if (d4 < 0) ERR ("four hexadecimal digits expected"); 705 d4 = decode_hexdigit [cur [3]]; if (expect_false (d4 < 0)) ERR ("exactly four hexadecimal digits expected");
591 706
592 dec->cur += 4; 707 dec->cur += 4;
593 708
594 return ((UV)d1) << 12 709 return ((UV)d1) << 12
595 | ((UV)d2) << 8 710 | ((UV)d2) << 8
603static SV * 718static SV *
604decode_str (dec_t *dec) 719decode_str (dec_t *dec)
605{ 720{
606 SV *sv = 0; 721 SV *sv = 0;
607 int utf8 = 0; 722 int utf8 = 0;
723 char *dec_cur = dec->cur;
608 724
609 do 725 do
610 { 726 {
611 char buf [SHORT_STRING_LEN + UTF8_MAXBYTES]; 727 char buf [SHORT_STRING_LEN + UTF8_MAXBYTES];
612 char *cur = buf; 728 char *cur = buf;
613 729
614 do 730 do
615 { 731 {
616 unsigned char ch = *(unsigned char *)dec->cur++; 732 unsigned char ch = *(unsigned char *)dec_cur++;
617 733
618 if (ch == '"') 734 if (expect_false (ch == '"'))
619 { 735 {
620 --dec->cur; 736 --dec_cur;
621 break; 737 break;
622 } 738 }
623 else if (ch == '\\') 739 else if (expect_false (ch == '\\'))
624 { 740 {
625 switch (*dec->cur) 741 switch (*dec_cur)
626 { 742 {
627 case '\\': 743 case '\\':
628 case '/': 744 case '/':
629 case '"': *cur++ = *dec->cur++; break; 745 case '"': *cur++ = *dec_cur++; break;
630 746
631 case 'b': ++dec->cur; *cur++ = '\010'; break; 747 case 'b': ++dec_cur; *cur++ = '\010'; break;
632 case 't': ++dec->cur; *cur++ = '\011'; break; 748 case 't': ++dec_cur; *cur++ = '\011'; break;
633 case 'n': ++dec->cur; *cur++ = '\012'; break; 749 case 'n': ++dec_cur; *cur++ = '\012'; break;
634 case 'f': ++dec->cur; *cur++ = '\014'; break; 750 case 'f': ++dec_cur; *cur++ = '\014'; break;
635 case 'r': ++dec->cur; *cur++ = '\015'; break; 751 case 'r': ++dec_cur; *cur++ = '\015'; break;
636 752
637 case 'u': 753 case 'u':
638 { 754 {
639 UV lo, hi; 755 UV lo, hi;
640 ++dec->cur; 756 ++dec_cur;
641 757
758 dec->cur = dec_cur;
642 hi = decode_4hex (dec); 759 hi = decode_4hex (dec);
760 dec_cur = dec->cur;
643 if (hi == (UV)-1) 761 if (hi == (UV)-1)
644 goto fail; 762 goto fail;
645 763
646 // possibly a surrogate pair 764 // possibly a surrogate pair
647 if (hi >= 0xd800) 765 if (hi >= 0xd800)
648 if (hi < 0xdc00) 766 if (hi < 0xdc00)
649 { 767 {
650 if (dec->cur [0] != '\\' || dec->cur [1] != 'u') 768 if (dec_cur [0] != '\\' || dec_cur [1] != 'u')
651 ERR ("missing low surrogate character in surrogate pair"); 769 ERR ("missing low surrogate character in surrogate pair");
652 770
653 dec->cur += 2; 771 dec_cur += 2;
654 772
773 dec->cur = dec_cur;
655 lo = decode_4hex (dec); 774 lo = decode_4hex (dec);
775 dec_cur = dec->cur;
656 if (lo == (UV)-1) 776 if (lo == (UV)-1)
657 goto fail; 777 goto fail;
658 778
659 if (lo < 0xdc00 || lo >= 0xe000) 779 if (lo < 0xdc00 || lo >= 0xe000)
660 ERR ("surrogate pair expected"); 780 ERR ("surrogate pair expected");
674 *cur++ = hi; 794 *cur++ = hi;
675 } 795 }
676 break; 796 break;
677 797
678 default: 798 default:
679 --dec->cur; 799 --dec_cur;
680 ERR ("illegal backslash escape sequence in string"); 800 ERR ("illegal backslash escape sequence in string");
681 } 801 }
682 } 802 }
683 else if (ch >= 0x20 && ch <= 0x7f) 803 else if (expect_true (ch >= 0x20 && ch <= 0x7f))
684 *cur++ = ch; 804 *cur++ = ch;
685 else if (ch >= 0x80) 805 else if (ch >= 0x80)
686 { 806 {
687 STRLEN clen; 807 STRLEN clen;
688 UV uch; 808 UV uch;
689 809
690 --dec->cur; 810 --dec_cur;
691 811
692 uch = decode_utf8 (dec->cur, dec->end - dec->cur, &clen); 812 uch = decode_utf8 (dec_cur, dec->end - dec_cur, &clen);
693 if (clen == (STRLEN)-1) 813 if (clen == (STRLEN)-1)
694 ERR ("malformed UTF-8 character in JSON string"); 814 ERR ("malformed UTF-8 character in JSON string");
695 815
696 do 816 do
697 *cur++ = *dec->cur++; 817 *cur++ = *dec_cur++;
698 while (--clen); 818 while (--clen);
699 819
700 utf8 = 1; 820 utf8 = 1;
701 } 821 }
702 else 822 else
703 { 823 {
704 --dec->cur; 824 --dec_cur;
705 825
706 if (!ch) 826 if (!ch)
707 ERR ("unexpected end of string while parsing JSON string"); 827 ERR ("unexpected end of string while parsing JSON string");
708 else 828 else
709 ERR ("invalid character encountered while parsing JSON string"); 829 ERR ("invalid character encountered while parsing JSON string");
722 } 842 }
723 else 843 else
724 sv = newSVpvn (buf, len); 844 sv = newSVpvn (buf, len);
725 } 845 }
726 } 846 }
727 while (*dec->cur != '"'); 847 while (*dec_cur != '"');
728 848
729 ++dec->cur; 849 ++dec_cur;
730 850
731 if (sv) 851 if (sv)
732 { 852 {
733 SvPOK_only (sv); 853 SvPOK_only (sv);
734 *SvEND (sv) = 0; 854 *SvEND (sv) = 0;
737 SvUTF8_on (sv); 857 SvUTF8_on (sv);
738 } 858 }
739 else 859 else
740 sv = newSVpvn ("", 0); 860 sv = newSVpvn ("", 0);
741 861
862 dec->cur = dec_cur;
742 return sv; 863 return sv;
743 864
744fail: 865fail:
866 dec->cur = dec_cur;
745 return 0; 867 return 0;
746} 868}
747 869
748static SV * 870static SV *
749decode_num (dec_t *dec) 871decode_num (dec_t *dec)
807 is_nv = 1; 929 is_nv = 1;
808 } 930 }
809 931
810 if (!is_nv) 932 if (!is_nv)
811 { 933 {
812 UV uv; 934 // special case the rather common 1..4-digit-int case, assumes 32 bit ints or so
813 int numtype = grok_number (start, dec->cur - start, &uv); 935 if (*start == '-')
814 if (numtype & IS_NUMBER_IN_UV) 936 switch (dec->cur - start)
815 if (numtype & IS_NUMBER_NEG)
816 { 937 {
817 if (uv < (UV)IV_MIN) 938 case 2: return newSViv (-( start [1] - '0' * 1));
818 return newSViv (-(IV)uv); 939 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11));
940 case 4: return newSViv (-( start [1] * 100 + start [2] * 10 + start [3] - '0' * 111));
941 case 5: return newSViv (-(start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111));
819 } 942 }
943 else
944 switch (dec->cur - start)
945 {
946 case 1: return newSViv ( start [0] - '0' * 1);
947 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11);
948 case 3: return newSViv ( start [0] * 100 + start [1] * 10 + start [2] - '0' * 111);
949 case 4: return newSViv ( start [0] * 1000 + start [1] * 100 + start [2] * 10 + start [3] - '0' * 1111);
950 }
951
952 {
953 UV uv;
954 int numtype = grok_number (start, dec->cur - start, &uv);
955 if (numtype & IS_NUMBER_IN_UV)
956 if (numtype & IS_NUMBER_NEG)
957 {
958 if (uv < (UV)IV_MIN)
959 return newSViv (-(IV)uv);
960 }
820 else 961 else
821 return newSVuv (uv); 962 return newSVuv (uv);
963
964 // here would likely be the place for bigint support
822 } 965 }
966 }
823 967
968 // if we ever support bigint or bigfloat, this is the place for bigfloat
824 return newSVnv (Atof (start)); 969 return newSVnv (Atof (start));
825 970
826fail: 971fail:
827 return 0; 972 return 0;
828} 973}
882 if (*dec->cur == '}') 1027 if (*dec->cur == '}')
883 ++dec->cur; 1028 ++dec->cur;
884 else 1029 else
885 for (;;) 1030 for (;;)
886 { 1031 {
887 SV *key, *value;
888
889 decode_ws (dec); EXPECT_CH ('"'); 1032 decode_ws (dec); EXPECT_CH ('"');
890 1033
891 key = decode_str (dec); 1034 // heuristic: assume that
892 if (!key) 1035 // a) decode_str + hv_store_ent are abysmally slow.
893 goto fail; 1036 // b) most hash keys are short, simple ascii text.
1037 // => try to "fast-match" such strings to avoid
1038 // the overhead of decode_str + hv_store_ent.
1039 {
1040 SV *value;
1041 char *p = dec->cur;
1042 char *e = p + 24; // only try up to 24 bytes
894 1043
895 decode_ws (dec); EXPECT_CH (':'); 1044 for (;;)
896
897 value = decode_sv (dec);
898 if (!value)
899 { 1045 {
1046 // the >= 0x80 is true on most architectures
1047 if (p == e || *p < 0x20 || *p >= 0x80 || *p == '\\')
1048 {
1049 // slow path, back up and use decode_str
1050 SV *key = decode_str (dec);
1051 if (!key)
1052 goto fail;
1053
1054 decode_ws (dec); EXPECT_CH (':');
1055
1056 value = decode_sv (dec);
1057 if (!value)
1058 {
1059 SvREFCNT_dec (key);
1060 goto fail;
1061 }
1062
1063 hv_store_ent (hv, key, value, 0);
900 SvREFCNT_dec (key); 1064 SvREFCNT_dec (key);
1065
1066 break;
1067 }
1068 else if (*p == '"')
1069 {
1070 // fast path, got a simple key
1071 char *key = dec->cur;
1072 int len = p - key;
1073 dec->cur = p + 1;
1074
1075 decode_ws (dec); EXPECT_CH (':');
1076
1077 value = decode_sv (dec);
1078 if (!value)
901 goto fail; 1079 goto fail;
1080
1081 hv_store (hv, key, len, value, 0);
1082
1083 break;
1084 }
1085
1086 ++p;
902 } 1087 }
903 1088 }
904 hv_store_ent (hv, key, value, 0);
905 SvREFCNT_dec (key);
906 1089
907 decode_ws (dec); 1090 decode_ws (dec);
908 1091
909 if (*dec->cur == '}') 1092 if (*dec->cur == '}')
910 { 1093 {
929 1112
930static SV * 1113static SV *
931decode_sv (dec_t *dec) 1114decode_sv (dec_t *dec)
932{ 1115{
933 decode_ws (dec); 1116 decode_ws (dec);
1117
1118 // the beauty of JSON: you need exactly one character lookahead
1119 // to parse anything.
934 switch (*dec->cur) 1120 switch (*dec->cur)
935 { 1121 {
936 case '"': ++dec->cur; return decode_str (dec); 1122 case '"': ++dec->cur; return decode_str (dec);
937 case '[': ++dec->cur; return decode_av (dec); 1123 case '[': ++dec->cur; return decode_av (dec);
938 case '{': ++dec->cur; return decode_hv (dec); 1124 case '{': ++dec->cur; return decode_hv (dec);
944 1130
945 case 't': 1131 case 't':
946 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1132 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
947 { 1133 {
948 dec->cur += 4; 1134 dec->cur += 4;
949 return newSViv (1); 1135 return SvREFCNT_inc (json_true);
950 } 1136 }
951 else 1137 else
952 ERR ("'true' expected"); 1138 ERR ("'true' expected");
953 1139
954 break; 1140 break;
955 1141
956 case 'f': 1142 case 'f':
957 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1143 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
958 { 1144 {
959 dec->cur += 5; 1145 dec->cur += 5;
960 return newSViv (0); 1146 return SvREFCNT_inc (json_false);
961 } 1147 }
962 else 1148 else
963 ERR ("'false' expected"); 1149 ERR ("'false' expected");
964 1150
965 break; 1151 break;
983fail: 1169fail:
984 return 0; 1170 return 0;
985} 1171}
986 1172
987static SV * 1173static SV *
988decode_json (SV *string, U32 flags) 1174decode_json (SV *string, struct json *json, UV *offset_return)
989{ 1175{
990 dec_t dec; 1176 dec_t dec;
1177 UV offset;
991 SV *sv; 1178 SV *sv;
992 1179
993 SvGETMAGIC (string); 1180 SvGETMAGIC (string);
994 SvUPGRADE (string, SVt_PV); 1181 SvUPGRADE (string, SVt_PV);
995 1182
1183 if (json->flags & F_MAXSIZE && SvCUR (string) > DEC_SIZE (json->flags))
1184 croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu",
1185 (unsigned long)SvCUR (string), (unsigned long)DEC_SIZE (json->flags));
1186
996 if (flags & F_UTF8) 1187 if (json->flags & F_UTF8)
997 sv_utf8_downgrade (string, 0); 1188 sv_utf8_downgrade (string, 0);
998 else 1189 else
999 sv_utf8_upgrade (string); 1190 sv_utf8_upgrade (string);
1000 1191
1001 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP 1192 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
1002 1193
1003 dec.flags = flags; 1194 dec.json = *json;
1004 dec.cur = SvPVX (string); 1195 dec.cur = SvPVX (string);
1005 dec.end = SvEND (string); 1196 dec.end = SvEND (string);
1006 dec.err = 0; 1197 dec.err = 0;
1007 dec.depth = 0; 1198 dec.depth = 0;
1008 dec.maxdepth = DEC_DEPTH (dec.flags); 1199 dec.maxdepth = DEC_DEPTH (dec.json.flags);
1009 1200
1010 *dec.end = 0; // this should basically be a nop, too, but make sure its there 1201 *dec.end = 0; // this should basically be a nop, too, but make sure it's there
1011 sv = decode_sv (&dec); 1202 sv = decode_sv (&dec);
1012 1203
1204 if (!(offset_return || !sv))
1205 {
1206 // check for trailing garbage
1207 decode_ws (&dec);
1208
1209 if (*dec.cur)
1210 {
1211 dec.err = "garbage after JSON object";
1212 SvREFCNT_dec (sv);
1213 sv = 0;
1214 }
1215 }
1216
1217 if (offset_return || !sv)
1218 {
1219 offset = dec.json.flags & F_UTF8
1220 ? dec.cur - SvPVX (string)
1221 : utf8_distance (dec.cur, SvPVX (string));
1222
1223 if (offset_return)
1224 *offset_return = offset;
1225 }
1226
1013 if (!sv) 1227 if (!sv)
1014 { 1228 {
1015 IV offset = dec.flags & F_UTF8
1016 ? dec.cur - SvPVX (string)
1017 : utf8_distance (dec.cur, SvPVX (string));
1018 SV *uni = sv_newmortal (); 1229 SV *uni = sv_newmortal ();
1019 1230
1020 // horrible hack to silence warning inside pv_uni_display 1231 // horrible hack to silence warning inside pv_uni_display
1021 COP cop = *PL_curcop; 1232 COP cop = *PL_curcop;
1022 cop.cop_warnings = pWARN_NONE; 1233 cop.cop_warnings = pWARN_NONE;
1032 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); 1243 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
1033 } 1244 }
1034 1245
1035 sv = sv_2mortal (sv); 1246 sv = sv_2mortal (sv);
1036 1247
1037 if (!(dec.flags & F_ALLOW_NONREF) && !SvROK (sv)) 1248 if (!(dec.json.flags & F_ALLOW_NONREF) && !SvROK (sv))
1038 croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)"); 1249 croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)");
1039 1250
1040 return sv; 1251 return sv;
1041} 1252}
1042 1253
1046MODULE = JSON::XS PACKAGE = JSON::XS 1257MODULE = JSON::XS PACKAGE = JSON::XS
1047 1258
1048BOOT: 1259BOOT:
1049{ 1260{
1050 int i; 1261 int i;
1051
1052 memset (decode_hexdigit, 0xff, 256);
1053 1262
1054 for (i = 0; i < 256; ++i) 1263 for (i = 0; i < 256; ++i)
1055 decode_hexdigit [i] = 1264 decode_hexdigit [i] =
1056 i >= '0' && i <= '9' ? i - '0' 1265 i >= '0' && i <= '9' ? i - '0'
1057 : i >= 'a' && i <= 'f' ? i - 'a' + 10 1266 : i >= 'a' && i <= 'f' ? i - 'a' + 10
1058 : i >= 'A' && i <= 'F' ? i - 'A' + 10 1267 : i >= 'A' && i <= 'F' ? i - 'A' + 10
1059 : -1; 1268 : -1;
1060 1269
1061 json_stash = gv_stashpv ("JSON::XS", 1); 1270 json_stash = gv_stashpv ("JSON::XS" , 1);
1271 json_boolean_stash = gv_stashpv ("JSON::XS::Boolean", 1);
1272
1273 json_true = get_sv ("JSON::XS::true" , 1); SvREADONLY_on (json_true );
1274 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1062} 1275}
1063 1276
1064PROTOTYPES: DISABLE 1277PROTOTYPES: DISABLE
1065 1278
1066SV *new (char *dummy) 1279SV *new (char *dummy)
1069 OUTPUT: 1282 OUTPUT:
1070 RETVAL 1283 RETVAL
1071 1284
1072SV *ascii (SV *self, int enable = 1) 1285SV *ascii (SV *self, int enable = 1)
1073 ALIAS: 1286 ALIAS:
1074 ascii = F_ASCII 1287 ascii = F_ASCII
1075 latin1 = F_LATIN1 1288 latin1 = F_LATIN1
1076 utf8 = F_UTF8 1289 utf8 = F_UTF8
1077 indent = F_INDENT 1290 indent = F_INDENT
1078 canonical = F_CANONICAL 1291 canonical = F_CANONICAL
1079 space_before = F_SPACE_BEFORE 1292 space_before = F_SPACE_BEFORE
1080 space_after = F_SPACE_AFTER 1293 space_after = F_SPACE_AFTER
1081 pretty = F_PRETTY 1294 pretty = F_PRETTY
1082 allow_nonref = F_ALLOW_NONREF 1295 allow_nonref = F_ALLOW_NONREF
1083 shrink = F_SHRINK 1296 shrink = F_SHRINK
1297 allow_blessed = F_ALLOW_BLESSED
1298 convert_blessed = F_CONV_BLESSED
1084 CODE: 1299 CODE:
1085{ 1300{
1086 UV *uv = SvJSON (self); 1301 UV *uv = SvJSON (self);
1087 if (enable) 1302 if (enable)
1088 *uv |= ix; 1303 *uv |= ix;
1110 RETVAL = newSVsv (self); 1325 RETVAL = newSVsv (self);
1111} 1326}
1112 OUTPUT: 1327 OUTPUT:
1113 RETVAL 1328 RETVAL
1114 1329
1330SV *max_size (SV *self, UV max_size = 0)
1331 CODE:
1332{
1333 UV *uv = SvJSON (self);
1334 UV log2 = 0;
1335
1336 if (max_size > 0x80000000UL) max_size = 0x80000000UL;
1337 if (max_size == 1) max_size = 2;
1338
1339 while ((1UL << log2) < max_size)
1340 ++log2;
1341
1342 *uv = *uv & ~F_MAXSIZE | (log2 << S_MAXSIZE);
1343
1344 RETVAL = newSVsv (self);
1345}
1346 OUTPUT:
1347 RETVAL
1348
1115void encode (SV *self, SV *scalar) 1349void encode (SV *self, SV *scalar)
1116 PPCODE: 1350 PPCODE:
1351{
1352 struct json json = { *SvJSON (self) };
1117 XPUSHs (encode_json (scalar, *SvJSON (self))); 1353 XPUSHs (encode_json (scalar, &json));
1354}
1118 1355
1119void decode (SV *self, SV *jsonstr) 1356void decode (SV *self, SV *jsonstr)
1120 PPCODE: 1357 PPCODE:
1358{
1359 struct json json = { *SvJSON (self) };
1121 XPUSHs (decode_json (jsonstr, *SvJSON (self))); 1360 XPUSHs (decode_json (jsonstr, &json, 0));
1361}
1362
1363void decode_prefix (SV *self, SV *jsonstr)
1364 PPCODE:
1365{
1366 UV offset;
1367 struct json json = { *SvJSON (self) };
1368 EXTEND (SP, 2);
1369 PUSHs (decode_json (jsonstr, &json, &offset));
1370 PUSHs (sv_2mortal (newSVuv (offset)));
1371}
1122 1372
1123PROTOTYPES: ENABLE 1373PROTOTYPES: ENABLE
1124 1374
1125void to_json (SV *scalar) 1375void to_json (SV *scalar)
1126 ALIAS:
1127 objToJson = 0
1128 PPCODE: 1376 PPCODE:
1377{
1378 struct json json = { F_DEFAULT | F_UTF8 };
1129 XPUSHs (encode_json (scalar, F_DEFAULT | F_UTF8)); 1379 XPUSHs (encode_json (scalar, &json));
1380}
1130 1381
1131void from_json (SV *jsonstr) 1382void from_json (SV *jsonstr)
1132 ALIAS:
1133 jsonToObj = 0
1134 PPCODE: 1383 PPCODE:
1384{
1385 struct json json = { F_DEFAULT | F_UTF8 };
1135 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8)); 1386 XPUSHs (decode_json (jsonstr, &json, 0));
1387}
1136 1388

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines