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.34 by root, Wed May 23 22:07:13 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 int fast = 1; 400 int fast = 1;
378 HE *he; 401 HE *he;
379#if defined(__BORLANDC__) || defined(_MSC_VER) 402#if defined(__BORLANDC__) || defined(_MSC_VER)
380 HE **hes = _alloca (count * sizeof (HE)); 403 HE **hes = _alloca (count * sizeof (HE));
452 svtype svt; 475 svtype svt;
453 476
454 SvGETMAGIC (sv); 477 SvGETMAGIC (sv);
455 svt = SvTYPE (sv); 478 svt = SvTYPE (sv);
456 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 }
457 if (svt == SVt_PVHV) 534 else if (svt == SVt_PVHV)
458 encode_hv (enc, (HV *)sv); 535 encode_hv (enc, (HV *)sv);
459 else if (svt == SVt_PVAV) 536 else if (svt == SVt_PVAV)
460 encode_av (enc, (AV *)sv); 537 encode_av (enc, (AV *)sv);
461 else if (svt < SVt_PVAV) 538 else if (svt < SVt_PVAV)
462 { 539 {
486 encode_str (enc, str, len, SvUTF8 (sv)); 563 encode_str (enc, str, len, SvUTF8 (sv));
487 encode_ch (enc, '"'); 564 encode_ch (enc, '"');
488 } 565 }
489 else if (SvNOKp (sv)) 566 else if (SvNOKp (sv))
490 { 567 {
568 // trust that perl will do the right thing w.r.t. JSON syntax.
491 need (enc, NV_DIG + 32); 569 need (enc, NV_DIG + 32);
492 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur); 570 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
493 enc->cur += strlen (enc->cur); 571 enc->cur += strlen (enc->cur);
494 } 572 }
495 else if (SvIOKp (sv)) 573 else if (SvIOKp (sv))
496 { 574 {
497 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);
498 enc->cur += 580 enc->cur +=
499 SvIsUV(sv) 581 SvIsUV(sv)
500 ? snprintf (enc->cur, 64, "%"UVuf, (UV)SvUVX (sv)) 582 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv))
501 : 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 }
502 } 612 }
503 else if (SvROK (sv)) 613 else if (SvROK (sv))
504 encode_rv (enc, SvRV (sv)); 614 encode_rv (enc, SvRV (sv));
505 else if (!SvOK (sv)) 615 else if (!SvOK (sv))
506 encode_str (enc, "null", 4, 0); 616 encode_str (enc, "null", 4, 0);
508 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",
509 SvPV_nolen (sv), SvFLAGS (sv)); 619 SvPV_nolen (sv), SvFLAGS (sv));
510} 620}
511 621
512static SV * 622static SV *
513encode_json (SV *scalar, U32 flags) 623encode_json (SV *scalar, struct json *json)
514{ 624{
515 enc_t enc; 625 enc_t enc;
516 626
517 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar)) 627 if (!(json->flags & F_ALLOW_NONREF) && !SvROK (scalar))
518 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)");
519 629
520 enc.flags = flags; 630 enc.json = *json;
521 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 631 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
522 enc.cur = SvPVX (enc.sv); 632 enc.cur = SvPVX (enc.sv);
523 enc.end = SvEND (enc.sv); 633 enc.end = SvEND (enc.sv);
524 enc.indent = 0; 634 enc.indent = 0;
525 enc.maxdepth = DEC_DEPTH (flags); 635 enc.maxdepth = DEC_DEPTH (enc.json.flags);
526 636
527 SvPOK_only (enc.sv); 637 SvPOK_only (enc.sv);
528 encode_sv (&enc, scalar); 638 encode_sv (&enc, scalar);
529 639
530 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); 640 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
531 *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
532 642
533 if (!(flags & (F_ASCII | F_LATIN1 | F_UTF8))) 643 if (!(enc.json.flags & (F_ASCII | F_LATIN1 | F_UTF8)))
534 SvUTF8_on (enc.sv); 644 SvUTF8_on (enc.sv);
535 645
536 if (enc.flags & F_SHRINK) 646 if (enc.json.flags & F_SHRINK)
537 shrink (enc.sv); 647 shrink (enc.sv);
538 648
539 return enc.sv; 649 return enc.sv;
540} 650}
541 651
546typedef struct 656typedef struct
547{ 657{
548 char *cur; // current parser pointer 658 char *cur; // current parser pointer
549 char *end; // end of input string 659 char *end; // end of input string
550 const char *err; // parse error, if != 0 660 const char *err; // parse error, if != 0
551 U32 flags; // F_* 661 struct json json;
552 U32 depth; // recursion depth 662 U32 depth; // recursion depth
553 U32 maxdepth; // recursion depth limit 663 U32 maxdepth; // recursion depth limit
554} dec_t; 664} dec_t;
555 665
556static void 666inline void
557decode_ws (dec_t *dec) 667decode_ws (dec_t *dec)
558{ 668{
559 for (;;) 669 for (;;)
560 { 670 {
561 char ch = *dec->cur; 671 char ch = *dec->cur;
587decode_4hex (dec_t *dec) 697decode_4hex (dec_t *dec)
588{ 698{
589 signed char d1, d2, d3, d4; 699 signed char d1, d2, d3, d4;
590 unsigned char *cur = (unsigned char *)dec->cur; 700 unsigned char *cur = (unsigned char *)dec->cur;
591 701
592 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");
593 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");
594 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");
595 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");
596 706
597 dec->cur += 4; 707 dec->cur += 4;
598 708
599 return ((UV)d1) << 12 709 return ((UV)d1) << 12
600 | ((UV)d2) << 8 710 | ((UV)d2) << 8
608static SV * 718static SV *
609decode_str (dec_t *dec) 719decode_str (dec_t *dec)
610{ 720{
611 SV *sv = 0; 721 SV *sv = 0;
612 int utf8 = 0; 722 int utf8 = 0;
723 char *dec_cur = dec->cur;
613 724
614 do 725 do
615 { 726 {
616 char buf [SHORT_STRING_LEN + UTF8_MAXBYTES]; 727 char buf [SHORT_STRING_LEN + UTF8_MAXBYTES];
617 char *cur = buf; 728 char *cur = buf;
618 729
619 do 730 do
620 { 731 {
621 unsigned char ch = *(unsigned char *)dec->cur++; 732 unsigned char ch = *(unsigned char *)dec_cur++;
622 733
623 if (ch == '"') 734 if (expect_false (ch == '"'))
624 { 735 {
625 --dec->cur; 736 --dec_cur;
626 break; 737 break;
627 } 738 }
628 else if (ch == '\\') 739 else if (expect_false (ch == '\\'))
629 { 740 {
630 switch (*dec->cur) 741 switch (*dec_cur)
631 { 742 {
632 case '\\': 743 case '\\':
633 case '/': 744 case '/':
634 case '"': *cur++ = *dec->cur++; break; 745 case '"': *cur++ = *dec_cur++; break;
635 746
636 case 'b': ++dec->cur; *cur++ = '\010'; break; 747 case 'b': ++dec_cur; *cur++ = '\010'; break;
637 case 't': ++dec->cur; *cur++ = '\011'; break; 748 case 't': ++dec_cur; *cur++ = '\011'; break;
638 case 'n': ++dec->cur; *cur++ = '\012'; break; 749 case 'n': ++dec_cur; *cur++ = '\012'; break;
639 case 'f': ++dec->cur; *cur++ = '\014'; break; 750 case 'f': ++dec_cur; *cur++ = '\014'; break;
640 case 'r': ++dec->cur; *cur++ = '\015'; break; 751 case 'r': ++dec_cur; *cur++ = '\015'; break;
641 752
642 case 'u': 753 case 'u':
643 { 754 {
644 UV lo, hi; 755 UV lo, hi;
645 ++dec->cur; 756 ++dec_cur;
646 757
758 dec->cur = dec_cur;
647 hi = decode_4hex (dec); 759 hi = decode_4hex (dec);
760 dec_cur = dec->cur;
648 if (hi == (UV)-1) 761 if (hi == (UV)-1)
649 goto fail; 762 goto fail;
650 763
651 // possibly a surrogate pair 764 // possibly a surrogate pair
652 if (hi >= 0xd800) 765 if (hi >= 0xd800)
653 if (hi < 0xdc00) 766 if (hi < 0xdc00)
654 { 767 {
655 if (dec->cur [0] != '\\' || dec->cur [1] != 'u') 768 if (dec_cur [0] != '\\' || dec_cur [1] != 'u')
656 ERR ("missing low surrogate character in surrogate pair"); 769 ERR ("missing low surrogate character in surrogate pair");
657 770
658 dec->cur += 2; 771 dec_cur += 2;
659 772
773 dec->cur = dec_cur;
660 lo = decode_4hex (dec); 774 lo = decode_4hex (dec);
775 dec_cur = dec->cur;
661 if (lo == (UV)-1) 776 if (lo == (UV)-1)
662 goto fail; 777 goto fail;
663 778
664 if (lo < 0xdc00 || lo >= 0xe000) 779 if (lo < 0xdc00 || lo >= 0xe000)
665 ERR ("surrogate pair expected"); 780 ERR ("surrogate pair expected");
679 *cur++ = hi; 794 *cur++ = hi;
680 } 795 }
681 break; 796 break;
682 797
683 default: 798 default:
684 --dec->cur; 799 --dec_cur;
685 ERR ("illegal backslash escape sequence in string"); 800 ERR ("illegal backslash escape sequence in string");
686 } 801 }
687 } 802 }
688 else if (ch >= 0x20 && ch <= 0x7f) 803 else if (expect_true (ch >= 0x20 && ch <= 0x7f))
689 *cur++ = ch; 804 *cur++ = ch;
690 else if (ch >= 0x80) 805 else if (ch >= 0x80)
691 { 806 {
692 STRLEN clen; 807 STRLEN clen;
693 UV uch; 808 UV uch;
694 809
695 --dec->cur; 810 --dec_cur;
696 811
697 uch = decode_utf8 (dec->cur, dec->end - dec->cur, &clen); 812 uch = decode_utf8 (dec_cur, dec->end - dec_cur, &clen);
698 if (clen == (STRLEN)-1) 813 if (clen == (STRLEN)-1)
699 ERR ("malformed UTF-8 character in JSON string"); 814 ERR ("malformed UTF-8 character in JSON string");
700 815
701 do 816 do
702 *cur++ = *dec->cur++; 817 *cur++ = *dec_cur++;
703 while (--clen); 818 while (--clen);
704 819
705 utf8 = 1; 820 utf8 = 1;
706 } 821 }
707 else 822 else
708 { 823 {
709 --dec->cur; 824 --dec_cur;
710 825
711 if (!ch) 826 if (!ch)
712 ERR ("unexpected end of string while parsing JSON string"); 827 ERR ("unexpected end of string while parsing JSON string");
713 else 828 else
714 ERR ("invalid character encountered while parsing JSON string"); 829 ERR ("invalid character encountered while parsing JSON string");
727 } 842 }
728 else 843 else
729 sv = newSVpvn (buf, len); 844 sv = newSVpvn (buf, len);
730 } 845 }
731 } 846 }
732 while (*dec->cur != '"'); 847 while (*dec_cur != '"');
733 848
734 ++dec->cur; 849 ++dec_cur;
735 850
736 if (sv) 851 if (sv)
737 { 852 {
738 SvPOK_only (sv); 853 SvPOK_only (sv);
739 *SvEND (sv) = 0; 854 *SvEND (sv) = 0;
742 SvUTF8_on (sv); 857 SvUTF8_on (sv);
743 } 858 }
744 else 859 else
745 sv = newSVpvn ("", 0); 860 sv = newSVpvn ("", 0);
746 861
862 dec->cur = dec_cur;
747 return sv; 863 return sv;
748 864
749fail: 865fail:
866 dec->cur = dec_cur;
750 return 0; 867 return 0;
751} 868}
752 869
753static SV * 870static SV *
754decode_num (dec_t *dec) 871decode_num (dec_t *dec)
812 is_nv = 1; 929 is_nv = 1;
813 } 930 }
814 931
815 if (!is_nv) 932 if (!is_nv)
816 { 933 {
817 UV uv; 934 // special case the rather common 1..4-digit-int case, assumes 32 bit ints or so
818 int numtype = grok_number (start, dec->cur - start, &uv); 935 if (*start == '-')
819 if (numtype & IS_NUMBER_IN_UV) 936 switch (dec->cur - start)
820 if (numtype & IS_NUMBER_NEG)
821 { 937 {
822 if (uv < (UV)IV_MIN) 938 case 2: return newSViv (-( start [1] - '0' * 1));
823 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));
824 } 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 }
825 else 961 else
826 return newSVuv (uv); 962 return newSVuv (uv);
963
964 // here would likely be the place for bigint support
827 } 965 }
966 }
828 967
968 // if we ever support bigint or bigfloat, this is the place for bigfloat
829 return newSVnv (Atof (start)); 969 return newSVnv (Atof (start));
830 970
831fail: 971fail:
832 return 0; 972 return 0;
833} 973}
887 if (*dec->cur == '}') 1027 if (*dec->cur == '}')
888 ++dec->cur; 1028 ++dec->cur;
889 else 1029 else
890 for (;;) 1030 for (;;)
891 { 1031 {
892 SV *key, *value;
893
894 decode_ws (dec); EXPECT_CH ('"'); 1032 decode_ws (dec); EXPECT_CH ('"');
895 1033
896 key = decode_str (dec); 1034 // heuristic: assume that
897 if (!key) 1035 // a) decode_str + hv_store_ent are abysmally slow.
898 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
899 1043
900 decode_ws (dec); EXPECT_CH (':'); 1044 for (;;)
901
902 value = decode_sv (dec);
903 if (!value)
904 { 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);
905 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)
906 goto fail; 1079 goto fail;
1080
1081 hv_store (hv, key, len, value, 0);
1082
1083 break;
1084 }
1085
1086 ++p;
907 } 1087 }
908 1088 }
909 hv_store_ent (hv, key, value, 0);
910 SvREFCNT_dec (key);
911 1089
912 decode_ws (dec); 1090 decode_ws (dec);
913 1091
914 if (*dec->cur == '}') 1092 if (*dec->cur == '}')
915 { 1093 {
934 1112
935static SV * 1113static SV *
936decode_sv (dec_t *dec) 1114decode_sv (dec_t *dec)
937{ 1115{
938 decode_ws (dec); 1116 decode_ws (dec);
1117
1118 // the beauty of JSON: you need exactly one character lookahead
1119 // to parse anything.
939 switch (*dec->cur) 1120 switch (*dec->cur)
940 { 1121 {
941 case '"': ++dec->cur; return decode_str (dec); 1122 case '"': ++dec->cur; return decode_str (dec);
942 case '[': ++dec->cur; return decode_av (dec); 1123 case '[': ++dec->cur; return decode_av (dec);
943 case '{': ++dec->cur; return decode_hv (dec); 1124 case '{': ++dec->cur; return decode_hv (dec);
949 1130
950 case 't': 1131 case 't':
951 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1132 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
952 { 1133 {
953 dec->cur += 4; 1134 dec->cur += 4;
954 return newSViv (1); 1135 return SvREFCNT_inc (json_true);
955 } 1136 }
956 else 1137 else
957 ERR ("'true' expected"); 1138 ERR ("'true' expected");
958 1139
959 break; 1140 break;
960 1141
961 case 'f': 1142 case 'f':
962 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1143 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
963 { 1144 {
964 dec->cur += 5; 1145 dec->cur += 5;
965 return newSViv (0); 1146 return SvREFCNT_inc (json_false);
966 } 1147 }
967 else 1148 else
968 ERR ("'false' expected"); 1149 ERR ("'false' expected");
969 1150
970 break; 1151 break;
988fail: 1169fail:
989 return 0; 1170 return 0;
990} 1171}
991 1172
992static SV * 1173static SV *
993decode_json (SV *string, U32 flags, UV *offset_return) 1174decode_json (SV *string, struct json *json, UV *offset_return)
994{ 1175{
995 dec_t dec; 1176 dec_t dec;
996 UV offset; 1177 UV offset;
997 SV *sv; 1178 SV *sv;
998 1179
999 SvGETMAGIC (string); 1180 SvGETMAGIC (string);
1000 SvUPGRADE (string, SVt_PV); 1181 SvUPGRADE (string, SVt_PV);
1001 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
1002 if (flags & F_UTF8) 1187 if (json->flags & F_UTF8)
1003 sv_utf8_downgrade (string, 0); 1188 sv_utf8_downgrade (string, 0);
1004 else 1189 else
1005 sv_utf8_upgrade (string); 1190 sv_utf8_upgrade (string);
1006 1191
1007 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP 1192 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
1008 1193
1009 dec.flags = flags; 1194 dec.json = *json;
1010 dec.cur = SvPVX (string); 1195 dec.cur = SvPVX (string);
1011 dec.end = SvEND (string); 1196 dec.end = SvEND (string);
1012 dec.err = 0; 1197 dec.err = 0;
1013 dec.depth = 0; 1198 dec.depth = 0;
1014 dec.maxdepth = DEC_DEPTH (dec.flags); 1199 dec.maxdepth = DEC_DEPTH (dec.json.flags);
1015 1200
1016 *dec.end = 0; // this should basically be a nop, too, but make sure it's there 1201 *dec.end = 0; // this should basically be a nop, too, but make sure it's there
1017 sv = decode_sv (&dec); 1202 sv = decode_sv (&dec);
1018 1203
1019 if (!(offset_return || !sv)) 1204 if (!(offset_return || !sv))
1029 } 1214 }
1030 } 1215 }
1031 1216
1032 if (offset_return || !sv) 1217 if (offset_return || !sv)
1033 { 1218 {
1034 offset = dec.flags & F_UTF8 1219 offset = dec.json.flags & F_UTF8
1035 ? dec.cur - SvPVX (string) 1220 ? dec.cur - SvPVX (string)
1036 : utf8_distance (dec.cur, SvPVX (string)); 1221 : utf8_distance (dec.cur, SvPVX (string));
1037 1222
1038 if (offset_return) 1223 if (offset_return)
1039 *offset_return = offset; 1224 *offset_return = offset;
1058 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); 1243 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
1059 } 1244 }
1060 1245
1061 sv = sv_2mortal (sv); 1246 sv = sv_2mortal (sv);
1062 1247
1063 if (!(dec.flags & F_ALLOW_NONREF) && !SvROK (sv)) 1248 if (!(dec.json.flags & F_ALLOW_NONREF) && !SvROK (sv))
1064 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)");
1065 1250
1066 return sv; 1251 return sv;
1067} 1252}
1068 1253
1072MODULE = JSON::XS PACKAGE = JSON::XS 1257MODULE = JSON::XS PACKAGE = JSON::XS
1073 1258
1074BOOT: 1259BOOT:
1075{ 1260{
1076 int i; 1261 int i;
1077
1078 memset (decode_hexdigit, 0xff, 256);
1079 1262
1080 for (i = 0; i < 256; ++i) 1263 for (i = 0; i < 256; ++i)
1081 decode_hexdigit [i] = 1264 decode_hexdigit [i] =
1082 i >= '0' && i <= '9' ? i - '0' 1265 i >= '0' && i <= '9' ? i - '0'
1083 : i >= 'a' && i <= 'f' ? i - 'a' + 10 1266 : i >= 'a' && i <= 'f' ? i - 'a' + 10
1084 : i >= 'A' && i <= 'F' ? i - 'A' + 10 1267 : i >= 'A' && i <= 'F' ? i - 'A' + 10
1085 : -1; 1268 : -1;
1086 1269
1087 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);
1088} 1275}
1089 1276
1090PROTOTYPES: DISABLE 1277PROTOTYPES: DISABLE
1091 1278
1092SV *new (char *dummy) 1279SV *new (char *dummy)
1095 OUTPUT: 1282 OUTPUT:
1096 RETVAL 1283 RETVAL
1097 1284
1098SV *ascii (SV *self, int enable = 1) 1285SV *ascii (SV *self, int enable = 1)
1099 ALIAS: 1286 ALIAS:
1100 ascii = F_ASCII 1287 ascii = F_ASCII
1101 latin1 = F_LATIN1 1288 latin1 = F_LATIN1
1102 utf8 = F_UTF8 1289 utf8 = F_UTF8
1103 indent = F_INDENT 1290 indent = F_INDENT
1104 canonical = F_CANONICAL 1291 canonical = F_CANONICAL
1105 space_before = F_SPACE_BEFORE 1292 space_before = F_SPACE_BEFORE
1106 space_after = F_SPACE_AFTER 1293 space_after = F_SPACE_AFTER
1107 pretty = F_PRETTY 1294 pretty = F_PRETTY
1108 allow_nonref = F_ALLOW_NONREF 1295 allow_nonref = F_ALLOW_NONREF
1109 shrink = F_SHRINK 1296 shrink = F_SHRINK
1297 allow_blessed = F_ALLOW_BLESSED
1298 convert_blessed = F_CONV_BLESSED
1110 CODE: 1299 CODE:
1111{ 1300{
1112 UV *uv = SvJSON (self); 1301 UV *uv = SvJSON (self);
1113 if (enable) 1302 if (enable)
1114 *uv |= ix; 1303 *uv |= ix;
1136 RETVAL = newSVsv (self); 1325 RETVAL = newSVsv (self);
1137} 1326}
1138 OUTPUT: 1327 OUTPUT:
1139 RETVAL 1328 RETVAL
1140 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
1141void encode (SV *self, SV *scalar) 1349void encode (SV *self, SV *scalar)
1142 PPCODE: 1350 PPCODE:
1351{
1352 struct json json = { *SvJSON (self) };
1143 XPUSHs (encode_json (scalar, *SvJSON (self))); 1353 XPUSHs (encode_json (scalar, &json));
1354}
1144 1355
1145void decode (SV *self, SV *jsonstr) 1356void decode (SV *self, SV *jsonstr)
1146 PPCODE: 1357 PPCODE:
1358{
1359 struct json json = { *SvJSON (self) };
1147 XPUSHs (decode_json (jsonstr, *SvJSON (self), 0)); 1360 XPUSHs (decode_json (jsonstr, &json, 0));
1361}
1148 1362
1149void decode_prefix (SV *self, SV *jsonstr) 1363void decode_prefix (SV *self, SV *jsonstr)
1150 PPCODE: 1364 PPCODE:
1151{ 1365{
1152 UV offset; 1366 UV offset;
1367 struct json json = { *SvJSON (self) };
1153 EXTEND (SP, 2); 1368 EXTEND (SP, 2);
1154 PUSHs (decode_json (jsonstr, *SvJSON (self), &offset)); 1369 PUSHs (decode_json (jsonstr, &json, &offset));
1155 PUSHs (sv_2mortal (newSVuv (offset))); 1370 PUSHs (sv_2mortal (newSVuv (offset)));
1156} 1371}
1157 1372
1158PROTOTYPES: ENABLE 1373PROTOTYPES: ENABLE
1159 1374
1160void to_json (SV *scalar) 1375void to_json (SV *scalar)
1161 ALIAS:
1162 objToJson = 0
1163 PPCODE: 1376 PPCODE:
1377{
1378 struct json json = { F_DEFAULT | F_UTF8 };
1164 XPUSHs (encode_json (scalar, F_DEFAULT | F_UTF8)); 1379 XPUSHs (encode_json (scalar, &json));
1380}
1165 1381
1166void from_json (SV *jsonstr) 1382void from_json (SV *jsonstr)
1167 ALIAS:
1168 jsonToObj = 0
1169 PPCODE: 1383 PPCODE:
1384{
1385 struct json json = { F_DEFAULT | F_UTF8 };
1170 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8, 0)); 1386 XPUSHs (decode_json (jsonstr, &json, 0));
1387}
1171 1388

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines