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.27 by root, Mon Apr 9 05:09:57 2007 UTC vs.
Revision 1.45 by root, Mon Jun 25 06:57:42 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
21#define F_LATIN1 0x00000002UL
15#define F_UTF8 0x00000002UL 22#define F_UTF8 0x00000004UL
16#define F_INDENT 0x00000004UL 23#define F_INDENT 0x00000008UL
17#define F_CANONICAL 0x00000008UL 24#define F_CANONICAL 0x00000010UL
18#define F_SPACE_BEFORE 0x00000010UL 25#define F_SPACE_BEFORE 0x00000020UL
19#define F_SPACE_AFTER 0x00000020UL 26#define F_SPACE_AFTER 0x00000040UL
20#define F_ALLOW_NONREF 0x00000080UL 27#define F_ALLOW_NONREF 0x00000100UL
21#define F_SHRINK 0x00000100UL 28#define F_SHRINK 0x00000200UL
29#define F_ALLOW_BLESSED 0x00000400UL
30#define F_CONV_BLESSED 0x00000800UL // NYI
22#define F_MAXDEPTH 0xf8000000UL 31#define F_MAXDEPTH 0xf8000000UL
23#define S_MAXDEPTH 27 32#define S_MAXDEPTH 27
33#define F_MAXSIZE 0x01f00000UL
34#define S_MAXSIZE 20
24 35
25#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH)) 36#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH))
26 37#define DEC_SIZE(flags) (1UL << ((flags & F_MAXSIZE ) >> S_MAXSIZE ))
27// F_SELFCONVERT? <=> to_json/toJson
28// F_BLESSED? <=> { $__class__$ => }
29 38
30#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER 39#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER
31#define F_DEFAULT (9UL << S_MAXDEPTH) 40#define F_DEFAULT (9UL << S_MAXDEPTH)
32 41
33#define INIT_SIZE 32 // initial scalar size to be allocated 42#define INIT_SIZE 32 // initial scalar size to be allocated
34#define INDENT_STEP 3 // spaces per indentation level 43#define INDENT_STEP 3 // spaces per indentation level
35 44
36#define UTF8_MAX_LEN 11 // for perls UTF-X: max. number of octets per character
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;
43 63
44///////////////////////////////////////////////////////////////////////////// 64/////////////////////////////////////////////////////////////////////////////
45// utility functions 65// utility functions
46 66
47static UV * 67static UV *
70// decode an utf-8 character and return it, or (UV)-1 in 90// decode an utf-8 character and return it, or (UV)-1 in
71// case of an error. 91// case of an error.
72// we special-case "safe" characters from U+80 .. U+7FF, 92// we special-case "safe" characters from U+80 .. U+7FF,
73// but use the very good perl function to parse anything else. 93// but use the very good perl function to parse anything else.
74// note that we never call this function for a ascii codepoints 94// note that we never call this function for a ascii codepoints
75static UV 95inline UV
76decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen) 96decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
77{ 97{
78 if (s[0] > 0xdf || s[0] < 0xc2) 98 if (expect_false (s[0] > 0xdf || s[0] < 0xc2))
79 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY); 99 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY);
80 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf) 100 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf)
81 { 101 {
82 *clen = 2; 102 *clen = 2;
83 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f); 103 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
101 U32 flags; // F_* 121 U32 flags; // F_*
102 U32 indent; // indentation level 122 U32 indent; // indentation level
103 U32 maxdepth; // max. indentation/recursion level 123 U32 maxdepth; // max. indentation/recursion level
104} enc_t; 124} enc_t;
105 125
106static void 126inline void
107need (enc_t *enc, STRLEN len) 127need (enc_t *enc, STRLEN len)
108{ 128{
109 if (enc->cur + len >= enc->end) 129 if (expect_false (enc->cur + len >= enc->end))
110 { 130 {
111 STRLEN cur = enc->cur - SvPVX (enc->sv); 131 STRLEN cur = enc->cur - SvPVX (enc->sv);
112 SvGROW (enc->sv, cur + len + 1); 132 SvGROW (enc->sv, cur + len + 1);
113 enc->cur = SvPVX (enc->sv) + cur; 133 enc->cur = SvPVX (enc->sv) + cur;
114 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1; 134 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
115 } 135 }
116} 136}
117 137
118static void 138inline void
119encode_ch (enc_t *enc, char ch) 139encode_ch (enc_t *enc, char ch)
120{ 140{
121 need (enc, 1); 141 need (enc, 1);
122 *enc->cur++ = ch; 142 *enc->cur++ = ch;
123} 143}
131 151
132 while (str < end) 152 while (str < end)
133 { 153 {
134 unsigned char ch = *(unsigned char *)str; 154 unsigned char ch = *(unsigned char *)str;
135 155
136 if (ch >= 0x20 && ch < 0x80) // most common case 156 if (expect_true (ch >= 0x20 && ch < 0x80)) // most common case
137 { 157 {
138 if (ch == '"') // but with slow exceptions 158 if (expect_false (ch == '"')) // but with slow exceptions
139 { 159 {
140 need (enc, len += 1); 160 need (enc, len += 1);
141 *enc->cur++ = '\\'; 161 *enc->cur++ = '\\';
142 *enc->cur++ = '"'; 162 *enc->cur++ = '"';
143 } 163 }
144 else if (ch == '\\') 164 else if (expect_false (ch == '\\'))
145 { 165 {
146 need (enc, len += 1); 166 need (enc, len += 1);
147 *enc->cur++ = '\\'; 167 *enc->cur++ = '\\';
148 *enc->cur++ = '\\'; 168 *enc->cur++ = '\\';
149 } 169 }
167 STRLEN clen; 187 STRLEN clen;
168 UV uch; 188 UV uch;
169 189
170 if (is_utf8) 190 if (is_utf8)
171 { 191 {
172 //uch = utf8n_to_uvuni (str, end - str, &clen, UTF8_CHECK_ONLY);
173 uch = decode_utf8 (str, end - str, &clen); 192 uch = decode_utf8 (str, end - str, &clen);
174 if (clen == (STRLEN)-1) 193 if (clen == (STRLEN)-1)
175 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str); 194 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str);
176 } 195 }
177 else 196 else
181 } 200 }
182 201
183 if (uch > 0x10FFFFUL) 202 if (uch > 0x10FFFFUL)
184 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch); 203 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
185 204
186 if (uch < 0x80 || enc->flags & F_ASCII) 205 if (uch < 0x80 || enc->flags & F_ASCII || (enc->flags & F_LATIN1 && uch > 0xFF))
187 { 206 {
188 if (uch > 0xFFFFUL) 207 if (uch > 0xFFFFUL)
189 { 208 {
190 need (enc, len += 11); 209 need (enc, len += 11);
191 sprintf (enc->cur, "\\u%04x\\u%04x", 210 sprintf (enc->cur, "\\u%04x\\u%04x",
205 *enc->cur++ = hexdigit [(uch >> 0) & 15]; 224 *enc->cur++ = hexdigit [(uch >> 0) & 15];
206 } 225 }
207 226
208 str += clen; 227 str += clen;
209 } 228 }
229 else if (enc->flags & F_LATIN1)
230 {
231 *enc->cur++ = uch;
232 str += clen;
233 }
210 else if (is_utf8) 234 else if (is_utf8)
211 { 235 {
212 need (enc, len += clen); 236 need (enc, len += clen);
213 do 237 do
214 { 238 {
216 } 240 }
217 while (--clen); 241 while (--clen);
218 } 242 }
219 else 243 else
220 { 244 {
221 need (enc, len += UTF8_MAX_LEN - 1); // never more than 11 bytes needed 245 need (enc, len += UTF8_MAXBYTES - 1); // never more than 11 bytes needed
222 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); 246 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0);
223 ++str; 247 ++str;
224 } 248 }
225 } 249 }
226 } 250 }
228 252
229 --len; 253 --len;
230 } 254 }
231} 255}
232 256
233static void 257inline void
234encode_indent (enc_t *enc) 258encode_indent (enc_t *enc)
235{ 259{
236 if (enc->flags & F_INDENT) 260 if (enc->flags & F_INDENT)
237 { 261 {
238 int spaces = enc->indent * INDENT_STEP; 262 int spaces = enc->indent * INDENT_STEP;
241 memset (enc->cur, ' ', spaces); 265 memset (enc->cur, ' ', spaces);
242 enc->cur += spaces; 266 enc->cur += spaces;
243 } 267 }
244} 268}
245 269
246static void 270inline void
247encode_space (enc_t *enc) 271encode_space (enc_t *enc)
248{ 272{
249 need (enc, 1); 273 need (enc, 1);
250 encode_ch (enc, ' '); 274 encode_ch (enc, ' ');
251} 275}
252 276
253static void 277inline void
254encode_nl (enc_t *enc) 278encode_nl (enc_t *enc)
255{ 279{
256 if (enc->flags & F_INDENT) 280 if (enc->flags & F_INDENT)
257 { 281 {
258 need (enc, 1); 282 need (enc, 1);
259 encode_ch (enc, '\n'); 283 encode_ch (enc, '\n');
260 } 284 }
261} 285}
262 286
263static void 287inline void
264encode_comma (enc_t *enc) 288encode_comma (enc_t *enc)
265{ 289{
266 encode_ch (enc, ','); 290 encode_ch (enc, ',');
267 291
268 if (enc->flags & F_INDENT) 292 if (enc->flags & F_INDENT)
367 // actually, this is mostly due to the stupid so-called 391 // actually, this is mostly due to the stupid so-called
368 // security workaround added somewhere in 5.8.x. 392 // security workaround added somewhere in 5.8.x.
369 // that randomises hash orderings 393 // that randomises hash orderings
370 if (enc->flags & F_CANONICAL) 394 if (enc->flags & F_CANONICAL)
371 { 395 {
372 HE *he, *hes [count]; // if your compiler dies here, you need to enable C99 mode
373 int fast = 1; 396 int fast = 1;
397 HE *he;
398#if defined(__BORLANDC__) || defined(_MSC_VER)
399 HE **hes = _alloca (count * sizeof (HE));
400#else
401 HE *hes [count]; // if your compiler dies here, you need to enable C99 mode
402#endif
374 403
375 i = 0; 404 i = 0;
376 while ((he = hv_iternext (hv))) 405 while ((he = hv_iternext (hv)))
377 { 406 {
378 hes [i++] = he; 407 hes [i++] = he;
442 svtype svt; 471 svtype svt;
443 472
444 SvGETMAGIC (sv); 473 SvGETMAGIC (sv);
445 svt = SvTYPE (sv); 474 svt = SvTYPE (sv);
446 475
476 if (expect_false (SvOBJECT (sv)))
477 {
478 if (SvSTASH (sv) == json_boolean_stash)
479 {
480 if (SvIV (sv) == 0)
481 encode_str (enc, "false", 5, 0);
482 else
483 encode_str (enc, "true", 4, 0);
484 }
485 else
486 {
487#if 0
488 if (0 && sv_derived_from (rv, "JSON::Literal"))
489 {
490 // not yet
491 }
492#endif
493 if (enc->flags & F_CONV_BLESSED)
494 {
495 // we re-bless the reference to get overload and other niceties right
496 GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 1);
497
498 if (to_json)
499 {
500 dSP;
501 ENTER;
502 SAVETMPS;
503 PUSHMARK (SP);
504 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv)));
505
506 // calling with G_SCALAR ensures that we always get a 1 reutrn value
507 // check anyways.
508 PUTBACK;
509 assert (1 == call_sv ((SV *)GvCV (to_json), G_SCALAR));
510 SPAGAIN;
511
512 encode_sv (enc, POPs);
513
514 FREETMPS;
515 LEAVE;
516 }
517 else if (enc->flags & F_ALLOW_BLESSED)
518 encode_str (enc, "null", 4, 0);
519 else
520 croak ("encountered object '%s', but neither allow_blessed enabled nor TO_JSON method available on it",
521 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
522 }
523 else if (enc->flags & F_ALLOW_BLESSED)
524 encode_str (enc, "null", 4, 0);
525 else
526 croak ("encountered object '%s', but neither allow_blessed nor convert_blessed settings are enabled",
527 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
528 }
529 }
447 if (svt == SVt_PVHV) 530 else if (svt == SVt_PVHV)
448 encode_hv (enc, (HV *)sv); 531 encode_hv (enc, (HV *)sv);
449 else if (svt == SVt_PVAV) 532 else if (svt == SVt_PVAV)
450 encode_av (enc, (AV *)sv); 533 encode_av (enc, (AV *)sv);
451 else if (svt < SVt_PVAV) 534 else if (svt < SVt_PVAV)
452 { 535 {
476 encode_str (enc, str, len, SvUTF8 (sv)); 559 encode_str (enc, str, len, SvUTF8 (sv));
477 encode_ch (enc, '"'); 560 encode_ch (enc, '"');
478 } 561 }
479 else if (SvNOKp (sv)) 562 else if (SvNOKp (sv))
480 { 563 {
564 // trust that perl will do the right thing w.r.t. JSON syntax.
481 need (enc, NV_DIG + 32); 565 need (enc, NV_DIG + 32);
482 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur); 566 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
483 enc->cur += strlen (enc->cur); 567 enc->cur += strlen (enc->cur);
484 } 568 }
485 else if (SvIOKp (sv)) 569 else if (SvIOKp (sv))
486 { 570 {
487 need (enc, 64); 571 // we assume we can always read an IV as a UV
572 if (SvUV (sv) & ~(UV)0x7fff)
573 {
574 // large integer, use the (rather slow) snprintf way.
575 need (enc, sizeof (UV) * 3);
488 enc->cur += 576 enc->cur +=
489 SvIsUV(sv) 577 SvIsUV(sv)
490 ? snprintf (enc->cur, 64, "%"UVuf, (UV)SvUVX (sv)) 578 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv))
491 : snprintf (enc->cur, 64, "%"IVdf, (IV)SvIVX (sv)); 579 : snprintf (enc->cur, sizeof (UV) * 3, "%"IVdf, (IV)SvIVX (sv));
580 }
581 else
582 {
583 // optimise the "small number case"
584 // code will likely be branchless and use only a single multiplication
585 I32 i = SvIV (sv);
586 U32 u;
587 char digit, nz = 0;
588
589 need (enc, 6);
590
591 *enc->cur = '-'; enc->cur += i < 0 ? 1 : 0;
592 u = i < 0 ? -i : i;
593
594 // convert to 4.28 fixed-point representation
595 u = u * ((0xfffffff + 10000) / 10000); // 10**5, 5 fractional digits
596
597 // now output digit by digit, each time masking out the integer part
598 // and multiplying by 5 while moving the decimal point one to the right,
599 // resulting in a net multiplication by 10.
600 // we always write the digit to memory but conditionally increment
601 // the pointer, to ease the usage of conditional move instructions.
602 digit = u >> 28; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0xfffffff) * 5;
603 digit = u >> 27; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x7ffffff) * 5;
604 digit = u >> 26; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x3ffffff) * 5;
605 digit = u >> 25; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x1ffffff) * 5;
606 digit = u >> 24; *enc->cur = digit + '0'; enc->cur += 1; // correctly generate '0'
607 }
492 } 608 }
493 else if (SvROK (sv)) 609 else if (SvROK (sv))
494 encode_rv (enc, SvRV (sv)); 610 encode_rv (enc, SvRV (sv));
495 else if (!SvOK (sv)) 611 else if (!SvOK (sv))
496 encode_str (enc, "null", 4, 0); 612 encode_str (enc, "null", 4, 0);
515 enc.maxdepth = DEC_DEPTH (flags); 631 enc.maxdepth = DEC_DEPTH (flags);
516 632
517 SvPOK_only (enc.sv); 633 SvPOK_only (enc.sv);
518 encode_sv (&enc, scalar); 634 encode_sv (&enc, scalar);
519 635
520 if (!(flags & (F_ASCII | F_UTF8)))
521 SvUTF8_on (enc.sv);
522
523 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); 636 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
524 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings 637 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings
638
639 if (!(flags & (F_ASCII | F_LATIN1 | F_UTF8)))
640 SvUTF8_on (enc.sv);
525 641
526 if (enc.flags & F_SHRINK) 642 if (enc.flags & F_SHRINK)
527 shrink (enc.sv); 643 shrink (enc.sv);
528 644
529 return enc.sv; 645 return enc.sv;
541 U32 flags; // F_* 657 U32 flags; // F_*
542 U32 depth; // recursion depth 658 U32 depth; // recursion depth
543 U32 maxdepth; // recursion depth limit 659 U32 maxdepth; // recursion depth limit
544} dec_t; 660} dec_t;
545 661
546static void 662inline void
547decode_ws (dec_t *dec) 663decode_ws (dec_t *dec)
548{ 664{
549 for (;;) 665 for (;;)
550 { 666 {
551 char ch = *dec->cur; 667 char ch = *dec->cur;
577decode_4hex (dec_t *dec) 693decode_4hex (dec_t *dec)
578{ 694{
579 signed char d1, d2, d3, d4; 695 signed char d1, d2, d3, d4;
580 unsigned char *cur = (unsigned char *)dec->cur; 696 unsigned char *cur = (unsigned char *)dec->cur;
581 697
582 d1 = decode_hexdigit [cur [0]]; if (d1 < 0) ERR ("four hexadecimal digits expected"); 698 d1 = decode_hexdigit [cur [0]]; if (expect_false (d1 < 0)) ERR ("exactly four hexadecimal digits expected");
583 d2 = decode_hexdigit [cur [1]]; if (d2 < 0) ERR ("four hexadecimal digits expected"); 699 d2 = decode_hexdigit [cur [1]]; if (expect_false (d2 < 0)) ERR ("exactly four hexadecimal digits expected");
584 d3 = decode_hexdigit [cur [2]]; if (d3 < 0) ERR ("four hexadecimal digits expected"); 700 d3 = decode_hexdigit [cur [2]]; if (expect_false (d3 < 0)) ERR ("exactly four hexadecimal digits expected");
585 d4 = decode_hexdigit [cur [3]]; if (d4 < 0) ERR ("four hexadecimal digits expected"); 701 d4 = decode_hexdigit [cur [3]]; if (expect_false (d4 < 0)) ERR ("exactly four hexadecimal digits expected");
586 702
587 dec->cur += 4; 703 dec->cur += 4;
588 704
589 return ((UV)d1) << 12 705 return ((UV)d1) << 12
590 | ((UV)d2) << 8 706 | ((UV)d2) << 8
598static SV * 714static SV *
599decode_str (dec_t *dec) 715decode_str (dec_t *dec)
600{ 716{
601 SV *sv = 0; 717 SV *sv = 0;
602 int utf8 = 0; 718 int utf8 = 0;
719 char *dec_cur = dec->cur;
603 720
604 do 721 do
605 { 722 {
606 char buf [SHORT_STRING_LEN + UTF8_MAX_LEN]; 723 char buf [SHORT_STRING_LEN + UTF8_MAXBYTES];
607 char *cur = buf; 724 char *cur = buf;
608 725
609 do 726 do
610 { 727 {
611 unsigned char ch = *(unsigned char *)dec->cur++; 728 unsigned char ch = *(unsigned char *)dec_cur++;
612 729
613 if (ch == '"') 730 if (expect_false (ch == '"'))
614 { 731 {
615 --dec->cur; 732 --dec_cur;
616 break; 733 break;
617 } 734 }
618 else if (ch == '\\') 735 else if (expect_false (ch == '\\'))
619 { 736 {
620 switch (*dec->cur) 737 switch (*dec_cur)
621 { 738 {
622 case '\\': 739 case '\\':
623 case '/': 740 case '/':
624 case '"': *cur++ = *dec->cur++; break; 741 case '"': *cur++ = *dec_cur++; break;
625 742
626 case 'b': ++dec->cur; *cur++ = '\010'; break; 743 case 'b': ++dec_cur; *cur++ = '\010'; break;
627 case 't': ++dec->cur; *cur++ = '\011'; break; 744 case 't': ++dec_cur; *cur++ = '\011'; break;
628 case 'n': ++dec->cur; *cur++ = '\012'; break; 745 case 'n': ++dec_cur; *cur++ = '\012'; break;
629 case 'f': ++dec->cur; *cur++ = '\014'; break; 746 case 'f': ++dec_cur; *cur++ = '\014'; break;
630 case 'r': ++dec->cur; *cur++ = '\015'; break; 747 case 'r': ++dec_cur; *cur++ = '\015'; break;
631 748
632 case 'u': 749 case 'u':
633 { 750 {
634 UV lo, hi; 751 UV lo, hi;
635 ++dec->cur; 752 ++dec_cur;
636 753
754 dec->cur = dec_cur;
637 hi = decode_4hex (dec); 755 hi = decode_4hex (dec);
756 dec_cur = dec->cur;
638 if (hi == (UV)-1) 757 if (hi == (UV)-1)
639 goto fail; 758 goto fail;
640 759
641 // possibly a surrogate pair 760 // possibly a surrogate pair
642 if (hi >= 0xd800) 761 if (hi >= 0xd800)
643 if (hi < 0xdc00) 762 if (hi < 0xdc00)
644 { 763 {
645 if (dec->cur [0] != '\\' || dec->cur [1] != 'u') 764 if (dec_cur [0] != '\\' || dec_cur [1] != 'u')
646 ERR ("missing low surrogate character in surrogate pair"); 765 ERR ("missing low surrogate character in surrogate pair");
647 766
648 dec->cur += 2; 767 dec_cur += 2;
649 768
769 dec->cur = dec_cur;
650 lo = decode_4hex (dec); 770 lo = decode_4hex (dec);
771 dec_cur = dec->cur;
651 if (lo == (UV)-1) 772 if (lo == (UV)-1)
652 goto fail; 773 goto fail;
653 774
654 if (lo < 0xdc00 || lo >= 0xe000) 775 if (lo < 0xdc00 || lo >= 0xe000)
655 ERR ("surrogate pair expected"); 776 ERR ("surrogate pair expected");
669 *cur++ = hi; 790 *cur++ = hi;
670 } 791 }
671 break; 792 break;
672 793
673 default: 794 default:
674 --dec->cur; 795 --dec_cur;
675 ERR ("illegal backslash escape sequence in string"); 796 ERR ("illegal backslash escape sequence in string");
676 } 797 }
677 } 798 }
678 else if (ch >= 0x20 && ch <= 0x7f) 799 else if (expect_true (ch >= 0x20 && ch <= 0x7f))
679 *cur++ = ch; 800 *cur++ = ch;
680 else if (ch >= 0x80) 801 else if (ch >= 0x80)
681 { 802 {
682 STRLEN clen; 803 STRLEN clen;
683 UV uch; 804 UV uch;
684 805
685 --dec->cur; 806 --dec_cur;
686 807
687 uch = decode_utf8 (dec->cur, dec->end - dec->cur, &clen); 808 uch = decode_utf8 (dec_cur, dec->end - dec_cur, &clen);
688 if (clen == (STRLEN)-1) 809 if (clen == (STRLEN)-1)
689 ERR ("malformed UTF-8 character in JSON string"); 810 ERR ("malformed UTF-8 character in JSON string");
690 811
691 do 812 do
692 *cur++ = *dec->cur++; 813 *cur++ = *dec_cur++;
693 while (--clen); 814 while (--clen);
694 815
695 utf8 = 1; 816 utf8 = 1;
696 } 817 }
697 else 818 else
698 { 819 {
699 --dec->cur; 820 --dec_cur;
700 821
701 if (!ch) 822 if (!ch)
702 ERR ("unexpected end of string while parsing JSON string"); 823 ERR ("unexpected end of string while parsing JSON string");
703 else 824 else
704 ERR ("invalid character encountered while parsing JSON string"); 825 ERR ("invalid character encountered while parsing JSON string");
717 } 838 }
718 else 839 else
719 sv = newSVpvn (buf, len); 840 sv = newSVpvn (buf, len);
720 } 841 }
721 } 842 }
722 while (*dec->cur != '"'); 843 while (*dec_cur != '"');
723 844
724 ++dec->cur; 845 ++dec_cur;
725 846
726 if (sv) 847 if (sv)
727 { 848 {
728 SvPOK_only (sv); 849 SvPOK_only (sv);
729 *SvEND (sv) = 0; 850 *SvEND (sv) = 0;
732 SvUTF8_on (sv); 853 SvUTF8_on (sv);
733 } 854 }
734 else 855 else
735 sv = newSVpvn ("", 0); 856 sv = newSVpvn ("", 0);
736 857
858 dec->cur = dec_cur;
737 return sv; 859 return sv;
738 860
739fail: 861fail:
862 dec->cur = dec_cur;
740 return 0; 863 return 0;
741} 864}
742 865
743static SV * 866static SV *
744decode_num (dec_t *dec) 867decode_num (dec_t *dec)
802 is_nv = 1; 925 is_nv = 1;
803 } 926 }
804 927
805 if (!is_nv) 928 if (!is_nv)
806 { 929 {
807 UV uv; 930 // special case the rather common 1..4-digit-int case, assumes 32 bit ints or so
808 int numtype = grok_number (start, dec->cur - start, &uv); 931 if (*start == '-')
809 if (numtype & IS_NUMBER_IN_UV) 932 switch (dec->cur - start)
810 if (numtype & IS_NUMBER_NEG)
811 { 933 {
812 if (uv < (UV)IV_MIN) 934 case 2: return newSViv (-( start [1] - '0' * 1));
813 return newSViv (-(IV)uv); 935 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11));
936 case 4: return newSViv (-( start [1] * 100 + start [2] * 10 + start [3] - '0' * 111));
937 case 5: return newSViv (-(start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111));
814 } 938 }
939 else
940 switch (dec->cur - start)
941 {
942 case 1: return newSViv ( start [0] - '0' * 1);
943 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11);
944 case 3: return newSViv ( start [0] * 100 + start [1] * 10 + start [2] - '0' * 111);
945 case 4: return newSViv ( start [0] * 1000 + start [1] * 100 + start [2] * 10 + start [3] - '0' * 1111);
946 }
947
948 {
949 UV uv;
950 int numtype = grok_number (start, dec->cur - start, &uv);
951 if (numtype & IS_NUMBER_IN_UV)
952 if (numtype & IS_NUMBER_NEG)
953 {
954 if (uv < (UV)IV_MIN)
955 return newSViv (-(IV)uv);
956 }
815 else 957 else
816 return newSVuv (uv); 958 return newSVuv (uv);
959
960 // here would likely be the place for bigint support
817 } 961 }
962 }
818 963
964 // if we ever support bigint or bigfloat, this is the place for bigfloat
819 return newSVnv (Atof (start)); 965 return newSVnv (Atof (start));
820 966
821fail: 967fail:
822 return 0; 968 return 0;
823} 969}
924 1070
925static SV * 1071static SV *
926decode_sv (dec_t *dec) 1072decode_sv (dec_t *dec)
927{ 1073{
928 decode_ws (dec); 1074 decode_ws (dec);
1075
1076 // the beauty of JSON: you need exactly one character lookahead
1077 // to parse anything.
929 switch (*dec->cur) 1078 switch (*dec->cur)
930 { 1079 {
931 case '"': ++dec->cur; return decode_str (dec); 1080 case '"': ++dec->cur; return decode_str (dec);
932 case '[': ++dec->cur; return decode_av (dec); 1081 case '[': ++dec->cur; return decode_av (dec);
933 case '{': ++dec->cur; return decode_hv (dec); 1082 case '{': ++dec->cur; return decode_hv (dec);
939 1088
940 case 't': 1089 case 't':
941 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1090 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
942 { 1091 {
943 dec->cur += 4; 1092 dec->cur += 4;
944 return newSViv (1); 1093 return SvREFCNT_inc (json_true);
945 } 1094 }
946 else 1095 else
947 ERR ("'true' expected"); 1096 ERR ("'true' expected");
948 1097
949 break; 1098 break;
950 1099
951 case 'f': 1100 case 'f':
952 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1101 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
953 { 1102 {
954 dec->cur += 5; 1103 dec->cur += 5;
955 return newSViv (0); 1104 return SvREFCNT_inc (json_false);
956 } 1105 }
957 else 1106 else
958 ERR ("'false' expected"); 1107 ERR ("'false' expected");
959 1108
960 break; 1109 break;
978fail: 1127fail:
979 return 0; 1128 return 0;
980} 1129}
981 1130
982static SV * 1131static SV *
983decode_json (SV *string, U32 flags) 1132decode_json (SV *string, U32 flags, UV *offset_return)
984{ 1133{
985 dec_t dec; 1134 dec_t dec;
1135 UV offset;
986 SV *sv; 1136 SV *sv;
987 1137
1138 SvGETMAGIC (string);
988 SvUPGRADE (string, SVt_PV); 1139 SvUPGRADE (string, SVt_PV);
1140
1141 if (flags & F_MAXSIZE && SvCUR (string) > DEC_SIZE (flags))
1142 croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu",
1143 (unsigned long)SvCUR (string), (unsigned long)DEC_SIZE (flags));
989 1144
990 if (flags & F_UTF8) 1145 if (flags & F_UTF8)
991 sv_utf8_downgrade (string, 0); 1146 sv_utf8_downgrade (string, 0);
992 else 1147 else
993 sv_utf8_upgrade (string); 1148 sv_utf8_upgrade (string);
999 dec.end = SvEND (string); 1154 dec.end = SvEND (string);
1000 dec.err = 0; 1155 dec.err = 0;
1001 dec.depth = 0; 1156 dec.depth = 0;
1002 dec.maxdepth = DEC_DEPTH (dec.flags); 1157 dec.maxdepth = DEC_DEPTH (dec.flags);
1003 1158
1004 *dec.end = 0; // this should basically be a nop, too, but make sure its there 1159 *dec.end = 0; // this should basically be a nop, too, but make sure it's there
1005 sv = decode_sv (&dec); 1160 sv = decode_sv (&dec);
1006 1161
1162 if (!(offset_return || !sv))
1163 {
1164 // check for trailing garbage
1165 decode_ws (&dec);
1166
1167 if (*dec.cur)
1168 {
1169 dec.err = "garbage after JSON object";
1170 SvREFCNT_dec (sv);
1171 sv = 0;
1172 }
1173 }
1174
1175 if (offset_return || !sv)
1176 {
1177 offset = dec.flags & F_UTF8
1178 ? dec.cur - SvPVX (string)
1179 : utf8_distance (dec.cur, SvPVX (string));
1180
1181 if (offset_return)
1182 *offset_return = offset;
1183 }
1184
1007 if (!sv) 1185 if (!sv)
1008 { 1186 {
1009 IV offset = dec.flags & F_UTF8
1010 ? dec.cur - SvPVX (string)
1011 : utf8_distance (dec.cur, SvPVX (string));
1012 SV *uni = sv_newmortal (); 1187 SV *uni = sv_newmortal ();
1013 1188
1014 // horrible hack to silence warning inside pv_uni_display 1189 // horrible hack to silence warning inside pv_uni_display
1015 COP cop = *PL_curcop; 1190 COP cop = *PL_curcop;
1016 cop.cop_warnings = pWARN_NONE; 1191 cop.cop_warnings = pWARN_NONE;
1041 1216
1042BOOT: 1217BOOT:
1043{ 1218{
1044 int i; 1219 int i;
1045 1220
1046 memset (decode_hexdigit, 0xff, 256);
1047
1048 for (i = 0; i < 256; ++i) 1221 for (i = 0; i < 256; ++i)
1049 decode_hexdigit [i] = 1222 decode_hexdigit [i] =
1050 i >= '0' && i <= '9' ? i - '0' 1223 i >= '0' && i <= '9' ? i - '0'
1051 : i >= 'a' && i <= 'f' ? i - 'a' + 10 1224 : i >= 'a' && i <= 'f' ? i - 'a' + 10
1052 : i >= 'A' && i <= 'F' ? i - 'A' + 10 1225 : i >= 'A' && i <= 'F' ? i - 'A' + 10
1053 : -1; 1226 : -1;
1054 1227
1055 json_stash = gv_stashpv ("JSON::XS", 1); 1228 json_stash = gv_stashpv ("JSON::XS" , 1);
1229 json_boolean_stash = gv_stashpv ("JSON::XS::Boolean", 1);
1230
1231 json_true = get_sv ("JSON::XS::true" , 1); SvREADONLY_on (json_true );
1232 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1056} 1233}
1057 1234
1058PROTOTYPES: DISABLE 1235PROTOTYPES: DISABLE
1059 1236
1060SV *new (char *dummy) 1237SV *new (char *dummy)
1063 OUTPUT: 1240 OUTPUT:
1064 RETVAL 1241 RETVAL
1065 1242
1066SV *ascii (SV *self, int enable = 1) 1243SV *ascii (SV *self, int enable = 1)
1067 ALIAS: 1244 ALIAS:
1068 ascii = F_ASCII 1245 ascii = F_ASCII
1246 latin1 = F_LATIN1
1069 utf8 = F_UTF8 1247 utf8 = F_UTF8
1070 indent = F_INDENT 1248 indent = F_INDENT
1071 canonical = F_CANONICAL 1249 canonical = F_CANONICAL
1072 space_before = F_SPACE_BEFORE 1250 space_before = F_SPACE_BEFORE
1073 space_after = F_SPACE_AFTER 1251 space_after = F_SPACE_AFTER
1074 pretty = F_PRETTY 1252 pretty = F_PRETTY
1075 allow_nonref = F_ALLOW_NONREF 1253 allow_nonref = F_ALLOW_NONREF
1076 shrink = F_SHRINK 1254 shrink = F_SHRINK
1255 allow_blessed = F_ALLOW_BLESSED
1256 convert_blessed = F_CONV_BLESSED
1077 CODE: 1257 CODE:
1078{ 1258{
1079 UV *uv = SvJSON (self); 1259 UV *uv = SvJSON (self);
1080 if (enable) 1260 if (enable)
1081 *uv |= ix; 1261 *uv |= ix;
1103 RETVAL = newSVsv (self); 1283 RETVAL = newSVsv (self);
1104} 1284}
1105 OUTPUT: 1285 OUTPUT:
1106 RETVAL 1286 RETVAL
1107 1287
1288SV *max_size (SV *self, UV max_size = 0)
1289 CODE:
1290{
1291 UV *uv = SvJSON (self);
1292 UV log2 = 0;
1293
1294 if (max_size > 0x80000000UL) max_size = 0x80000000UL;
1295 if (max_size == 1) max_size = 2;
1296
1297 while ((1UL << log2) < max_size)
1298 ++log2;
1299
1300 *uv = *uv & ~F_MAXSIZE | (log2 << S_MAXSIZE);
1301
1302 RETVAL = newSVsv (self);
1303}
1304 OUTPUT:
1305 RETVAL
1306
1108void encode (SV *self, SV *scalar) 1307void encode (SV *self, SV *scalar)
1109 PPCODE: 1308 PPCODE:
1110 XPUSHs (encode_json (scalar, *SvJSON (self))); 1309 XPUSHs (encode_json (scalar, *SvJSON (self)));
1111 1310
1112void decode (SV *self, SV *jsonstr) 1311void decode (SV *self, SV *jsonstr)
1113 PPCODE: 1312 PPCODE:
1114 XPUSHs (decode_json (jsonstr, *SvJSON (self))); 1313 XPUSHs (decode_json (jsonstr, *SvJSON (self), 0));
1314
1315void decode_prefix (SV *self, SV *jsonstr)
1316 PPCODE:
1317{
1318 UV offset;
1319 EXTEND (SP, 2);
1320 PUSHs (decode_json (jsonstr, *SvJSON (self), &offset));
1321 PUSHs (sv_2mortal (newSVuv (offset)));
1322}
1115 1323
1116PROTOTYPES: ENABLE 1324PROTOTYPES: ENABLE
1117 1325
1118void to_json (SV *scalar) 1326void to_json (SV *scalar)
1119 ALIAS: 1327 ALIAS:
1123 1331
1124void from_json (SV *jsonstr) 1332void from_json (SV *jsonstr)
1125 ALIAS: 1333 ALIAS:
1126 jsonToObj = 0 1334 jsonToObj = 0
1127 PPCODE: 1335 PPCODE:
1128 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8)); 1336 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8, 0));
1129 1337

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines