ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/JSON-XS/XS.xs
Revision: 1.45
Committed: Mon Jun 25 06:57:42 2007 UTC (16 years, 10 months ago) by root
Branch: MAIN
Changes since 1.44: +26 -0 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 #include "EXTERN.h"
2 #include "perl.h"
3 #include "XSUB.h"
4
5 #include "assert.h"
6 #include "string.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
19
20 #define F_ASCII 0x00000001UL
21 #define F_LATIN1 0x00000002UL
22 #define F_UTF8 0x00000004UL
23 #define F_INDENT 0x00000008UL
24 #define F_CANONICAL 0x00000010UL
25 #define F_SPACE_BEFORE 0x00000020UL
26 #define F_SPACE_AFTER 0x00000040UL
27 #define F_ALLOW_NONREF 0x00000100UL
28 #define F_SHRINK 0x00000200UL
29 #define F_ALLOW_BLESSED 0x00000400UL
30 #define F_CONV_BLESSED 0x00000800UL // NYI
31 #define F_MAXDEPTH 0xf8000000UL
32 #define S_MAXDEPTH 27
33 #define F_MAXSIZE 0x01f00000UL
34 #define S_MAXSIZE 20
35
36 #define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH))
37 #define DEC_SIZE(flags) (1UL << ((flags & F_MAXSIZE ) >> S_MAXSIZE ))
38
39 #define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER
40 #define F_DEFAULT (9UL << S_MAXDEPTH)
41
42 #define INIT_SIZE 32 // initial scalar size to be allocated
43 #define INDENT_STEP 3 // spaces per indentation level
44
45 #define SHORT_STRING_LEN 16384 // special-case strings of up to this size
46
47 #define SB do {
48 #define SE } while (0)
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
61 static HV *json_stash, *json_boolean_stash; // JSON::XS::
62 static SV *json_true, *json_false;
63
64 /////////////////////////////////////////////////////////////////////////////
65 // utility functions
66
67 static UV *
68 SvJSON (SV *sv)
69 {
70 if (!(SvROK (sv) && SvOBJECT (SvRV (sv)) && SvSTASH (SvRV (sv)) == json_stash))
71 croak ("object is not of type JSON::XS");
72
73 return &SvUVX (SvRV (sv));
74 }
75
76 static void
77 shrink (SV *sv)
78 {
79 sv_utf8_downgrade (sv, 1);
80 if (SvLEN (sv) > SvCUR (sv) + 1)
81 {
82 #ifdef SvPV_shrink_to_cur
83 SvPV_shrink_to_cur (sv);
84 #elif defined (SvPV_renew)
85 SvPV_renew (sv, SvCUR (sv) + 1);
86 #endif
87 }
88 }
89
90 // decode an utf-8 character and return it, or (UV)-1 in
91 // case of an error.
92 // we special-case "safe" characters from U+80 .. U+7FF,
93 // but use the very good perl function to parse anything else.
94 // note that we never call this function for a ascii codepoints
95 inline UV
96 decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
97 {
98 if (expect_false (s[0] > 0xdf || s[0] < 0xc2))
99 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY);
100 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf)
101 {
102 *clen = 2;
103 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
104 }
105 else
106 {
107 *clen = (STRLEN)-1;
108 return (UV)-1;
109 }
110 }
111
112 /////////////////////////////////////////////////////////////////////////////
113 // encoder
114
115 // structure used for encoding JSON
116 typedef struct
117 {
118 char *cur; // SvPVX (sv) + current output position
119 char *end; // SvEND (sv)
120 SV *sv; // result scalar
121 U32 flags; // F_*
122 U32 indent; // indentation level
123 U32 maxdepth; // max. indentation/recursion level
124 } enc_t;
125
126 inline void
127 need (enc_t *enc, STRLEN len)
128 {
129 if (expect_false (enc->cur + len >= enc->end))
130 {
131 STRLEN cur = enc->cur - SvPVX (enc->sv);
132 SvGROW (enc->sv, cur + len + 1);
133 enc->cur = SvPVX (enc->sv) + cur;
134 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
135 }
136 }
137
138 inline void
139 encode_ch (enc_t *enc, char ch)
140 {
141 need (enc, 1);
142 *enc->cur++ = ch;
143 }
144
145 static void
146 encode_str (enc_t *enc, char *str, STRLEN len, int is_utf8)
147 {
148 char *end = str + len;
149
150 need (enc, len);
151
152 while (str < end)
153 {
154 unsigned char ch = *(unsigned char *)str;
155
156 if (expect_true (ch >= 0x20 && ch < 0x80)) // most common case
157 {
158 if (expect_false (ch == '"')) // but with slow exceptions
159 {
160 need (enc, len += 1);
161 *enc->cur++ = '\\';
162 *enc->cur++ = '"';
163 }
164 else if (expect_false (ch == '\\'))
165 {
166 need (enc, len += 1);
167 *enc->cur++ = '\\';
168 *enc->cur++ = '\\';
169 }
170 else
171 *enc->cur++ = ch;
172
173 ++str;
174 }
175 else
176 {
177 switch (ch)
178 {
179 case '\010': need (enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 'b'; ++str; break;
180 case '\011': need (enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 't'; ++str; break;
181 case '\012': need (enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 'n'; ++str; break;
182 case '\014': need (enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 'f'; ++str; break;
183 case '\015': need (enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 'r'; ++str; break;
184
185 default:
186 {
187 STRLEN clen;
188 UV uch;
189
190 if (is_utf8)
191 {
192 uch = decode_utf8 (str, end - str, &clen);
193 if (clen == (STRLEN)-1)
194 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str);
195 }
196 else
197 {
198 uch = ch;
199 clen = 1;
200 }
201
202 if (uch > 0x10FFFFUL)
203 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
204
205 if (uch < 0x80 || enc->flags & F_ASCII || (enc->flags & F_LATIN1 && uch > 0xFF))
206 {
207 if (uch > 0xFFFFUL)
208 {
209 need (enc, len += 11);
210 sprintf (enc->cur, "\\u%04x\\u%04x",
211 (int)((uch - 0x10000) / 0x400 + 0xD800),
212 (int)((uch - 0x10000) % 0x400 + 0xDC00));
213 enc->cur += 12;
214 }
215 else
216 {
217 static char hexdigit [16] = "0123456789abcdef";
218 need (enc, len += 5);
219 *enc->cur++ = '\\';
220 *enc->cur++ = 'u';
221 *enc->cur++ = hexdigit [ uch >> 12 ];
222 *enc->cur++ = hexdigit [(uch >> 8) & 15];
223 *enc->cur++ = hexdigit [(uch >> 4) & 15];
224 *enc->cur++ = hexdigit [(uch >> 0) & 15];
225 }
226
227 str += clen;
228 }
229 else if (enc->flags & F_LATIN1)
230 {
231 *enc->cur++ = uch;
232 str += clen;
233 }
234 else if (is_utf8)
235 {
236 need (enc, len += clen);
237 do
238 {
239 *enc->cur++ = *str++;
240 }
241 while (--clen);
242 }
243 else
244 {
245 need (enc, len += UTF8_MAXBYTES - 1); // never more than 11 bytes needed
246 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0);
247 ++str;
248 }
249 }
250 }
251 }
252
253 --len;
254 }
255 }
256
257 inline void
258 encode_indent (enc_t *enc)
259 {
260 if (enc->flags & F_INDENT)
261 {
262 int spaces = enc->indent * INDENT_STEP;
263
264 need (enc, spaces);
265 memset (enc->cur, ' ', spaces);
266 enc->cur += spaces;
267 }
268 }
269
270 inline void
271 encode_space (enc_t *enc)
272 {
273 need (enc, 1);
274 encode_ch (enc, ' ');
275 }
276
277 inline void
278 encode_nl (enc_t *enc)
279 {
280 if (enc->flags & F_INDENT)
281 {
282 need (enc, 1);
283 encode_ch (enc, '\n');
284 }
285 }
286
287 inline void
288 encode_comma (enc_t *enc)
289 {
290 encode_ch (enc, ',');
291
292 if (enc->flags & F_INDENT)
293 encode_nl (enc);
294 else if (enc->flags & F_SPACE_AFTER)
295 encode_space (enc);
296 }
297
298 static void encode_sv (enc_t *enc, SV *sv);
299
300 static void
301 encode_av (enc_t *enc, AV *av)
302 {
303 int i, len = av_len (av);
304
305 if (enc->indent >= enc->maxdepth)
306 croak ("data structure too deep (hit recursion limit)");
307
308 encode_ch (enc, '['); encode_nl (enc);
309 ++enc->indent;
310
311 for (i = 0; i <= len; ++i)
312 {
313 encode_indent (enc);
314 encode_sv (enc, *av_fetch (av, i, 0));
315
316 if (i < len)
317 encode_comma (enc);
318 }
319
320 encode_nl (enc);
321
322 --enc->indent;
323 encode_indent (enc); encode_ch (enc, ']');
324 }
325
326 static void
327 encode_he (enc_t *enc, HE *he)
328 {
329 encode_ch (enc, '"');
330
331 if (HeKLEN (he) == HEf_SVKEY)
332 {
333 SV *sv = HeSVKEY (he);
334 STRLEN len;
335 char *str;
336
337 SvGETMAGIC (sv);
338 str = SvPV (sv, len);
339
340 encode_str (enc, str, len, SvUTF8 (sv));
341 }
342 else
343 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he));
344
345 encode_ch (enc, '"');
346
347 if (enc->flags & F_SPACE_BEFORE) encode_space (enc);
348 encode_ch (enc, ':');
349 if (enc->flags & F_SPACE_AFTER ) encode_space (enc);
350 encode_sv (enc, HeVAL (he));
351 }
352
353 // compare hash entries, used when all keys are bytestrings
354 static int
355 he_cmp_fast (const void *a_, const void *b_)
356 {
357 int cmp;
358
359 HE *a = *(HE **)a_;
360 HE *b = *(HE **)b_;
361
362 STRLEN la = HeKLEN (a);
363 STRLEN lb = HeKLEN (b);
364
365 if (!(cmp = memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb)))
366 cmp = la - lb;
367
368 return cmp;
369 }
370
371 // compare hash entries, used when some keys are sv's or utf-x
372 static int
373 he_cmp_slow (const void *a, const void *b)
374 {
375 return sv_cmp (HeSVKEY_force (*(HE **)a), HeSVKEY_force (*(HE **)b));
376 }
377
378 static void
379 encode_hv (enc_t *enc, HV *hv)
380 {
381 int count, i;
382
383 if (enc->indent >= enc->maxdepth)
384 croak ("data structure too deep (hit recursion limit)");
385
386 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent;
387
388 if ((count = hv_iterinit (hv)))
389 {
390 // for canonical output we have to sort by keys first
391 // actually, this is mostly due to the stupid so-called
392 // security workaround added somewhere in 5.8.x.
393 // that randomises hash orderings
394 if (enc->flags & F_CANONICAL)
395 {
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
403
404 i = 0;
405 while ((he = hv_iternext (hv)))
406 {
407 hes [i++] = he;
408 if (HeKLEN (he) < 0 || HeKUTF8 (he))
409 fast = 0;
410 }
411
412 assert (i == count);
413
414 if (fast)
415 qsort (hes, count, sizeof (HE *), he_cmp_fast);
416 else
417 {
418 // hack to forcefully disable "use bytes"
419 COP cop = *PL_curcop;
420 cop.op_private = 0;
421
422 ENTER;
423 SAVETMPS;
424
425 SAVEVPTR (PL_curcop);
426 PL_curcop = &cop;
427
428 qsort (hes, count, sizeof (HE *), he_cmp_slow);
429
430 FREETMPS;
431 LEAVE;
432 }
433
434 for (i = 0; i < count; ++i)
435 {
436 encode_indent (enc);
437 encode_he (enc, hes [i]);
438
439 if (i < count - 1)
440 encode_comma (enc);
441 }
442
443 encode_nl (enc);
444 }
445 else
446 {
447 HE *he = hv_iternext (hv);
448
449 for (;;)
450 {
451 encode_indent (enc);
452 encode_he (enc, he);
453
454 if (!(he = hv_iternext (hv)))
455 break;
456
457 encode_comma (enc);
458 }
459
460 encode_nl (enc);
461 }
462 }
463
464 --enc->indent; encode_indent (enc); encode_ch (enc, '}');
465 }
466
467 // encode objects, arrays and special \0=false and \1=true values.
468 static void
469 encode_rv (enc_t *enc, SV *sv)
470 {
471 svtype svt;
472
473 SvGETMAGIC (sv);
474 svt = SvTYPE (sv);
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 }
530 else if (svt == SVt_PVHV)
531 encode_hv (enc, (HV *)sv);
532 else if (svt == SVt_PVAV)
533 encode_av (enc, (AV *)sv);
534 else if (svt < SVt_PVAV)
535 {
536 if (SvNIOK (sv) && SvIV (sv) == 0)
537 encode_str (enc, "false", 5, 0);
538 else if (SvNIOK (sv) && SvIV (sv) == 1)
539 encode_str (enc, "true", 4, 0);
540 else
541 croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1",
542 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
543 }
544 else
545 croak ("encountered %s, but JSON can only represent references to arrays or hashes",
546 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
547 }
548
549 static void
550 encode_sv (enc_t *enc, SV *sv)
551 {
552 SvGETMAGIC (sv);
553
554 if (SvPOKp (sv))
555 {
556 STRLEN len;
557 char *str = SvPV (sv, len);
558 encode_ch (enc, '"');
559 encode_str (enc, str, len, SvUTF8 (sv));
560 encode_ch (enc, '"');
561 }
562 else if (SvNOKp (sv))
563 {
564 // trust that perl will do the right thing w.r.t. JSON syntax.
565 need (enc, NV_DIG + 32);
566 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
567 enc->cur += strlen (enc->cur);
568 }
569 else if (SvIOKp (sv))
570 {
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);
576 enc->cur +=
577 SvIsUV(sv)
578 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (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 }
608 }
609 else if (SvROK (sv))
610 encode_rv (enc, SvRV (sv));
611 else if (!SvOK (sv))
612 encode_str (enc, "null", 4, 0);
613 else
614 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this",
615 SvPV_nolen (sv), SvFLAGS (sv));
616 }
617
618 static SV *
619 encode_json (SV *scalar, U32 flags)
620 {
621 enc_t enc;
622
623 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar))
624 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)");
625
626 enc.flags = flags;
627 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
628 enc.cur = SvPVX (enc.sv);
629 enc.end = SvEND (enc.sv);
630 enc.indent = 0;
631 enc.maxdepth = DEC_DEPTH (flags);
632
633 SvPOK_only (enc.sv);
634 encode_sv (&enc, scalar);
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
639 if (!(flags & (F_ASCII | F_LATIN1 | F_UTF8)))
640 SvUTF8_on (enc.sv);
641
642 if (enc.flags & F_SHRINK)
643 shrink (enc.sv);
644
645 return enc.sv;
646 }
647
648 /////////////////////////////////////////////////////////////////////////////
649 // decoder
650
651 // structure used for decoding JSON
652 typedef struct
653 {
654 char *cur; // current parser pointer
655 char *end; // end of input string
656 const char *err; // parse error, if != 0
657 U32 flags; // F_*
658 U32 depth; // recursion depth
659 U32 maxdepth; // recursion depth limit
660 } dec_t;
661
662 inline void
663 decode_ws (dec_t *dec)
664 {
665 for (;;)
666 {
667 char ch = *dec->cur;
668
669 if (ch > 0x20
670 || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09))
671 break;
672
673 ++dec->cur;
674 }
675 }
676
677 #define ERR(reason) SB dec->err = reason; goto fail; SE
678
679 #define EXPECT_CH(ch) SB \
680 if (*dec->cur != ch) \
681 ERR (# ch " expected"); \
682 ++dec->cur; \
683 SE
684
685 #define DEC_INC_DEPTH if (++dec->depth > dec->maxdepth) ERR ("json datastructure exceeds maximum nesting level (set a higher max_depth)")
686 #define DEC_DEC_DEPTH --dec->depth
687
688 static SV *decode_sv (dec_t *dec);
689
690 static signed char decode_hexdigit[256];
691
692 static UV
693 decode_4hex (dec_t *dec)
694 {
695 signed char d1, d2, d3, d4;
696 unsigned char *cur = (unsigned char *)dec->cur;
697
698 d1 = decode_hexdigit [cur [0]]; if (expect_false (d1 < 0)) ERR ("exactly four hexadecimal digits expected");
699 d2 = decode_hexdigit [cur [1]]; if (expect_false (d2 < 0)) ERR ("exactly four hexadecimal digits expected");
700 d3 = decode_hexdigit [cur [2]]; if (expect_false (d3 < 0)) ERR ("exactly four hexadecimal digits expected");
701 d4 = decode_hexdigit [cur [3]]; if (expect_false (d4 < 0)) ERR ("exactly four hexadecimal digits expected");
702
703 dec->cur += 4;
704
705 return ((UV)d1) << 12
706 | ((UV)d2) << 8
707 | ((UV)d3) << 4
708 | ((UV)d4);
709
710 fail:
711 return (UV)-1;
712 }
713
714 static SV *
715 decode_str (dec_t *dec)
716 {
717 SV *sv = 0;
718 int utf8 = 0;
719 char *dec_cur = dec->cur;
720
721 do
722 {
723 char buf [SHORT_STRING_LEN + UTF8_MAXBYTES];
724 char *cur = buf;
725
726 do
727 {
728 unsigned char ch = *(unsigned char *)dec_cur++;
729
730 if (expect_false (ch == '"'))
731 {
732 --dec_cur;
733 break;
734 }
735 else if (expect_false (ch == '\\'))
736 {
737 switch (*dec_cur)
738 {
739 case '\\':
740 case '/':
741 case '"': *cur++ = *dec_cur++; break;
742
743 case 'b': ++dec_cur; *cur++ = '\010'; break;
744 case 't': ++dec_cur; *cur++ = '\011'; break;
745 case 'n': ++dec_cur; *cur++ = '\012'; break;
746 case 'f': ++dec_cur; *cur++ = '\014'; break;
747 case 'r': ++dec_cur; *cur++ = '\015'; break;
748
749 case 'u':
750 {
751 UV lo, hi;
752 ++dec_cur;
753
754 dec->cur = dec_cur;
755 hi = decode_4hex (dec);
756 dec_cur = dec->cur;
757 if (hi == (UV)-1)
758 goto fail;
759
760 // possibly a surrogate pair
761 if (hi >= 0xd800)
762 if (hi < 0xdc00)
763 {
764 if (dec_cur [0] != '\\' || dec_cur [1] != 'u')
765 ERR ("missing low surrogate character in surrogate pair");
766
767 dec_cur += 2;
768
769 dec->cur = dec_cur;
770 lo = decode_4hex (dec);
771 dec_cur = dec->cur;
772 if (lo == (UV)-1)
773 goto fail;
774
775 if (lo < 0xdc00 || lo >= 0xe000)
776 ERR ("surrogate pair expected");
777
778 hi = (hi - 0xD800) * 0x400 + (lo - 0xDC00) + 0x10000;
779 }
780 else if (hi < 0xe000)
781 ERR ("missing high surrogate character in surrogate pair");
782
783 if (hi >= 0x80)
784 {
785 utf8 = 1;
786
787 cur = (char *)uvuni_to_utf8_flags (cur, hi, 0);
788 }
789 else
790 *cur++ = hi;
791 }
792 break;
793
794 default:
795 --dec_cur;
796 ERR ("illegal backslash escape sequence in string");
797 }
798 }
799 else if (expect_true (ch >= 0x20 && ch <= 0x7f))
800 *cur++ = ch;
801 else if (ch >= 0x80)
802 {
803 STRLEN clen;
804 UV uch;
805
806 --dec_cur;
807
808 uch = decode_utf8 (dec_cur, dec->end - dec_cur, &clen);
809 if (clen == (STRLEN)-1)
810 ERR ("malformed UTF-8 character in JSON string");
811
812 do
813 *cur++ = *dec_cur++;
814 while (--clen);
815
816 utf8 = 1;
817 }
818 else
819 {
820 --dec_cur;
821
822 if (!ch)
823 ERR ("unexpected end of string while parsing JSON string");
824 else
825 ERR ("invalid character encountered while parsing JSON string");
826 }
827 }
828 while (cur < buf + SHORT_STRING_LEN);
829
830 {
831 STRLEN len = cur - buf;
832
833 if (sv)
834 {
835 SvGROW (sv, SvCUR (sv) + len + 1);
836 memcpy (SvPVX (sv) + SvCUR (sv), buf, len);
837 SvCUR_set (sv, SvCUR (sv) + len);
838 }
839 else
840 sv = newSVpvn (buf, len);
841 }
842 }
843 while (*dec_cur != '"');
844
845 ++dec_cur;
846
847 if (sv)
848 {
849 SvPOK_only (sv);
850 *SvEND (sv) = 0;
851
852 if (utf8)
853 SvUTF8_on (sv);
854 }
855 else
856 sv = newSVpvn ("", 0);
857
858 dec->cur = dec_cur;
859 return sv;
860
861 fail:
862 dec->cur = dec_cur;
863 return 0;
864 }
865
866 static SV *
867 decode_num (dec_t *dec)
868 {
869 int is_nv = 0;
870 char *start = dec->cur;
871
872 // [minus]
873 if (*dec->cur == '-')
874 ++dec->cur;
875
876 if (*dec->cur == '0')
877 {
878 ++dec->cur;
879 if (*dec->cur >= '0' && *dec->cur <= '9')
880 ERR ("malformed number (leading zero must not be followed by another digit)");
881 }
882 else if (*dec->cur < '0' || *dec->cur > '9')
883 ERR ("malformed number (no digits after initial minus)");
884 else
885 do
886 {
887 ++dec->cur;
888 }
889 while (*dec->cur >= '0' && *dec->cur <= '9');
890
891 // [frac]
892 if (*dec->cur == '.')
893 {
894 ++dec->cur;
895
896 if (*dec->cur < '0' || *dec->cur > '9')
897 ERR ("malformed number (no digits after decimal point)");
898
899 do
900 {
901 ++dec->cur;
902 }
903 while (*dec->cur >= '0' && *dec->cur <= '9');
904
905 is_nv = 1;
906 }
907
908 // [exp]
909 if (*dec->cur == 'e' || *dec->cur == 'E')
910 {
911 ++dec->cur;
912
913 if (*dec->cur == '-' || *dec->cur == '+')
914 ++dec->cur;
915
916 if (*dec->cur < '0' || *dec->cur > '9')
917 ERR ("malformed number (no digits after exp sign)");
918
919 do
920 {
921 ++dec->cur;
922 }
923 while (*dec->cur >= '0' && *dec->cur <= '9');
924
925 is_nv = 1;
926 }
927
928 if (!is_nv)
929 {
930 // special case the rather common 1..4-digit-int case, assumes 32 bit ints or so
931 if (*start == '-')
932 switch (dec->cur - start)
933 {
934 case 2: return newSViv (-( start [1] - '0' * 1));
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));
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 }
957 else
958 return newSVuv (uv);
959
960 // here would likely be the place for bigint support
961 }
962 }
963
964 // if we ever support bigint or bigfloat, this is the place for bigfloat
965 return newSVnv (Atof (start));
966
967 fail:
968 return 0;
969 }
970
971 static SV *
972 decode_av (dec_t *dec)
973 {
974 AV *av = newAV ();
975
976 DEC_INC_DEPTH;
977 decode_ws (dec);
978
979 if (*dec->cur == ']')
980 ++dec->cur;
981 else
982 for (;;)
983 {
984 SV *value;
985
986 value = decode_sv (dec);
987 if (!value)
988 goto fail;
989
990 av_push (av, value);
991
992 decode_ws (dec);
993
994 if (*dec->cur == ']')
995 {
996 ++dec->cur;
997 break;
998 }
999
1000 if (*dec->cur != ',')
1001 ERR (", or ] expected while parsing array");
1002
1003 ++dec->cur;
1004 }
1005
1006 DEC_DEC_DEPTH;
1007 return newRV_noinc ((SV *)av);
1008
1009 fail:
1010 SvREFCNT_dec (av);
1011 DEC_DEC_DEPTH;
1012 return 0;
1013 }
1014
1015 static SV *
1016 decode_hv (dec_t *dec)
1017 {
1018 HV *hv = newHV ();
1019
1020 DEC_INC_DEPTH;
1021 decode_ws (dec);
1022
1023 if (*dec->cur == '}')
1024 ++dec->cur;
1025 else
1026 for (;;)
1027 {
1028 SV *key, *value;
1029
1030 decode_ws (dec); EXPECT_CH ('"');
1031
1032 key = decode_str (dec);
1033 if (!key)
1034 goto fail;
1035
1036 decode_ws (dec); EXPECT_CH (':');
1037
1038 value = decode_sv (dec);
1039 if (!value)
1040 {
1041 SvREFCNT_dec (key);
1042 goto fail;
1043 }
1044
1045 hv_store_ent (hv, key, value, 0);
1046 SvREFCNT_dec (key);
1047
1048 decode_ws (dec);
1049
1050 if (*dec->cur == '}')
1051 {
1052 ++dec->cur;
1053 break;
1054 }
1055
1056 if (*dec->cur != ',')
1057 ERR (", or } expected while parsing object/hash");
1058
1059 ++dec->cur;
1060 }
1061
1062 DEC_DEC_DEPTH;
1063 return newRV_noinc ((SV *)hv);
1064
1065 fail:
1066 SvREFCNT_dec (hv);
1067 DEC_DEC_DEPTH;
1068 return 0;
1069 }
1070
1071 static SV *
1072 decode_sv (dec_t *dec)
1073 {
1074 decode_ws (dec);
1075
1076 // the beauty of JSON: you need exactly one character lookahead
1077 // to parse anything.
1078 switch (*dec->cur)
1079 {
1080 case '"': ++dec->cur; return decode_str (dec);
1081 case '[': ++dec->cur; return decode_av (dec);
1082 case '{': ++dec->cur; return decode_hv (dec);
1083
1084 case '-':
1085 case '0': case '1': case '2': case '3': case '4':
1086 case '5': case '6': case '7': case '8': case '9':
1087 return decode_num (dec);
1088
1089 case 't':
1090 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
1091 {
1092 dec->cur += 4;
1093 return SvREFCNT_inc (json_true);
1094 }
1095 else
1096 ERR ("'true' expected");
1097
1098 break;
1099
1100 case 'f':
1101 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
1102 {
1103 dec->cur += 5;
1104 return SvREFCNT_inc (json_false);
1105 }
1106 else
1107 ERR ("'false' expected");
1108
1109 break;
1110
1111 case 'n':
1112 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "null", 4))
1113 {
1114 dec->cur += 4;
1115 return newSVsv (&PL_sv_undef);
1116 }
1117 else
1118 ERR ("'null' expected");
1119
1120 break;
1121
1122 default:
1123 ERR ("malformed JSON string, neither array, object, number, string or atom");
1124 break;
1125 }
1126
1127 fail:
1128 return 0;
1129 }
1130
1131 static SV *
1132 decode_json (SV *string, U32 flags, UV *offset_return)
1133 {
1134 dec_t dec;
1135 UV offset;
1136 SV *sv;
1137
1138 SvGETMAGIC (string);
1139 SvUPGRADE (string, SVt_PV);
1140
1141 if (flags & F_MAXSIZE && SvCUR (string) > DEC_SIZE (flags))
1142 croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu",
1143 (unsigned long)SvCUR (string), (unsigned long)DEC_SIZE (flags));
1144
1145 if (flags & F_UTF8)
1146 sv_utf8_downgrade (string, 0);
1147 else
1148 sv_utf8_upgrade (string);
1149
1150 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
1151
1152 dec.flags = flags;
1153 dec.cur = SvPVX (string);
1154 dec.end = SvEND (string);
1155 dec.err = 0;
1156 dec.depth = 0;
1157 dec.maxdepth = DEC_DEPTH (dec.flags);
1158
1159 *dec.end = 0; // this should basically be a nop, too, but make sure it's there
1160 sv = decode_sv (&dec);
1161
1162 if (!(offset_return || !sv))
1163 {
1164 // check for trailing garbage
1165 decode_ws (&dec);
1166
1167 if (*dec.cur)
1168 {
1169 dec.err = "garbage after JSON object";
1170 SvREFCNT_dec (sv);
1171 sv = 0;
1172 }
1173 }
1174
1175 if (offset_return || !sv)
1176 {
1177 offset = dec.flags & F_UTF8
1178 ? dec.cur - SvPVX (string)
1179 : utf8_distance (dec.cur, SvPVX (string));
1180
1181 if (offset_return)
1182 *offset_return = offset;
1183 }
1184
1185 if (!sv)
1186 {
1187 SV *uni = sv_newmortal ();
1188
1189 // horrible hack to silence warning inside pv_uni_display
1190 COP cop = *PL_curcop;
1191 cop.cop_warnings = pWARN_NONE;
1192 ENTER;
1193 SAVEVPTR (PL_curcop);
1194 PL_curcop = &cop;
1195 pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ);
1196 LEAVE;
1197
1198 croak ("%s, at character offset %d [\"%s\"]",
1199 dec.err,
1200 (int)offset,
1201 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
1202 }
1203
1204 sv = sv_2mortal (sv);
1205
1206 if (!(dec.flags & F_ALLOW_NONREF) && !SvROK (sv))
1207 croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)");
1208
1209 return sv;
1210 }
1211
1212 /////////////////////////////////////////////////////////////////////////////
1213 // XS interface functions
1214
1215 MODULE = JSON::XS PACKAGE = JSON::XS
1216
1217 BOOT:
1218 {
1219 int i;
1220
1221 for (i = 0; i < 256; ++i)
1222 decode_hexdigit [i] =
1223 i >= '0' && i <= '9' ? i - '0'
1224 : i >= 'a' && i <= 'f' ? i - 'a' + 10
1225 : i >= 'A' && i <= 'F' ? i - 'A' + 10
1226 : -1;
1227
1228 json_stash = gv_stashpv ("JSON::XS" , 1);
1229 json_boolean_stash = gv_stashpv ("JSON::XS::Boolean", 1);
1230
1231 json_true = get_sv ("JSON::XS::true" , 1); SvREADONLY_on (json_true );
1232 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1233 }
1234
1235 PROTOTYPES: DISABLE
1236
1237 SV *new (char *dummy)
1238 CODE:
1239 RETVAL = sv_bless (newRV_noinc (newSVuv (F_DEFAULT)), json_stash);
1240 OUTPUT:
1241 RETVAL
1242
1243 SV *ascii (SV *self, int enable = 1)
1244 ALIAS:
1245 ascii = F_ASCII
1246 latin1 = F_LATIN1
1247 utf8 = F_UTF8
1248 indent = F_INDENT
1249 canonical = F_CANONICAL
1250 space_before = F_SPACE_BEFORE
1251 space_after = F_SPACE_AFTER
1252 pretty = F_PRETTY
1253 allow_nonref = F_ALLOW_NONREF
1254 shrink = F_SHRINK
1255 allow_blessed = F_ALLOW_BLESSED
1256 convert_blessed = F_CONV_BLESSED
1257 CODE:
1258 {
1259 UV *uv = SvJSON (self);
1260 if (enable)
1261 *uv |= ix;
1262 else
1263 *uv &= ~ix;
1264
1265 RETVAL = newSVsv (self);
1266 }
1267 OUTPUT:
1268 RETVAL
1269
1270 SV *max_depth (SV *self, UV max_depth = 0x80000000UL)
1271 CODE:
1272 {
1273 UV *uv = SvJSON (self);
1274 UV log2 = 0;
1275
1276 if (max_depth > 0x80000000UL) max_depth = 0x80000000UL;
1277
1278 while ((1UL << log2) < max_depth)
1279 ++log2;
1280
1281 *uv = *uv & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1282
1283 RETVAL = newSVsv (self);
1284 }
1285 OUTPUT:
1286 RETVAL
1287
1288 SV *max_size (SV *self, UV max_size = 0)
1289 CODE:
1290 {
1291 UV *uv = SvJSON (self);
1292 UV log2 = 0;
1293
1294 if (max_size > 0x80000000UL) max_size = 0x80000000UL;
1295 if (max_size == 1) max_size = 2;
1296
1297 while ((1UL << log2) < max_size)
1298 ++log2;
1299
1300 *uv = *uv & ~F_MAXSIZE | (log2 << S_MAXSIZE);
1301
1302 RETVAL = newSVsv (self);
1303 }
1304 OUTPUT:
1305 RETVAL
1306
1307 void encode (SV *self, SV *scalar)
1308 PPCODE:
1309 XPUSHs (encode_json (scalar, *SvJSON (self)));
1310
1311 void decode (SV *self, SV *jsonstr)
1312 PPCODE:
1313 XPUSHs (decode_json (jsonstr, *SvJSON (self), 0));
1314
1315 void decode_prefix (SV *self, SV *jsonstr)
1316 PPCODE:
1317 {
1318 UV offset;
1319 EXTEND (SP, 2);
1320 PUSHs (decode_json (jsonstr, *SvJSON (self), &offset));
1321 PUSHs (sv_2mortal (newSVuv (offset)));
1322 }
1323
1324 PROTOTYPES: ENABLE
1325
1326 void to_json (SV *scalar)
1327 ALIAS:
1328 objToJson = 0
1329 PPCODE:
1330 XPUSHs (encode_json (scalar, F_DEFAULT | F_UTF8));
1331
1332 void from_json (SV *jsonstr)
1333 ALIAS:
1334 jsonToObj = 0
1335 PPCODE:
1336 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8, 0));
1337