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.21 by root, Thu Mar 29 02:45:49 2007 UTC vs.
Revision 1.46 by root, Mon Jun 25 22:11:39 2007 UTC

3#include "XSUB.h" 3#include "XSUB.h"
4 4
5#include "assert.h" 5#include "assert.h"
6#include "string.h" 6#include "string.h"
7#include "stdlib.h" 7#include "stdlib.h"
8#include "stdio.h"
8 9
10#if defined(__BORLANDC__) || defined(_MSC_VER)
11# define snprintf _snprintf // C compilers have this in stdio.h
12#endif
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
9#define F_ASCII 0x00000001UL 20#define F_ASCII 0x00000001UL
21#define F_LATIN1 0x00000002UL
10#define F_UTF8 0x00000002UL 22#define F_UTF8 0x00000004UL
11#define F_INDENT 0x00000004UL 23#define F_INDENT 0x00000008UL
12#define F_CANONICAL 0x00000008UL 24#define F_CANONICAL 0x00000010UL
13#define F_SPACE_BEFORE 0x00000010UL 25#define F_SPACE_BEFORE 0x00000020UL
14#define F_SPACE_AFTER 0x00000020UL 26#define F_SPACE_AFTER 0x00000040UL
15#define F_ALLOW_NONREF 0x00000080UL 27#define F_ALLOW_NONREF 0x00000100UL
16#define F_SHRINK 0x00000100UL 28#define F_SHRINK 0x00000200UL
29#define F_ALLOW_BLESSED 0x00000400UL
30#define F_CONV_BLESSED 0x00000800UL // NYI
17#define F_MAXDEPTH 0xf8000000UL 31#define F_MAXDEPTH 0xf8000000UL
18#define S_MAXDEPTH 27 32#define S_MAXDEPTH 27
33#define F_MAXSIZE 0x01f00000UL
34#define S_MAXSIZE 20
19 35
20#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH)) 36#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH))
21 37#define DEC_SIZE(flags) (1UL << ((flags & F_MAXSIZE ) >> S_MAXSIZE ))
22// F_SELFCONVERT? <=> to_json/toJson
23// F_BLESSED? <=> { $__class__$ => }
24 38
25#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER 39#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER
26#define F_DEFAULT (12UL << S_MAXDEPTH) 40#define F_DEFAULT (9UL << S_MAXDEPTH)
27 41
28#define INIT_SIZE 32 // initial scalar size to be allocated 42#define INIT_SIZE 32 // initial scalar size to be allocated
29#define INDENT_STEP 3 // spaces per indentation level 43#define INDENT_STEP 3 // spaces per indentation level
30 44
31#define UTF8_MAX_LEN 11 // for perls UTF-X: max. number of octets per character
32#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
33 46
34#define SB do { 47#define SB do {
35#define SE } while (0) 48#define SE } while (0)
36 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
37static HV *json_stash; // JSON::XS:: 61static HV *json_stash, *json_boolean_stash; // JSON::XS::
62static SV *json_true, *json_false;
38 63
39///////////////////////////////////////////////////////////////////////////// 64/////////////////////////////////////////////////////////////////////////////
40// utility functions 65// utility functions
41 66
42static UV * 67static UV *
65// 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
66// case of an error. 91// case of an error.
67// we special-case "safe" characters from U+80 .. U+7FF, 92// we special-case "safe" characters from U+80 .. U+7FF,
68// but use the very good perl function to parse anything else. 93// but use the very good perl function to parse anything else.
69// note that we never call this function for a ascii codepoints 94// note that we never call this function for a ascii codepoints
70static UV 95inline UV
71decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen) 96decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
72{ 97{
73 if (s[0] > 0xdf || s[0] < 0xc2) 98 if (expect_false (s[0] > 0xdf || s[0] < 0xc2))
74 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY); 99 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY);
75 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf) 100 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf)
76 { 101 {
77 *clen = 2; 102 *clen = 2;
78 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f); 103 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
79 } 104 }
80 else 105 else
106 {
107 *clen = (STRLEN)-1;
81 return (UV)-1; 108 return (UV)-1;
109 }
82} 110}
83 111
84///////////////////////////////////////////////////////////////////////////// 112/////////////////////////////////////////////////////////////////////////////
85// encoder 113// encoder
86 114
93 U32 flags; // F_* 121 U32 flags; // F_*
94 U32 indent; // indentation level 122 U32 indent; // indentation level
95 U32 maxdepth; // max. indentation/recursion level 123 U32 maxdepth; // max. indentation/recursion level
96} enc_t; 124} enc_t;
97 125
98static void 126inline void
99need (enc_t *enc, STRLEN len) 127need (enc_t *enc, STRLEN len)
100{ 128{
101 if (enc->cur + len >= enc->end) 129 if (expect_false (enc->cur + len >= enc->end))
102 { 130 {
103 STRLEN cur = enc->cur - SvPVX (enc->sv); 131 STRLEN cur = enc->cur - SvPVX (enc->sv);
104 SvGROW (enc->sv, cur + len + 1); 132 SvGROW (enc->sv, cur + len + 1);
105 enc->cur = SvPVX (enc->sv) + cur; 133 enc->cur = SvPVX (enc->sv) + cur;
106 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv); 134 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
107 } 135 }
108} 136}
109 137
110static void 138inline void
111encode_ch (enc_t *enc, char ch) 139encode_ch (enc_t *enc, char ch)
112{ 140{
113 need (enc, 1); 141 need (enc, 1);
114 *enc->cur++ = ch; 142 *enc->cur++ = ch;
115} 143}
123 151
124 while (str < end) 152 while (str < end)
125 { 153 {
126 unsigned char ch = *(unsigned char *)str; 154 unsigned char ch = *(unsigned char *)str;
127 155
128 if (ch >= 0x20 && ch < 0x80) // most common case 156 if (expect_true (ch >= 0x20 && ch < 0x80)) // most common case
129 { 157 {
130 if (ch == '"') // but with slow exceptions 158 if (expect_false (ch == '"')) // but with slow exceptions
131 { 159 {
132 need (enc, len += 1); 160 need (enc, len += 1);
133 *enc->cur++ = '\\'; 161 *enc->cur++ = '\\';
134 *enc->cur++ = '"'; 162 *enc->cur++ = '"';
135 } 163 }
136 else if (ch == '\\') 164 else if (expect_false (ch == '\\'))
137 { 165 {
138 need (enc, len += 1); 166 need (enc, len += 1);
139 *enc->cur++ = '\\'; 167 *enc->cur++ = '\\';
140 *enc->cur++ = '\\'; 168 *enc->cur++ = '\\';
141 } 169 }
159 STRLEN clen; 187 STRLEN clen;
160 UV uch; 188 UV uch;
161 189
162 if (is_utf8) 190 if (is_utf8)
163 { 191 {
164 //uch = utf8n_to_uvuni (str, end - str, &clen, UTF8_CHECK_ONLY);
165 uch = decode_utf8 (str, end - str, &clen); 192 uch = decode_utf8 (str, end - str, &clen);
166 if (clen == (STRLEN)-1) 193 if (clen == (STRLEN)-1)
167 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);
168 } 195 }
169 else 196 else
173 } 200 }
174 201
175 if (uch > 0x10FFFFUL) 202 if (uch > 0x10FFFFUL)
176 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);
177 204
178 if (uch < 0x80 || enc->flags & F_ASCII) 205 if (uch < 0x80 || enc->flags & F_ASCII || (enc->flags & F_LATIN1 && uch > 0xFF))
179 { 206 {
180 if (uch > 0xFFFFUL) 207 if (uch > 0xFFFFUL)
181 { 208 {
182 need (enc, len += 11); 209 need (enc, len += 11);
183 sprintf (enc->cur, "\\u%04x\\u%04x", 210 sprintf (enc->cur, "\\u%04x\\u%04x",
197 *enc->cur++ = hexdigit [(uch >> 0) & 15]; 224 *enc->cur++ = hexdigit [(uch >> 0) & 15];
198 } 225 }
199 226
200 str += clen; 227 str += clen;
201 } 228 }
229 else if (enc->flags & F_LATIN1)
230 {
231 *enc->cur++ = uch;
232 str += clen;
233 }
202 else if (is_utf8) 234 else if (is_utf8)
203 { 235 {
204 need (enc, len += clen); 236 need (enc, len += clen);
205 do 237 do
206 { 238 {
208 } 240 }
209 while (--clen); 241 while (--clen);
210 } 242 }
211 else 243 else
212 { 244 {
213 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
214 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); 246 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0);
215 ++str; 247 ++str;
216 } 248 }
217 } 249 }
218 } 250 }
220 252
221 --len; 253 --len;
222 } 254 }
223} 255}
224 256
225static void 257inline void
226encode_indent (enc_t *enc) 258encode_indent (enc_t *enc)
227{ 259{
228 if (enc->flags & F_INDENT) 260 if (enc->flags & F_INDENT)
229 { 261 {
230 int spaces = enc->indent * INDENT_STEP; 262 int spaces = enc->indent * INDENT_STEP;
233 memset (enc->cur, ' ', spaces); 265 memset (enc->cur, ' ', spaces);
234 enc->cur += spaces; 266 enc->cur += spaces;
235 } 267 }
236} 268}
237 269
238static void 270inline void
239encode_space (enc_t *enc) 271encode_space (enc_t *enc)
240{ 272{
241 need (enc, 1); 273 need (enc, 1);
242 encode_ch (enc, ' '); 274 encode_ch (enc, ' ');
243} 275}
244 276
245static void 277inline void
246encode_nl (enc_t *enc) 278encode_nl (enc_t *enc)
247{ 279{
248 if (enc->flags & F_INDENT) 280 if (enc->flags & F_INDENT)
249 { 281 {
250 need (enc, 1); 282 need (enc, 1);
251 encode_ch (enc, '\n'); 283 encode_ch (enc, '\n');
252 } 284 }
253} 285}
254 286
255static void 287inline void
256encode_comma (enc_t *enc) 288encode_comma (enc_t *enc)
257{ 289{
258 encode_ch (enc, ','); 290 encode_ch (enc, ',');
259 291
260 if (enc->flags & F_INDENT) 292 if (enc->flags & F_INDENT)
359 // actually, this is mostly due to the stupid so-called 391 // actually, this is mostly due to the stupid so-called
360 // security workaround added somewhere in 5.8.x. 392 // security workaround added somewhere in 5.8.x.
361 // that randomises hash orderings 393 // that randomises hash orderings
362 if (enc->flags & F_CANONICAL) 394 if (enc->flags & F_CANONICAL)
363 { 395 {
364 HE *he, *hes [count]; // if your compiler dies here, you need to enable C99 mode
365 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
366 403
367 i = 0; 404 i = 0;
368 while ((he = hv_iternext (hv))) 405 while ((he = hv_iternext (hv)))
369 { 406 {
370 hes [i++] = he; 407 hes [i++] = he;
405 442
406 encode_nl (enc); 443 encode_nl (enc);
407 } 444 }
408 else 445 else
409 { 446 {
410 SV *sv;
411 HE *he = hv_iternext (hv); 447 HE *he = hv_iternext (hv);
412 448
413 for (;;) 449 for (;;)
414 { 450 {
415 encode_indent (enc); 451 encode_indent (enc);
430 466
431// encode objects, arrays and special \0=false and \1=true values. 467// encode objects, arrays and special \0=false and \1=true values.
432static void 468static void
433encode_rv (enc_t *enc, SV *sv) 469encode_rv (enc_t *enc, SV *sv)
434{ 470{
471 svtype svt;
472
435 SvGETMAGIC (sv); 473 SvGETMAGIC (sv);
436
437 svtype svt = SvTYPE (sv); 474 svt = SvTYPE (sv);
438 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 }
439 if (svt == SVt_PVHV) 530 else if (svt == SVt_PVHV)
440 encode_hv (enc, (HV *)sv); 531 encode_hv (enc, (HV *)sv);
441 else if (svt == SVt_PVAV) 532 else if (svt == SVt_PVAV)
442 encode_av (enc, (AV *)sv); 533 encode_av (enc, (AV *)sv);
443 else if (svt < SVt_PVAV) 534 else if (svt < SVt_PVAV)
444 { 535 {
468 encode_str (enc, str, len, SvUTF8 (sv)); 559 encode_str (enc, str, len, SvUTF8 (sv));
469 encode_ch (enc, '"'); 560 encode_ch (enc, '"');
470 } 561 }
471 else if (SvNOKp (sv)) 562 else if (SvNOKp (sv))
472 { 563 {
564 // trust that perl will do the right thing w.r.t. JSON syntax.
473 need (enc, NV_DIG + 32); 565 need (enc, NV_DIG + 32);
474 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur); 566 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
475 enc->cur += strlen (enc->cur); 567 enc->cur += strlen (enc->cur);
476 } 568 }
477 else if (SvIOKp (sv)) 569 else if (SvIOKp (sv))
478 { 570 {
479 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);
480 enc->cur += 576 enc->cur +=
481 SvIsUV(sv) 577 SvIsUV(sv)
482 ? snprintf (enc->cur, 64, "%"UVuf, (UV)SvUVX (sv)) 578 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv))
483 : 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 }
484 } 608 }
485 else if (SvROK (sv)) 609 else if (SvROK (sv))
486 encode_rv (enc, SvRV (sv)); 610 encode_rv (enc, SvRV (sv));
487 else if (!SvOK (sv)) 611 else if (!SvOK (sv))
488 encode_str (enc, "null", 4, 0); 612 encode_str (enc, "null", 4, 0);
492} 616}
493 617
494static SV * 618static SV *
495encode_json (SV *scalar, U32 flags) 619encode_json (SV *scalar, U32 flags)
496{ 620{
621 enc_t enc;
622
497 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar)) 623 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar))
498 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)"); 624 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)");
499 625
500 enc_t enc;
501 enc.flags = flags; 626 enc.flags = flags;
502 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 627 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
503 enc.cur = SvPVX (enc.sv); 628 enc.cur = SvPVX (enc.sv);
504 enc.end = SvEND (enc.sv); 629 enc.end = SvEND (enc.sv);
505 enc.indent = 0; 630 enc.indent = 0;
506 enc.maxdepth = DEC_DEPTH (flags); 631 enc.maxdepth = DEC_DEPTH (flags);
507 632
508 SvPOK_only (enc.sv); 633 SvPOK_only (enc.sv);
509 encode_sv (&enc, scalar); 634 encode_sv (&enc, scalar);
510 635
636 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
637 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings
638
511 if (!(flags & (F_ASCII | F_UTF8))) 639 if (!(flags & (F_ASCII | F_LATIN1 | F_UTF8)))
512 SvUTF8_on (enc.sv); 640 SvUTF8_on (enc.sv);
513
514 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
515 641
516 if (enc.flags & F_SHRINK) 642 if (enc.flags & F_SHRINK)
517 shrink (enc.sv); 643 shrink (enc.sv);
518 644
519 return enc.sv; 645 return enc.sv;
531 U32 flags; // F_* 657 U32 flags; // F_*
532 U32 depth; // recursion depth 658 U32 depth; // recursion depth
533 U32 maxdepth; // recursion depth limit 659 U32 maxdepth; // recursion depth limit
534} dec_t; 660} dec_t;
535 661
536static void 662inline void
537decode_ws (dec_t *dec) 663decode_ws (dec_t *dec)
538{ 664{
539 for (;;) 665 for (;;)
540 { 666 {
541 char ch = *dec->cur; 667 char ch = *dec->cur;
567decode_4hex (dec_t *dec) 693decode_4hex (dec_t *dec)
568{ 694{
569 signed char d1, d2, d3, d4; 695 signed char d1, d2, d3, d4;
570 unsigned char *cur = (unsigned char *)dec->cur; 696 unsigned char *cur = (unsigned char *)dec->cur;
571 697
572 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");
573 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");
574 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");
575 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");
576 702
577 dec->cur += 4; 703 dec->cur += 4;
578 704
579 return ((UV)d1) << 12 705 return ((UV)d1) << 12
580 | ((UV)d2) << 8 706 | ((UV)d2) << 8
588static SV * 714static SV *
589decode_str (dec_t *dec) 715decode_str (dec_t *dec)
590{ 716{
591 SV *sv = 0; 717 SV *sv = 0;
592 int utf8 = 0; 718 int utf8 = 0;
719 char *dec_cur = dec->cur;
593 720
594 do 721 do
595 { 722 {
596 char buf [SHORT_STRING_LEN + UTF8_MAX_LEN]; 723 char buf [SHORT_STRING_LEN + UTF8_MAXBYTES];
597 char *cur = buf; 724 char *cur = buf;
598 725
599 do 726 do
600 { 727 {
601 unsigned char ch = *(unsigned char *)dec->cur++; 728 unsigned char ch = *(unsigned char *)dec_cur++;
602 729
603 if (ch == '"') 730 if (expect_false (ch == '"'))
604 { 731 {
605 --dec->cur; 732 --dec_cur;
606 break; 733 break;
607 } 734 }
608 else if (ch == '\\') 735 else if (expect_false (ch == '\\'))
609 { 736 {
610 switch (*dec->cur) 737 switch (*dec_cur)
611 { 738 {
612 case '\\': 739 case '\\':
613 case '/': 740 case '/':
614 case '"': *cur++ = *dec->cur++; break; 741 case '"': *cur++ = *dec_cur++; break;
615 742
616 case 'b': ++dec->cur; *cur++ = '\010'; break; 743 case 'b': ++dec_cur; *cur++ = '\010'; break;
617 case 't': ++dec->cur; *cur++ = '\011'; break; 744 case 't': ++dec_cur; *cur++ = '\011'; break;
618 case 'n': ++dec->cur; *cur++ = '\012'; break; 745 case 'n': ++dec_cur; *cur++ = '\012'; break;
619 case 'f': ++dec->cur; *cur++ = '\014'; break; 746 case 'f': ++dec_cur; *cur++ = '\014'; break;
620 case 'r': ++dec->cur; *cur++ = '\015'; break; 747 case 'r': ++dec_cur; *cur++ = '\015'; break;
621 748
622 case 'u': 749 case 'u':
623 { 750 {
624 UV lo, hi; 751 UV lo, hi;
625 ++dec->cur; 752 ++dec_cur;
626 753
754 dec->cur = dec_cur;
627 hi = decode_4hex (dec); 755 hi = decode_4hex (dec);
756 dec_cur = dec->cur;
628 if (hi == (UV)-1) 757 if (hi == (UV)-1)
629 goto fail; 758 goto fail;
630 759
631 // possibly a surrogate pair 760 // possibly a surrogate pair
632 if (hi >= 0xd800) 761 if (hi >= 0xd800)
633 if (hi < 0xdc00) 762 if (hi < 0xdc00)
634 { 763 {
635 if (dec->cur [0] != '\\' || dec->cur [1] != 'u') 764 if (dec_cur [0] != '\\' || dec_cur [1] != 'u')
636 ERR ("missing low surrogate character in surrogate pair"); 765 ERR ("missing low surrogate character in surrogate pair");
637 766
638 dec->cur += 2; 767 dec_cur += 2;
639 768
769 dec->cur = dec_cur;
640 lo = decode_4hex (dec); 770 lo = decode_4hex (dec);
771 dec_cur = dec->cur;
641 if (lo == (UV)-1) 772 if (lo == (UV)-1)
642 goto fail; 773 goto fail;
643 774
644 if (lo < 0xdc00 || lo >= 0xe000) 775 if (lo < 0xdc00 || lo >= 0xe000)
645 ERR ("surrogate pair expected"); 776 ERR ("surrogate pair expected");
659 *cur++ = hi; 790 *cur++ = hi;
660 } 791 }
661 break; 792 break;
662 793
663 default: 794 default:
664 --dec->cur; 795 --dec_cur;
665 ERR ("illegal backslash escape sequence in string"); 796 ERR ("illegal backslash escape sequence in string");
666 } 797 }
667 } 798 }
668 else if (ch >= 0x20 && ch <= 0x7f) 799 else if (expect_true (ch >= 0x20 && ch <= 0x7f))
669 *cur++ = ch; 800 *cur++ = ch;
670 else if (ch >= 0x80) 801 else if (ch >= 0x80)
671 { 802 {
672 --dec->cur;
673
674 STRLEN clen; 803 STRLEN clen;
804 UV uch;
805
806 --dec_cur;
807
675 UV uch = decode_utf8 (dec->cur, dec->end - dec->cur, &clen); 808 uch = decode_utf8 (dec_cur, dec->end - dec_cur, &clen);
676 if (clen == (STRLEN)-1) 809 if (clen == (STRLEN)-1)
677 ERR ("malformed UTF-8 character in JSON string"); 810 ERR ("malformed UTF-8 character in JSON string");
678 811
679 do 812 do
680 {
681 *cur++ = *dec->cur++; 813 *cur++ = *dec_cur++;
682 }
683 while (--clen); 814 while (--clen);
684 815
685 utf8 = 1; 816 utf8 = 1;
686 } 817 }
687 else if (!ch)
688 ERR ("unexpected end of string while parsing json string");
689 else 818 else
819 {
820 --dec_cur;
821
822 if (!ch)
823 ERR ("unexpected end of string while parsing JSON string");
824 else
690 ERR ("invalid character encountered"); 825 ERR ("invalid character encountered while parsing JSON string");
691 826 }
692 } 827 }
693 while (cur < buf + SHORT_STRING_LEN); 828 while (cur < buf + SHORT_STRING_LEN);
694 829
830 {
695 STRLEN len = cur - buf; 831 STRLEN len = cur - buf;
696 832
697 if (sv) 833 if (sv)
698 { 834 {
699 SvGROW (sv, SvCUR (sv) + len + 1); 835 SvGROW (sv, SvCUR (sv) + len + 1);
700 memcpy (SvPVX (sv) + SvCUR (sv), buf, len); 836 memcpy (SvPVX (sv) + SvCUR (sv), buf, len);
701 SvCUR_set (sv, SvCUR (sv) + len); 837 SvCUR_set (sv, SvCUR (sv) + len);
702 } 838 }
703 else 839 else
704 sv = newSVpvn (buf, len); 840 sv = newSVpvn (buf, len);
705 } 841 }
842 }
706 while (*dec->cur != '"'); 843 while (*dec_cur != '"');
707 844
708 ++dec->cur; 845 ++dec_cur;
709 846
710 if (sv) 847 if (sv)
711 { 848 {
712 SvPOK_only (sv); 849 SvPOK_only (sv);
713 *SvEND (sv) = 0; 850 *SvEND (sv) = 0;
716 SvUTF8_on (sv); 853 SvUTF8_on (sv);
717 } 854 }
718 else 855 else
719 sv = newSVpvn ("", 0); 856 sv = newSVpvn ("", 0);
720 857
858 dec->cur = dec_cur;
721 return sv; 859 return sv;
722 860
723fail: 861fail:
862 dec->cur = dec_cur;
724 return 0; 863 return 0;
725} 864}
726 865
727static SV * 866static SV *
728decode_num (dec_t *dec) 867decode_num (dec_t *dec)
786 is_nv = 1; 925 is_nv = 1;
787 } 926 }
788 927
789 if (!is_nv) 928 if (!is_nv)
790 { 929 {
791 UV uv; 930 // special case the rather common 1..4-digit-int case, assumes 32 bit ints or so
792 int numtype = grok_number (start, dec->cur - start, &uv); 931 if (*start == '-')
793 if (numtype & IS_NUMBER_IN_UV) 932 switch (dec->cur - start)
794 if (numtype & IS_NUMBER_NEG)
795 { 933 {
796 if (uv < (UV)IV_MIN) 934 case 2: return newSViv (-( start [1] - '0' * 1));
797 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));
798 } 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 }
799 else 957 else
800 return newSVuv (uv); 958 return newSVuv (uv);
959
960 // here would likely be the place for bigint support
801 } 961 }
962 }
802 963
964 // if we ever support bigint or bigfloat, this is the place for bigfloat
803 return newSVnv (Atof (start)); 965 return newSVnv (Atof (start));
804 966
805fail: 967fail:
806 return 0; 968 return 0;
807} 969}
861 if (*dec->cur == '}') 1023 if (*dec->cur == '}')
862 ++dec->cur; 1024 ++dec->cur;
863 else 1025 else
864 for (;;) 1026 for (;;)
865 { 1027 {
866 SV *key, *value;
867
868 decode_ws (dec); EXPECT_CH ('"'); 1028 decode_ws (dec); EXPECT_CH ('"');
869 1029
870 key = decode_str (dec); 1030 // heuristic: assume that
871 if (!key) 1031 // a) decode_str + hv_store_ent are abysmally slow
872 goto fail; 1032 // b) most hash keys are short, simple ascii text
1033 // so try to "fast-match" such strings to avoid
1034 // the overhead of hv_store_ent.
1035 {
1036 SV *value;
1037 char *p = dec->cur;
1038 char *e = p + 24; // only try up to 24 bytes
873 1039
874 decode_ws (dec); EXPECT_CH (':'); 1040 for (;;)
875
876 value = decode_sv (dec);
877 if (!value)
878 { 1041 {
1042 if (p == e || *p < 0x20 || *p >= 0x80 || *p == '\\')
1043 {
1044 // slow path, back up and use decode_str
1045 SV *key = decode_str (dec);
1046 if (!key)
1047 goto fail;
1048
1049 decode_ws (dec); EXPECT_CH (':');
1050
1051 value = decode_sv (dec);
1052 if (!value)
1053 {
1054 SvREFCNT_dec (key);
1055 goto fail;
1056 }
1057
1058 hv_store_ent (hv, key, value, 0);
879 SvREFCNT_dec (key); 1059 SvREFCNT_dec (key);
1060
1061 break;
1062 }
1063 else if (*p == '"')
1064 {
1065 // fast path, got a simple key
1066 char *key = dec->cur;
1067 int len = p - key;
1068 dec->cur = p + 1;
1069
1070 decode_ws (dec); EXPECT_CH (':');
1071
1072 value = decode_sv (dec);
1073 if (!value)
880 goto fail; 1074 goto fail;
1075
1076 hv_store (hv, key, len, value, 0);
1077
1078 break;
1079 }
1080
1081 ++p;
881 } 1082 }
882 1083 }
883 hv_store_ent (hv, key, value, 0);
884 SvREFCNT_dec (key);
885 1084
886 decode_ws (dec); 1085 decode_ws (dec);
887 1086
888 if (*dec->cur == '}') 1087 if (*dec->cur == '}')
889 { 1088 {
908 1107
909static SV * 1108static SV *
910decode_sv (dec_t *dec) 1109decode_sv (dec_t *dec)
911{ 1110{
912 decode_ws (dec); 1111 decode_ws (dec);
1112
1113 // the beauty of JSON: you need exactly one character lookahead
1114 // to parse anything.
913 switch (*dec->cur) 1115 switch (*dec->cur)
914 { 1116 {
915 case '"': ++dec->cur; return decode_str (dec); 1117 case '"': ++dec->cur; return decode_str (dec);
916 case '[': ++dec->cur; return decode_av (dec); 1118 case '[': ++dec->cur; return decode_av (dec);
917 case '{': ++dec->cur; return decode_hv (dec); 1119 case '{': ++dec->cur; return decode_hv (dec);
923 1125
924 case 't': 1126 case 't':
925 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1127 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
926 { 1128 {
927 dec->cur += 4; 1129 dec->cur += 4;
928 return newSViv (1); 1130 return SvREFCNT_inc (json_true);
929 } 1131 }
930 else 1132 else
931 ERR ("'true' expected"); 1133 ERR ("'true' expected");
932 1134
933 break; 1135 break;
934 1136
935 case 'f': 1137 case 'f':
936 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1138 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
937 { 1139 {
938 dec->cur += 5; 1140 dec->cur += 5;
939 return newSViv (0); 1141 return SvREFCNT_inc (json_false);
940 } 1142 }
941 else 1143 else
942 ERR ("'false' expected"); 1144 ERR ("'false' expected");
943 1145
944 break; 1146 break;
953 ERR ("'null' expected"); 1155 ERR ("'null' expected");
954 1156
955 break; 1157 break;
956 1158
957 default: 1159 default:
958 ERR ("malformed json string, neither array, object, number, string or atom"); 1160 ERR ("malformed JSON string, neither array, object, number, string or atom");
959 break; 1161 break;
960 } 1162 }
961 1163
962fail: 1164fail:
963 return 0; 1165 return 0;
964} 1166}
965 1167
966static SV * 1168static SV *
967decode_json (SV *string, U32 flags) 1169decode_json (SV *string, U32 flags, UV *offset_return)
968{ 1170{
1171 dec_t dec;
1172 UV offset;
969 SV *sv; 1173 SV *sv;
1174
1175 SvGETMAGIC (string);
1176 SvUPGRADE (string, SVt_PV);
1177
1178 if (flags & F_MAXSIZE && SvCUR (string) > DEC_SIZE (flags))
1179 croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu",
1180 (unsigned long)SvCUR (string), (unsigned long)DEC_SIZE (flags));
970 1181
971 if (flags & F_UTF8) 1182 if (flags & F_UTF8)
972 sv_utf8_downgrade (string, 0); 1183 sv_utf8_downgrade (string, 0);
973 else 1184 else
974 sv_utf8_upgrade (string); 1185 sv_utf8_upgrade (string);
975 1186
976 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP 1187 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
977 1188
978 dec_t dec;
979 dec.flags = flags; 1189 dec.flags = flags;
980 dec.cur = SvPVX (string); 1190 dec.cur = SvPVX (string);
981 dec.end = SvEND (string); 1191 dec.end = SvEND (string);
982 dec.err = 0; 1192 dec.err = 0;
983 dec.depth = 0; 1193 dec.depth = 0;
984 dec.maxdepth = DEC_DEPTH (dec.flags); 1194 dec.maxdepth = DEC_DEPTH (dec.flags);
985 1195
986 *dec.end = 0; // this should basically be a nop, too, but make sure its there 1196 *dec.end = 0; // this should basically be a nop, too, but make sure it's there
987 sv = decode_sv (&dec); 1197 sv = decode_sv (&dec);
988 1198
1199 if (!(offset_return || !sv))
1200 {
1201 // check for trailing garbage
1202 decode_ws (&dec);
1203
1204 if (*dec.cur)
1205 {
1206 dec.err = "garbage after JSON object";
1207 SvREFCNT_dec (sv);
1208 sv = 0;
1209 }
1210 }
1211
1212 if (offset_return || !sv)
1213 {
1214 offset = dec.flags & F_UTF8
1215 ? dec.cur - SvPVX (string)
1216 : utf8_distance (dec.cur, SvPVX (string));
1217
1218 if (offset_return)
1219 *offset_return = offset;
1220 }
1221
989 if (!sv) 1222 if (!sv)
990 { 1223 {
991 IV offset = dec.flags & F_UTF8
992 ? dec.cur - SvPVX (string)
993 : utf8_distance (dec.cur, SvPVX (string));
994 SV *uni = sv_newmortal (); 1224 SV *uni = sv_newmortal ();
995 1225
996 // horrible hack to silence warning inside pv_uni_display 1226 // horrible hack to silence warning inside pv_uni_display
997 COP cop = *PL_curcop; 1227 COP cop = *PL_curcop;
998 cop.cop_warnings = pWARN_NONE; 1228 cop.cop_warnings = pWARN_NONE;
1000 SAVEVPTR (PL_curcop); 1230 SAVEVPTR (PL_curcop);
1001 PL_curcop = &cop; 1231 PL_curcop = &cop;
1002 pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ); 1232 pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ);
1003 LEAVE; 1233 LEAVE;
1004 1234
1005 croak ("%s, at character offset %d (%s)", 1235 croak ("%s, at character offset %d [\"%s\"]",
1006 dec.err, 1236 dec.err,
1007 (int)offset, 1237 (int)offset,
1008 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); 1238 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
1009 } 1239 }
1010 1240
1022MODULE = JSON::XS PACKAGE = JSON::XS 1252MODULE = JSON::XS PACKAGE = JSON::XS
1023 1253
1024BOOT: 1254BOOT:
1025{ 1255{
1026 int i; 1256 int i;
1027
1028 memset (decode_hexdigit, 0xff, 256);
1029 1257
1030 for (i = 0; i < 256; ++i) 1258 for (i = 0; i < 256; ++i)
1031 decode_hexdigit [i] = 1259 decode_hexdigit [i] =
1032 i >= '0' && i <= '9' ? i - '0' 1260 i >= '0' && i <= '9' ? i - '0'
1033 : i >= 'a' && i <= 'f' ? i - 'a' + 10 1261 : i >= 'a' && i <= 'f' ? i - 'a' + 10
1034 : i >= 'A' && i <= 'F' ? i - 'A' + 10 1262 : i >= 'A' && i <= 'F' ? i - 'A' + 10
1035 : -1; 1263 : -1;
1036 1264
1037 json_stash = gv_stashpv ("JSON::XS", 1); 1265 json_stash = gv_stashpv ("JSON::XS" , 1);
1266 json_boolean_stash = gv_stashpv ("JSON::XS::Boolean", 1);
1267
1268 json_true = get_sv ("JSON::XS::true" , 1); SvREADONLY_on (json_true );
1269 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1038} 1270}
1039 1271
1040PROTOTYPES: DISABLE 1272PROTOTYPES: DISABLE
1041 1273
1042SV *new (char *dummy) 1274SV *new (char *dummy)
1045 OUTPUT: 1277 OUTPUT:
1046 RETVAL 1278 RETVAL
1047 1279
1048SV *ascii (SV *self, int enable = 1) 1280SV *ascii (SV *self, int enable = 1)
1049 ALIAS: 1281 ALIAS:
1050 ascii = F_ASCII 1282 ascii = F_ASCII
1283 latin1 = F_LATIN1
1051 utf8 = F_UTF8 1284 utf8 = F_UTF8
1052 indent = F_INDENT 1285 indent = F_INDENT
1053 canonical = F_CANONICAL 1286 canonical = F_CANONICAL
1054 space_before = F_SPACE_BEFORE 1287 space_before = F_SPACE_BEFORE
1055 space_after = F_SPACE_AFTER 1288 space_after = F_SPACE_AFTER
1056 pretty = F_PRETTY 1289 pretty = F_PRETTY
1057 allow_nonref = F_ALLOW_NONREF 1290 allow_nonref = F_ALLOW_NONREF
1058 shrink = F_SHRINK 1291 shrink = F_SHRINK
1292 allow_blessed = F_ALLOW_BLESSED
1293 convert_blessed = F_CONV_BLESSED
1059 CODE: 1294 CODE:
1060{ 1295{
1061 UV *uv = SvJSON (self); 1296 UV *uv = SvJSON (self);
1062 if (enable) 1297 if (enable)
1063 *uv |= ix; 1298 *uv |= ix;
1067 RETVAL = newSVsv (self); 1302 RETVAL = newSVsv (self);
1068} 1303}
1069 OUTPUT: 1304 OUTPUT:
1070 RETVAL 1305 RETVAL
1071 1306
1072SV *max_depth (SV *self, int max_depth = 0x80000000UL) 1307SV *max_depth (SV *self, UV max_depth = 0x80000000UL)
1073 CODE: 1308 CODE:
1074{ 1309{
1075 UV *uv = SvJSON (self); 1310 UV *uv = SvJSON (self);
1076 UV log2 = 0; 1311 UV log2 = 0;
1077 1312
1079 1314
1080 while ((1UL << log2) < max_depth) 1315 while ((1UL << log2) < max_depth)
1081 ++log2; 1316 ++log2;
1082 1317
1083 *uv = *uv & ~F_MAXDEPTH | (log2 << S_MAXDEPTH); 1318 *uv = *uv & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1319
1320 RETVAL = newSVsv (self);
1321}
1322 OUTPUT:
1323 RETVAL
1324
1325SV *max_size (SV *self, UV max_size = 0)
1326 CODE:
1327{
1328 UV *uv = SvJSON (self);
1329 UV log2 = 0;
1330
1331 if (max_size > 0x80000000UL) max_size = 0x80000000UL;
1332 if (max_size == 1) max_size = 2;
1333
1334 while ((1UL << log2) < max_size)
1335 ++log2;
1336
1337 *uv = *uv & ~F_MAXSIZE | (log2 << S_MAXSIZE);
1084 1338
1085 RETVAL = newSVsv (self); 1339 RETVAL = newSVsv (self);
1086} 1340}
1087 OUTPUT: 1341 OUTPUT:
1088 RETVAL 1342 RETVAL
1091 PPCODE: 1345 PPCODE:
1092 XPUSHs (encode_json (scalar, *SvJSON (self))); 1346 XPUSHs (encode_json (scalar, *SvJSON (self)));
1093 1347
1094void decode (SV *self, SV *jsonstr) 1348void decode (SV *self, SV *jsonstr)
1095 PPCODE: 1349 PPCODE:
1096 XPUSHs (decode_json (jsonstr, *SvJSON (self))); 1350 XPUSHs (decode_json (jsonstr, *SvJSON (self), 0));
1351
1352void decode_prefix (SV *self, SV *jsonstr)
1353 PPCODE:
1354{
1355 UV offset;
1356 EXTEND (SP, 2);
1357 PUSHs (decode_json (jsonstr, *SvJSON (self), &offset));
1358 PUSHs (sv_2mortal (newSVuv (offset)));
1359}
1097 1360
1098PROTOTYPES: ENABLE 1361PROTOTYPES: ENABLE
1099 1362
1100void to_json (SV *scalar) 1363void to_json (SV *scalar)
1101 ALIAS: 1364 ALIAS:
1105 1368
1106void from_json (SV *jsonstr) 1369void from_json (SV *jsonstr)
1107 ALIAS: 1370 ALIAS:
1108 jsonToObj = 0 1371 jsonToObj = 0
1109 PPCODE: 1372 PPCODE:
1110 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8)); 1373 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8, 0));
1111 1374

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines