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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines