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.22 by root, Sat Mar 31 14:20:06 2007 UTC vs.
Revision 1.43 by root, Sat Jun 23 23:49:29 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"
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
8 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
17#define F_MAXDEPTH 0xf8000000UL 29#define F_MAXDEPTH 0xf8000000UL
18#define S_MAXDEPTH 27 30#define S_MAXDEPTH 27
19 31
20#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH)) 32#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH))
21 33
22// F_SELFCONVERT? <=> to_json/toJson 34// F_SELFCONVERT? <=> to_json/toJson
23// F_BLESSED? <=> { $__class__$ => } 35// F_BLESSED? <=> { $__class__$ => }
24 36
25#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER 37#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER
26#define F_DEFAULT (12UL << S_MAXDEPTH) 38#define F_DEFAULT (9UL << S_MAXDEPTH)
27 39
28#define INIT_SIZE 32 // initial scalar size to be allocated 40#define INIT_SIZE 32 // initial scalar size to be allocated
29#define INDENT_STEP 3 // spaces per indentation level 41#define INDENT_STEP 3 // spaces per indentation level
30 42
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 43#define SHORT_STRING_LEN 16384 // special-case strings of up to this size
33 44
34#define SB do { 45#define SB do {
35#define SE } while (0) 46#define SE } while (0)
36 47
48#if __GNUC__ >= 3
49# define expect(expr,value) __builtin_expect ((expr),(value))
50# define inline inline
51#else
52# define expect(expr,value) (expr)
53# define inline static
54#endif
55
56#define expect_false(expr) expect ((expr) != 0, 0)
57#define expect_true(expr) expect ((expr) != 0, 1)
58
37static HV *json_stash; // JSON::XS:: 59static HV *json_stash; // JSON::XS::
60static SV *json_true, *json_false;
38 61
39///////////////////////////////////////////////////////////////////////////// 62/////////////////////////////////////////////////////////////////////////////
40// utility functions 63// utility functions
41 64
42static UV * 65static UV *
65// decode an utf-8 character and return it, or (UV)-1 in 88// decode an utf-8 character and return it, or (UV)-1 in
66// case of an error. 89// case of an error.
67// we special-case "safe" characters from U+80 .. U+7FF, 90// we special-case "safe" characters from U+80 .. U+7FF,
68// but use the very good perl function to parse anything else. 91// but use the very good perl function to parse anything else.
69// note that we never call this function for a ascii codepoints 92// note that we never call this function for a ascii codepoints
70static UV 93inline UV
71decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen) 94decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
72{ 95{
73 if (s[0] > 0xdf || s[0] < 0xc2) 96 if (expect_false (s[0] > 0xdf || s[0] < 0xc2))
74 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY); 97 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY);
75 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf) 98 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf)
76 { 99 {
77 *clen = 2; 100 *clen = 2;
78 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f); 101 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
79 } 102 }
80 else 103 else
104 {
105 *clen = (STRLEN)-1;
81 return (UV)-1; 106 return (UV)-1;
107 }
82} 108}
83 109
84///////////////////////////////////////////////////////////////////////////// 110/////////////////////////////////////////////////////////////////////////////
85// encoder 111// encoder
86 112
93 U32 flags; // F_* 119 U32 flags; // F_*
94 U32 indent; // indentation level 120 U32 indent; // indentation level
95 U32 maxdepth; // max. indentation/recursion level 121 U32 maxdepth; // max. indentation/recursion level
96} enc_t; 122} enc_t;
97 123
98static void 124inline void
99need (enc_t *enc, STRLEN len) 125need (enc_t *enc, STRLEN len)
100{ 126{
101 if (enc->cur + len >= enc->end) 127 if (expect_false (enc->cur + len >= enc->end))
102 { 128 {
103 STRLEN cur = enc->cur - SvPVX (enc->sv); 129 STRLEN cur = enc->cur - SvPVX (enc->sv);
104 SvGROW (enc->sv, cur + len + 1); 130 SvGROW (enc->sv, cur + len + 1);
105 enc->cur = SvPVX (enc->sv) + cur; 131 enc->cur = SvPVX (enc->sv) + cur;
106 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv); 132 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
107 } 133 }
108} 134}
109 135
110static void 136inline void
111encode_ch (enc_t *enc, char ch) 137encode_ch (enc_t *enc, char ch)
112{ 138{
113 need (enc, 1); 139 need (enc, 1);
114 *enc->cur++ = ch; 140 *enc->cur++ = ch;
115} 141}
123 149
124 while (str < end) 150 while (str < end)
125 { 151 {
126 unsigned char ch = *(unsigned char *)str; 152 unsigned char ch = *(unsigned char *)str;
127 153
128 if (ch >= 0x20 && ch < 0x80) // most common case 154 if (expect_true (ch >= 0x20 && ch < 0x80)) // most common case
129 { 155 {
130 if (ch == '"') // but with slow exceptions 156 if (expect_false (ch == '"')) // but with slow exceptions
131 { 157 {
132 need (enc, len += 1); 158 need (enc, len += 1);
133 *enc->cur++ = '\\'; 159 *enc->cur++ = '\\';
134 *enc->cur++ = '"'; 160 *enc->cur++ = '"';
135 } 161 }
136 else if (ch == '\\') 162 else if (expect_false (ch == '\\'))
137 { 163 {
138 need (enc, len += 1); 164 need (enc, len += 1);
139 *enc->cur++ = '\\'; 165 *enc->cur++ = '\\';
140 *enc->cur++ = '\\'; 166 *enc->cur++ = '\\';
141 } 167 }
159 STRLEN clen; 185 STRLEN clen;
160 UV uch; 186 UV uch;
161 187
162 if (is_utf8) 188 if (is_utf8)
163 { 189 {
164 //uch = utf8n_to_uvuni (str, end - str, &clen, UTF8_CHECK_ONLY);
165 uch = decode_utf8 (str, end - str, &clen); 190 uch = decode_utf8 (str, end - str, &clen);
166 if (clen == (STRLEN)-1) 191 if (clen == (STRLEN)-1)
167 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str); 192 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str);
168 } 193 }
169 else 194 else
173 } 198 }
174 199
175 if (uch > 0x10FFFFUL) 200 if (uch > 0x10FFFFUL)
176 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch); 201 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
177 202
178 if (uch < 0x80 || enc->flags & F_ASCII) 203 if (uch < 0x80 || enc->flags & F_ASCII || (enc->flags & F_LATIN1 && uch > 0xFF))
179 { 204 {
180 if (uch > 0xFFFFUL) 205 if (uch > 0xFFFFUL)
181 { 206 {
182 need (enc, len += 11); 207 need (enc, len += 11);
183 sprintf (enc->cur, "\\u%04x\\u%04x", 208 sprintf (enc->cur, "\\u%04x\\u%04x",
197 *enc->cur++ = hexdigit [(uch >> 0) & 15]; 222 *enc->cur++ = hexdigit [(uch >> 0) & 15];
198 } 223 }
199 224
200 str += clen; 225 str += clen;
201 } 226 }
227 else if (enc->flags & F_LATIN1)
228 {
229 *enc->cur++ = uch;
230 str += clen;
231 }
202 else if (is_utf8) 232 else if (is_utf8)
203 { 233 {
204 need (enc, len += clen); 234 need (enc, len += clen);
205 do 235 do
206 { 236 {
208 } 238 }
209 while (--clen); 239 while (--clen);
210 } 240 }
211 else 241 else
212 { 242 {
213 need (enc, len += UTF8_MAX_LEN - 1); // never more than 11 bytes needed 243 need (enc, len += UTF8_MAXBYTES - 1); // never more than 11 bytes needed
214 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); 244 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0);
215 ++str; 245 ++str;
216 } 246 }
217 } 247 }
218 } 248 }
220 250
221 --len; 251 --len;
222 } 252 }
223} 253}
224 254
225static void 255inline void
226encode_indent (enc_t *enc) 256encode_indent (enc_t *enc)
227{ 257{
228 if (enc->flags & F_INDENT) 258 if (enc->flags & F_INDENT)
229 { 259 {
230 int spaces = enc->indent * INDENT_STEP; 260 int spaces = enc->indent * INDENT_STEP;
233 memset (enc->cur, ' ', spaces); 263 memset (enc->cur, ' ', spaces);
234 enc->cur += spaces; 264 enc->cur += spaces;
235 } 265 }
236} 266}
237 267
238static void 268inline void
239encode_space (enc_t *enc) 269encode_space (enc_t *enc)
240{ 270{
241 need (enc, 1); 271 need (enc, 1);
242 encode_ch (enc, ' '); 272 encode_ch (enc, ' ');
243} 273}
244 274
245static void 275inline void
246encode_nl (enc_t *enc) 276encode_nl (enc_t *enc)
247{ 277{
248 if (enc->flags & F_INDENT) 278 if (enc->flags & F_INDENT)
249 { 279 {
250 need (enc, 1); 280 need (enc, 1);
251 encode_ch (enc, '\n'); 281 encode_ch (enc, '\n');
252 } 282 }
253} 283}
254 284
255static void 285inline void
256encode_comma (enc_t *enc) 286encode_comma (enc_t *enc)
257{ 287{
258 encode_ch (enc, ','); 288 encode_ch (enc, ',');
259 289
260 if (enc->flags & F_INDENT) 290 if (enc->flags & F_INDENT)
359 // actually, this is mostly due to the stupid so-called 389 // actually, this is mostly due to the stupid so-called
360 // security workaround added somewhere in 5.8.x. 390 // security workaround added somewhere in 5.8.x.
361 // that randomises hash orderings 391 // that randomises hash orderings
362 if (enc->flags & F_CANONICAL) 392 if (enc->flags & F_CANONICAL)
363 { 393 {
364 HE *he, *hes [count]; // if your compiler dies here, you need to enable C99 mode
365 int fast = 1; 394 int fast = 1;
395 HE *he;
396#if defined(__BORLANDC__) || defined(_MSC_VER)
397 HE **hes = _alloca (count * sizeof (HE));
398#else
399 HE *hes [count]; // if your compiler dies here, you need to enable C99 mode
400#endif
366 401
367 i = 0; 402 i = 0;
368 while ((he = hv_iternext (hv))) 403 while ((he = hv_iternext (hv)))
369 { 404 {
370 hes [i++] = he; 405 hes [i++] = he;
405 440
406 encode_nl (enc); 441 encode_nl (enc);
407 } 442 }
408 else 443 else
409 { 444 {
410 SV *sv;
411 HE *he = hv_iternext (hv); 445 HE *he = hv_iternext (hv);
412 446
413 for (;;) 447 for (;;)
414 { 448 {
415 encode_indent (enc); 449 encode_indent (enc);
430 464
431// encode objects, arrays and special \0=false and \1=true values. 465// encode objects, arrays and special \0=false and \1=true values.
432static void 466static void
433encode_rv (enc_t *enc, SV *sv) 467encode_rv (enc_t *enc, SV *sv)
434{ 468{
469 svtype svt;
470
435 SvGETMAGIC (sv); 471 SvGETMAGIC (sv);
436
437 svtype svt = SvTYPE (sv); 472 svt = SvTYPE (sv);
438 473
439 if (svt == SVt_PVHV) 474 if (svt == SVt_PVHV)
440 encode_hv (enc, (HV *)sv); 475 encode_hv (enc, (HV *)sv);
441 else if (svt == SVt_PVAV) 476 else if (svt == SVt_PVAV)
442 encode_av (enc, (AV *)sv); 477 encode_av (enc, (AV *)sv);
468 encode_str (enc, str, len, SvUTF8 (sv)); 503 encode_str (enc, str, len, SvUTF8 (sv));
469 encode_ch (enc, '"'); 504 encode_ch (enc, '"');
470 } 505 }
471 else if (SvNOKp (sv)) 506 else if (SvNOKp (sv))
472 { 507 {
508 // trust that perl will do the right thing w.r.t. JSON syntax.
473 need (enc, NV_DIG + 32); 509 need (enc, NV_DIG + 32);
474 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur); 510 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
475 enc->cur += strlen (enc->cur); 511 enc->cur += strlen (enc->cur);
476 } 512 }
477 else if (SvIOKp (sv)) 513 else if (SvIOKp (sv))
478 { 514 {
479 need (enc, 64); 515 // we assume we can always read an IV as a UV
516 if (SvUV (sv) & ~(UV)0x7fff)
517 {
518 // large integer, use the (rather slow) snprintf way.
519 need (enc, sizeof (UV) * 3);
480 enc->cur += 520 enc->cur +=
481 SvIsUV(sv) 521 SvIsUV(sv)
482 ? snprintf (enc->cur, 64, "%"UVuf, (UV)SvUVX (sv)) 522 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv))
483 : snprintf (enc->cur, 64, "%"IVdf, (IV)SvIVX (sv)); 523 : snprintf (enc->cur, sizeof (UV) * 3, "%"IVdf, (IV)SvIVX (sv));
524 }
525 else
526 {
527 // optimise the "small number case"
528 // code will likely be branchless and use only a single multiplication
529 I32 i = SvIV (sv);
530 U32 u;
531 char digit, nz = 0;
532
533 need (enc, 6);
534
535 *enc->cur = '-'; enc->cur += i < 0 ? 1 : 0;
536 u = i < 0 ? -i : i;
537
538 // convert to 4.28 fixed-point representation
539 u = u * ((0xfffffff + 10000) / 10000); // 10**5, 5 fractional digits
540
541 // now output digit by digit, each time masking out the integer part
542 // and multiplying by 5 while moving the decimal point one to the right,
543 // resulting in a net multiplication by 10.
544 // we always write the digit to memory but conditionally increment
545 // the pointer, to ease the usage of conditional move instructions.
546 digit = u >> 28; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0xfffffff) * 5;
547 digit = u >> 27; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x7ffffff) * 5;
548 digit = u >> 26; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x3ffffff) * 5;
549 digit = u >> 25; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x1ffffff) * 5;
550 digit = u >> 24; *enc->cur = digit + '0'; enc->cur += 1; // correctly generate '0'
551 }
484 } 552 }
485 else if (SvROK (sv)) 553 else if (SvROK (sv))
486 encode_rv (enc, SvRV (sv)); 554 encode_rv (enc, SvRV (sv));
487 else if (!SvOK (sv)) 555 else if (!SvOK (sv))
488 encode_str (enc, "null", 4, 0); 556 encode_str (enc, "null", 4, 0);
492} 560}
493 561
494static SV * 562static SV *
495encode_json (SV *scalar, U32 flags) 563encode_json (SV *scalar, U32 flags)
496{ 564{
565 enc_t enc;
566
497 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar)) 567 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar))
498 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)"); 568 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)");
499 569
500 enc_t enc;
501 enc.flags = flags; 570 enc.flags = flags;
502 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 571 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
503 enc.cur = SvPVX (enc.sv); 572 enc.cur = SvPVX (enc.sv);
504 enc.end = SvEND (enc.sv); 573 enc.end = SvEND (enc.sv);
505 enc.indent = 0; 574 enc.indent = 0;
506 enc.maxdepth = DEC_DEPTH (flags); 575 enc.maxdepth = DEC_DEPTH (flags);
507 576
508 SvPOK_only (enc.sv); 577 SvPOK_only (enc.sv);
509 encode_sv (&enc, scalar); 578 encode_sv (&enc, scalar);
510 579
580 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
581 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings
582
511 if (!(flags & (F_ASCII | F_UTF8))) 583 if (!(flags & (F_ASCII | F_LATIN1 | F_UTF8)))
512 SvUTF8_on (enc.sv); 584 SvUTF8_on (enc.sv);
513
514 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
515 585
516 if (enc.flags & F_SHRINK) 586 if (enc.flags & F_SHRINK)
517 shrink (enc.sv); 587 shrink (enc.sv);
518 588
519 return enc.sv; 589 return enc.sv;
531 U32 flags; // F_* 601 U32 flags; // F_*
532 U32 depth; // recursion depth 602 U32 depth; // recursion depth
533 U32 maxdepth; // recursion depth limit 603 U32 maxdepth; // recursion depth limit
534} dec_t; 604} dec_t;
535 605
536static void 606inline void
537decode_ws (dec_t *dec) 607decode_ws (dec_t *dec)
538{ 608{
539 for (;;) 609 for (;;)
540 { 610 {
541 char ch = *dec->cur; 611 char ch = *dec->cur;
567decode_4hex (dec_t *dec) 637decode_4hex (dec_t *dec)
568{ 638{
569 signed char d1, d2, d3, d4; 639 signed char d1, d2, d3, d4;
570 unsigned char *cur = (unsigned char *)dec->cur; 640 unsigned char *cur = (unsigned char *)dec->cur;
571 641
572 d1 = decode_hexdigit [cur [0]]; if (d1 < 0) ERR ("four hexadecimal digits expected"); 642 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"); 643 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"); 644 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"); 645 d4 = decode_hexdigit [cur [3]]; if (expect_false (d4 < 0)) ERR ("exactly four hexadecimal digits expected");
576 646
577 dec->cur += 4; 647 dec->cur += 4;
578 648
579 return ((UV)d1) << 12 649 return ((UV)d1) << 12
580 | ((UV)d2) << 8 650 | ((UV)d2) << 8
588static SV * 658static SV *
589decode_str (dec_t *dec) 659decode_str (dec_t *dec)
590{ 660{
591 SV *sv = 0; 661 SV *sv = 0;
592 int utf8 = 0; 662 int utf8 = 0;
663 char *dec_cur = dec->cur;
593 664
594 do 665 do
595 { 666 {
596 char buf [SHORT_STRING_LEN + UTF8_MAX_LEN]; 667 char buf [SHORT_STRING_LEN + UTF8_MAXBYTES];
597 char *cur = buf; 668 char *cur = buf;
598 669
599 do 670 do
600 { 671 {
601 unsigned char ch = *(unsigned char *)dec->cur++; 672 unsigned char ch = *(unsigned char *)dec_cur++;
602 673
603 if (ch == '"') 674 if (expect_false (ch == '"'))
604 { 675 {
605 --dec->cur; 676 --dec_cur;
606 break; 677 break;
607 } 678 }
608 else if (ch == '\\') 679 else if (expect_false (ch == '\\'))
609 { 680 {
610 switch (*dec->cur) 681 switch (*dec_cur)
611 { 682 {
612 case '\\': 683 case '\\':
613 case '/': 684 case '/':
614 case '"': *cur++ = *dec->cur++; break; 685 case '"': *cur++ = *dec_cur++; break;
615 686
616 case 'b': ++dec->cur; *cur++ = '\010'; break; 687 case 'b': ++dec_cur; *cur++ = '\010'; break;
617 case 't': ++dec->cur; *cur++ = '\011'; break; 688 case 't': ++dec_cur; *cur++ = '\011'; break;
618 case 'n': ++dec->cur; *cur++ = '\012'; break; 689 case 'n': ++dec_cur; *cur++ = '\012'; break;
619 case 'f': ++dec->cur; *cur++ = '\014'; break; 690 case 'f': ++dec_cur; *cur++ = '\014'; break;
620 case 'r': ++dec->cur; *cur++ = '\015'; break; 691 case 'r': ++dec_cur; *cur++ = '\015'; break;
621 692
622 case 'u': 693 case 'u':
623 { 694 {
624 UV lo, hi; 695 UV lo, hi;
625 ++dec->cur; 696 ++dec_cur;
626 697
698 dec->cur = dec_cur;
627 hi = decode_4hex (dec); 699 hi = decode_4hex (dec);
700 dec_cur = dec->cur;
628 if (hi == (UV)-1) 701 if (hi == (UV)-1)
629 goto fail; 702 goto fail;
630 703
631 // possibly a surrogate pair 704 // possibly a surrogate pair
632 if (hi >= 0xd800) 705 if (hi >= 0xd800)
633 if (hi < 0xdc00) 706 if (hi < 0xdc00)
634 { 707 {
635 if (dec->cur [0] != '\\' || dec->cur [1] != 'u') 708 if (dec_cur [0] != '\\' || dec_cur [1] != 'u')
636 ERR ("missing low surrogate character in surrogate pair"); 709 ERR ("missing low surrogate character in surrogate pair");
637 710
638 dec->cur += 2; 711 dec_cur += 2;
639 712
713 dec->cur = dec_cur;
640 lo = decode_4hex (dec); 714 lo = decode_4hex (dec);
715 dec_cur = dec->cur;
641 if (lo == (UV)-1) 716 if (lo == (UV)-1)
642 goto fail; 717 goto fail;
643 718
644 if (lo < 0xdc00 || lo >= 0xe000) 719 if (lo < 0xdc00 || lo >= 0xe000)
645 ERR ("surrogate pair expected"); 720 ERR ("surrogate pair expected");
659 *cur++ = hi; 734 *cur++ = hi;
660 } 735 }
661 break; 736 break;
662 737
663 default: 738 default:
664 --dec->cur; 739 --dec_cur;
665 ERR ("illegal backslash escape sequence in string"); 740 ERR ("illegal backslash escape sequence in string");
666 } 741 }
667 } 742 }
668 else if (ch >= 0x20 && ch <= 0x7f) 743 else if (expect_true (ch >= 0x20 && ch <= 0x7f))
669 *cur++ = ch; 744 *cur++ = ch;
670 else if (ch >= 0x80) 745 else if (ch >= 0x80)
671 { 746 {
672 --dec->cur;
673
674 STRLEN clen; 747 STRLEN clen;
748 UV uch;
749
750 --dec_cur;
751
675 UV uch = decode_utf8 (dec->cur, dec->end - dec->cur, &clen); 752 uch = decode_utf8 (dec_cur, dec->end - dec_cur, &clen);
676 if (clen == (STRLEN)-1) 753 if (clen == (STRLEN)-1)
677 ERR ("malformed UTF-8 character in JSON string"); 754 ERR ("malformed UTF-8 character in JSON string");
678 755
679 do 756 do
680 {
681 *cur++ = *dec->cur++; 757 *cur++ = *dec_cur++;
682 }
683 while (--clen); 758 while (--clen);
684 759
685 utf8 = 1; 760 utf8 = 1;
686 } 761 }
687 else if (!ch)
688 ERR ("unexpected end of string while parsing json string");
689 else 762 else
763 {
764 --dec_cur;
765
766 if (!ch)
767 ERR ("unexpected end of string while parsing JSON string");
768 else
690 ERR ("invalid character encountered"); 769 ERR ("invalid character encountered while parsing JSON string");
691 770 }
692 } 771 }
693 while (cur < buf + SHORT_STRING_LEN); 772 while (cur < buf + SHORT_STRING_LEN);
694 773
774 {
695 STRLEN len = cur - buf; 775 STRLEN len = cur - buf;
696 776
697 if (sv) 777 if (sv)
698 { 778 {
699 SvGROW (sv, SvCUR (sv) + len + 1); 779 SvGROW (sv, SvCUR (sv) + len + 1);
700 memcpy (SvPVX (sv) + SvCUR (sv), buf, len); 780 memcpy (SvPVX (sv) + SvCUR (sv), buf, len);
701 SvCUR_set (sv, SvCUR (sv) + len); 781 SvCUR_set (sv, SvCUR (sv) + len);
702 } 782 }
703 else 783 else
704 sv = newSVpvn (buf, len); 784 sv = newSVpvn (buf, len);
705 } 785 }
786 }
706 while (*dec->cur != '"'); 787 while (*dec_cur != '"');
707 788
708 ++dec->cur; 789 ++dec_cur;
709 790
710 if (sv) 791 if (sv)
711 { 792 {
712 SvPOK_only (sv); 793 SvPOK_only (sv);
713 *SvEND (sv) = 0; 794 *SvEND (sv) = 0;
716 SvUTF8_on (sv); 797 SvUTF8_on (sv);
717 } 798 }
718 else 799 else
719 sv = newSVpvn ("", 0); 800 sv = newSVpvn ("", 0);
720 801
802 dec->cur = dec_cur;
721 return sv; 803 return sv;
722 804
723fail: 805fail:
806 dec->cur = dec_cur;
724 return 0; 807 return 0;
725} 808}
726 809
727static SV * 810static SV *
728decode_num (dec_t *dec) 811decode_num (dec_t *dec)
786 is_nv = 1; 869 is_nv = 1;
787 } 870 }
788 871
789 if (!is_nv) 872 if (!is_nv)
790 { 873 {
791 UV uv; 874 // 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); 875 if (*start == '-')
793 if (numtype & IS_NUMBER_IN_UV) 876 switch (dec->cur - start)
794 if (numtype & IS_NUMBER_NEG)
795 { 877 {
796 if (uv < (UV)IV_MIN) 878 case 2: return newSViv (-( start [1] - '0' * 1));
797 return newSViv (-(IV)uv); 879 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11));
880 case 4: return newSViv (-( start [1] * 100 + start [2] * 10 + start [3] - '0' * 111));
881 case 5: return newSViv (-(start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111));
798 } 882 }
883 else
884 switch (dec->cur - start)
885 {
886 case 1: return newSViv ( start [0] - '0' * 1);
887 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11);
888 case 3: return newSViv ( start [0] * 100 + start [1] * 10 + start [2] - '0' * 111);
889 case 4: return newSViv ( start [0] * 1000 + start [1] * 100 + start [2] * 10 + start [3] - '0' * 1111);
890 }
891
892 {
893 UV uv;
894 int numtype = grok_number (start, dec->cur - start, &uv);
895 if (numtype & IS_NUMBER_IN_UV)
896 if (numtype & IS_NUMBER_NEG)
897 {
898 if (uv < (UV)IV_MIN)
899 return newSViv (-(IV)uv);
900 }
799 else 901 else
800 return newSVuv (uv); 902 return newSVuv (uv);
903
904 // here would likely be the place for bigint support
801 } 905 }
906 }
802 907
908 // if we ever support bigint or bigfloat, this is the place for bigfloat
803 return newSVnv (Atof (start)); 909 return newSVnv (Atof (start));
804 910
805fail: 911fail:
806 return 0; 912 return 0;
807} 913}
908 1014
909static SV * 1015static SV *
910decode_sv (dec_t *dec) 1016decode_sv (dec_t *dec)
911{ 1017{
912 decode_ws (dec); 1018 decode_ws (dec);
1019
1020 // the beauty of JSON: you need exactly one character lookahead
1021 // to parse anything.
913 switch (*dec->cur) 1022 switch (*dec->cur)
914 { 1023 {
915 case '"': ++dec->cur; return decode_str (dec); 1024 case '"': ++dec->cur; return decode_str (dec);
916 case '[': ++dec->cur; return decode_av (dec); 1025 case '[': ++dec->cur; return decode_av (dec);
917 case '{': ++dec->cur; return decode_hv (dec); 1026 case '{': ++dec->cur; return decode_hv (dec);
923 1032
924 case 't': 1033 case 't':
925 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1034 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
926 { 1035 {
927 dec->cur += 4; 1036 dec->cur += 4;
928 return newSViv (1); 1037 return SvREFCNT_inc (json_true);
929 } 1038 }
930 else 1039 else
931 ERR ("'true' expected"); 1040 ERR ("'true' expected");
932 1041
933 break; 1042 break;
934 1043
935 case 'f': 1044 case 'f':
936 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1045 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
937 { 1046 {
938 dec->cur += 5; 1047 dec->cur += 5;
939 return newSViv (0); 1048 return SvREFCNT_inc (json_false);
940 } 1049 }
941 else 1050 else
942 ERR ("'false' expected"); 1051 ERR ("'false' expected");
943 1052
944 break; 1053 break;
953 ERR ("'null' expected"); 1062 ERR ("'null' expected");
954 1063
955 break; 1064 break;
956 1065
957 default: 1066 default:
958 ERR ("malformed json string, neither array, object, number, string or atom"); 1067 ERR ("malformed JSON string, neither array, object, number, string or atom");
959 break; 1068 break;
960 } 1069 }
961 1070
962fail: 1071fail:
963 return 0; 1072 return 0;
964} 1073}
965 1074
966static SV * 1075static SV *
967decode_json (SV *string, U32 flags) 1076decode_json (SV *string, U32 flags, UV *offset_return)
968{ 1077{
1078 dec_t dec;
1079 UV offset;
969 SV *sv; 1080 SV *sv;
970 1081
1082 SvGETMAGIC (string);
971 SvUPGRADE (string, SVt_PV); 1083 SvUPGRADE (string, SVt_PV);
972 1084
973 if (flags & F_UTF8) 1085 if (flags & F_UTF8)
974 sv_utf8_downgrade (string, 0); 1086 sv_utf8_downgrade (string, 0);
975 else 1087 else
976 sv_utf8_upgrade (string); 1088 sv_utf8_upgrade (string);
977 1089
978 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP 1090 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
979 1091
980 dec_t dec;
981 dec.flags = flags; 1092 dec.flags = flags;
982 dec.cur = SvPVX (string); 1093 dec.cur = SvPVX (string);
983 dec.end = SvEND (string); 1094 dec.end = SvEND (string);
984 dec.err = 0; 1095 dec.err = 0;
985 dec.depth = 0; 1096 dec.depth = 0;
986 dec.maxdepth = DEC_DEPTH (dec.flags); 1097 dec.maxdepth = DEC_DEPTH (dec.flags);
987 1098
988 *dec.end = 0; // this should basically be a nop, too, but make sure its there 1099 *dec.end = 0; // this should basically be a nop, too, but make sure it's there
989 sv = decode_sv (&dec); 1100 sv = decode_sv (&dec);
990 1101
1102 if (!(offset_return || !sv))
1103 {
1104 // check for trailing garbage
1105 decode_ws (&dec);
1106
1107 if (*dec.cur)
1108 {
1109 dec.err = "garbage after JSON object";
1110 SvREFCNT_dec (sv);
1111 sv = 0;
1112 }
1113 }
1114
1115 if (offset_return || !sv)
1116 {
1117 offset = dec.flags & F_UTF8
1118 ? dec.cur - SvPVX (string)
1119 : utf8_distance (dec.cur, SvPVX (string));
1120
1121 if (offset_return)
1122 *offset_return = offset;
1123 }
1124
991 if (!sv) 1125 if (!sv)
992 { 1126 {
993 IV offset = dec.flags & F_UTF8
994 ? dec.cur - SvPVX (string)
995 : utf8_distance (dec.cur, SvPVX (string));
996 SV *uni = sv_newmortal (); 1127 SV *uni = sv_newmortal ();
997 1128
998 // horrible hack to silence warning inside pv_uni_display 1129 // horrible hack to silence warning inside pv_uni_display
999 COP cop = *PL_curcop; 1130 COP cop = *PL_curcop;
1000 cop.cop_warnings = pWARN_NONE; 1131 cop.cop_warnings = pWARN_NONE;
1002 SAVEVPTR (PL_curcop); 1133 SAVEVPTR (PL_curcop);
1003 PL_curcop = &cop; 1134 PL_curcop = &cop;
1004 pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ); 1135 pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ);
1005 LEAVE; 1136 LEAVE;
1006 1137
1007 croak ("%s, at character offset %d (%s)", 1138 croak ("%s, at character offset %d [\"%s\"]",
1008 dec.err, 1139 dec.err,
1009 (int)offset, 1140 (int)offset,
1010 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); 1141 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
1011 } 1142 }
1012 1143
1024MODULE = JSON::XS PACKAGE = JSON::XS 1155MODULE = JSON::XS PACKAGE = JSON::XS
1025 1156
1026BOOT: 1157BOOT:
1027{ 1158{
1028 int i; 1159 int i;
1029
1030 memset (decode_hexdigit, 0xff, 256);
1031 1160
1032 for (i = 0; i < 256; ++i) 1161 for (i = 0; i < 256; ++i)
1033 decode_hexdigit [i] = 1162 decode_hexdigit [i] =
1034 i >= '0' && i <= '9' ? i - '0' 1163 i >= '0' && i <= '9' ? i - '0'
1035 : i >= 'a' && i <= 'f' ? i - 'a' + 10 1164 : i >= 'a' && i <= 'f' ? i - 'a' + 10
1036 : i >= 'A' && i <= 'F' ? i - 'A' + 10 1165 : i >= 'A' && i <= 'F' ? i - 'A' + 10
1037 : -1; 1166 : -1;
1038 1167
1039 json_stash = gv_stashpv ("JSON::XS", 1); 1168 json_stash = gv_stashpv ("JSON::XS", 1);
1169
1170 json_true = get_sv ("JSON::XS::true" , 1); SvREADONLY_on (json_true );
1171 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1040} 1172}
1041 1173
1042PROTOTYPES: DISABLE 1174PROTOTYPES: DISABLE
1043 1175
1044SV *new (char *dummy) 1176SV *new (char *dummy)
1048 RETVAL 1180 RETVAL
1049 1181
1050SV *ascii (SV *self, int enable = 1) 1182SV *ascii (SV *self, int enable = 1)
1051 ALIAS: 1183 ALIAS:
1052 ascii = F_ASCII 1184 ascii = F_ASCII
1185 latin1 = F_LATIN1
1053 utf8 = F_UTF8 1186 utf8 = F_UTF8
1054 indent = F_INDENT 1187 indent = F_INDENT
1055 canonical = F_CANONICAL 1188 canonical = F_CANONICAL
1056 space_before = F_SPACE_BEFORE 1189 space_before = F_SPACE_BEFORE
1057 space_after = F_SPACE_AFTER 1190 space_after = F_SPACE_AFTER
1069 RETVAL = newSVsv (self); 1202 RETVAL = newSVsv (self);
1070} 1203}
1071 OUTPUT: 1204 OUTPUT:
1072 RETVAL 1205 RETVAL
1073 1206
1074SV *max_depth (SV *self, int max_depth = 0x80000000UL) 1207SV *max_depth (SV *self, UV max_depth = 0x80000000UL)
1075 CODE: 1208 CODE:
1076{ 1209{
1077 UV *uv = SvJSON (self); 1210 UV *uv = SvJSON (self);
1078 UV log2 = 0; 1211 UV log2 = 0;
1079 1212
1093 PPCODE: 1226 PPCODE:
1094 XPUSHs (encode_json (scalar, *SvJSON (self))); 1227 XPUSHs (encode_json (scalar, *SvJSON (self)));
1095 1228
1096void decode (SV *self, SV *jsonstr) 1229void decode (SV *self, SV *jsonstr)
1097 PPCODE: 1230 PPCODE:
1098 XPUSHs (decode_json (jsonstr, *SvJSON (self))); 1231 XPUSHs (decode_json (jsonstr, *SvJSON (self), 0));
1232
1233void decode_prefix (SV *self, SV *jsonstr)
1234 PPCODE:
1235{
1236 UV offset;
1237 EXTEND (SP, 2);
1238 PUSHs (decode_json (jsonstr, *SvJSON (self), &offset));
1239 PUSHs (sv_2mortal (newSVuv (offset)));
1240}
1099 1241
1100PROTOTYPES: ENABLE 1242PROTOTYPES: ENABLE
1101 1243
1102void to_json (SV *scalar) 1244void to_json (SV *scalar)
1103 ALIAS: 1245 ALIAS:
1107 1249
1108void from_json (SV *jsonstr) 1250void from_json (SV *jsonstr)
1109 ALIAS: 1251 ALIAS:
1110 jsonToObj = 0 1252 jsonToObj = 0
1111 PPCODE: 1253 PPCODE:
1112 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8)); 1254 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8, 0));
1113 1255

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines