ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/JSON-XS/XS.xs
Revision: 1.25
Committed: Fri Apr 6 20:37:22 2007 UTC (17 years, 1 month ago) by root
Branch: MAIN
Changes since 1.24: +22 -17 lines
Log Message:
it's a bloody disgrace

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
9 #define F_ASCII 0x00000001UL
10 #define F_UTF8 0x00000002UL
11 #define F_INDENT 0x00000004UL
12 #define F_CANONICAL 0x00000008UL
13 #define F_SPACE_BEFORE 0x00000010UL
14 #define F_SPACE_AFTER 0x00000020UL
15 #define F_ALLOW_NONREF 0x00000080UL
16 #define F_SHRINK 0x00000100UL
17 #define F_MAXDEPTH 0xf8000000UL
18 #define S_MAXDEPTH 27
19
20 #define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH))
21
22 // F_SELFCONVERT? <=> to_json/toJson
23 // F_BLESSED? <=> { $__class__$ => }
24
25 #define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER
26 #define F_DEFAULT (9UL << S_MAXDEPTH)
27
28 #define INIT_SIZE 32 // initial scalar size to be allocated
29 #define INDENT_STEP 3 // spaces per indentation level
30
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
33
34 #define SB do {
35 #define SE } while (0)
36
37 static HV *json_stash; // JSON::XS::
38
39 /////////////////////////////////////////////////////////////////////////////
40 // utility functions
41
42 static UV *
43 SvJSON (SV *sv)
44 {
45 if (!(SvROK (sv) && SvOBJECT (SvRV (sv)) && SvSTASH (SvRV (sv)) == json_stash))
46 croak ("object is not of type JSON::XS");
47
48 return &SvUVX (SvRV (sv));
49 }
50
51 static void
52 shrink (SV *sv)
53 {
54 sv_utf8_downgrade (sv, 1);
55 if (SvLEN (sv) > SvCUR (sv) + 1)
56 {
57 #ifdef SvPV_shrink_to_cur
58 SvPV_shrink_to_cur (sv);
59 #elif defined (SvPV_renew)
60 SvPV_renew (sv, SvCUR (sv) + 1);
61 #endif
62 }
63 }
64
65 // decode an utf-8 character and return it, or (UV)-1 in
66 // case of an error.
67 // we special-case "safe" characters from U+80 .. U+7FF,
68 // but use the very good perl function to parse anything else.
69 // note that we never call this function for a ascii codepoints
70 static UV
71 decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
72 {
73 if (s[0] > 0xdf || s[0] < 0xc2)
74 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY);
75 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf)
76 {
77 *clen = 2;
78 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
79 }
80 else
81 {
82 *clen = (STRLEN)-1;
83 return (UV)-1;
84 }
85 }
86
87 /////////////////////////////////////////////////////////////////////////////
88 // encoder
89
90 // structure used for encoding JSON
91 typedef struct
92 {
93 char *cur; // SvPVX (sv) + current output position
94 char *end; // SvEND (sv)
95 SV *sv; // result scalar
96 U32 flags; // F_*
97 U32 indent; // indentation level
98 U32 maxdepth; // max. indentation/recursion level
99 } enc_t;
100
101 static void
102 need (enc_t *enc, STRLEN len)
103 {
104 if (enc->cur + len >= enc->end)
105 {
106 STRLEN cur = enc->cur - SvPVX (enc->sv);
107 SvGROW (enc->sv, cur + len + 1);
108 enc->cur = SvPVX (enc->sv) + cur;
109 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv);
110 }
111 }
112
113 static void
114 encode_ch (enc_t *enc, char ch)
115 {
116 need (enc, 1);
117 *enc->cur++ = ch;
118 }
119
120 static void
121 encode_str (enc_t *enc, char *str, STRLEN len, int is_utf8)
122 {
123 char *end = str + len;
124
125 need (enc, len);
126
127 while (str < end)
128 {
129 unsigned char ch = *(unsigned char *)str;
130
131 if (ch >= 0x20 && ch < 0x80) // most common case
132 {
133 if (ch == '"') // but with slow exceptions
134 {
135 need (enc, len += 1);
136 *enc->cur++ = '\\';
137 *enc->cur++ = '"';
138 }
139 else if (ch == '\\')
140 {
141 need (enc, len += 1);
142 *enc->cur++ = '\\';
143 *enc->cur++ = '\\';
144 }
145 else
146 *enc->cur++ = ch;
147
148 ++str;
149 }
150 else
151 {
152 switch (ch)
153 {
154 case '\010': need (enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 'b'; ++str; break;
155 case '\011': need (enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 't'; ++str; break;
156 case '\012': need (enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 'n'; ++str; break;
157 case '\014': need (enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 'f'; ++str; break;
158 case '\015': need (enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 'r'; ++str; break;
159
160 default:
161 {
162 STRLEN clen;
163 UV uch;
164
165 if (is_utf8)
166 {
167 //uch = utf8n_to_uvuni (str, end - str, &clen, UTF8_CHECK_ONLY);
168 uch = decode_utf8 (str, end - str, &clen);
169 if (clen == (STRLEN)-1)
170 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str);
171 }
172 else
173 {
174 uch = ch;
175 clen = 1;
176 }
177
178 if (uch > 0x10FFFFUL)
179 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
180
181 if (uch < 0x80 || enc->flags & F_ASCII)
182 {
183 if (uch > 0xFFFFUL)
184 {
185 need (enc, len += 11);
186 sprintf (enc->cur, "\\u%04x\\u%04x",
187 (int)((uch - 0x10000) / 0x400 + 0xD800),
188 (int)((uch - 0x10000) % 0x400 + 0xDC00));
189 enc->cur += 12;
190 }
191 else
192 {
193 static char hexdigit [16] = "0123456789abcdef";
194 need (enc, len += 5);
195 *enc->cur++ = '\\';
196 *enc->cur++ = 'u';
197 *enc->cur++ = hexdigit [ uch >> 12 ];
198 *enc->cur++ = hexdigit [(uch >> 8) & 15];
199 *enc->cur++ = hexdigit [(uch >> 4) & 15];
200 *enc->cur++ = hexdigit [(uch >> 0) & 15];
201 }
202
203 str += clen;
204 }
205 else if (is_utf8)
206 {
207 need (enc, len += clen);
208 do
209 {
210 *enc->cur++ = *str++;
211 }
212 while (--clen);
213 }
214 else
215 {
216 need (enc, len += UTF8_MAX_LEN - 1); // never more than 11 bytes needed
217 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0);
218 ++str;
219 }
220 }
221 }
222 }
223
224 --len;
225 }
226 }
227
228 static void
229 encode_indent (enc_t *enc)
230 {
231 if (enc->flags & F_INDENT)
232 {
233 int spaces = enc->indent * INDENT_STEP;
234
235 need (enc, spaces);
236 memset (enc->cur, ' ', spaces);
237 enc->cur += spaces;
238 }
239 }
240
241 static void
242 encode_space (enc_t *enc)
243 {
244 need (enc, 1);
245 encode_ch (enc, ' ');
246 }
247
248 static void
249 encode_nl (enc_t *enc)
250 {
251 if (enc->flags & F_INDENT)
252 {
253 need (enc, 1);
254 encode_ch (enc, '\n');
255 }
256 }
257
258 static void
259 encode_comma (enc_t *enc)
260 {
261 encode_ch (enc, ',');
262
263 if (enc->flags & F_INDENT)
264 encode_nl (enc);
265 else if (enc->flags & F_SPACE_AFTER)
266 encode_space (enc);
267 }
268
269 static void encode_sv (enc_t *enc, SV *sv);
270
271 static void
272 encode_av (enc_t *enc, AV *av)
273 {
274 int i, len = av_len (av);
275
276 if (enc->indent >= enc->maxdepth)
277 croak ("data structure too deep (hit recursion limit)");
278
279 encode_ch (enc, '['); encode_nl (enc);
280 ++enc->indent;
281
282 for (i = 0; i <= len; ++i)
283 {
284 encode_indent (enc);
285 encode_sv (enc, *av_fetch (av, i, 0));
286
287 if (i < len)
288 encode_comma (enc);
289 }
290
291 encode_nl (enc);
292
293 --enc->indent;
294 encode_indent (enc); encode_ch (enc, ']');
295 }
296
297 static void
298 encode_he (enc_t *enc, HE *he)
299 {
300 encode_ch (enc, '"');
301
302 if (HeKLEN (he) == HEf_SVKEY)
303 {
304 SV *sv = HeSVKEY (he);
305 STRLEN len;
306 char *str;
307
308 SvGETMAGIC (sv);
309 str = SvPV (sv, len);
310
311 encode_str (enc, str, len, SvUTF8 (sv));
312 }
313 else
314 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he));
315
316 encode_ch (enc, '"');
317
318 if (enc->flags & F_SPACE_BEFORE) encode_space (enc);
319 encode_ch (enc, ':');
320 if (enc->flags & F_SPACE_AFTER ) encode_space (enc);
321 encode_sv (enc, HeVAL (he));
322 }
323
324 // compare hash entries, used when all keys are bytestrings
325 static int
326 he_cmp_fast (const void *a_, const void *b_)
327 {
328 int cmp;
329
330 HE *a = *(HE **)a_;
331 HE *b = *(HE **)b_;
332
333 STRLEN la = HeKLEN (a);
334 STRLEN lb = HeKLEN (b);
335
336 if (!(cmp = memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb)))
337 cmp = la - lb;
338
339 return cmp;
340 }
341
342 // compare hash entries, used when some keys are sv's or utf-x
343 static int
344 he_cmp_slow (const void *a, const void *b)
345 {
346 return sv_cmp (HeSVKEY_force (*(HE **)a), HeSVKEY_force (*(HE **)b));
347 }
348
349 static void
350 encode_hv (enc_t *enc, HV *hv)
351 {
352 int count, i;
353
354 if (enc->indent >= enc->maxdepth)
355 croak ("data structure too deep (hit recursion limit)");
356
357 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent;
358
359 if ((count = hv_iterinit (hv)))
360 {
361 // for canonical output we have to sort by keys first
362 // actually, this is mostly due to the stupid so-called
363 // security workaround added somewhere in 5.8.x.
364 // that randomises hash orderings
365 if (enc->flags & F_CANONICAL)
366 {
367 HE *he, *hes [count]; // if your compiler dies here, you need to enable C99 mode
368 int fast = 1;
369
370 i = 0;
371 while ((he = hv_iternext (hv)))
372 {
373 hes [i++] = he;
374 if (HeKLEN (he) < 0 || HeKUTF8 (he))
375 fast = 0;
376 }
377
378 assert (i == count);
379
380 if (fast)
381 qsort (hes, count, sizeof (HE *), he_cmp_fast);
382 else
383 {
384 // hack to forcefully disable "use bytes"
385 COP cop = *PL_curcop;
386 cop.op_private = 0;
387
388 ENTER;
389 SAVETMPS;
390
391 SAVEVPTR (PL_curcop);
392 PL_curcop = &cop;
393
394 qsort (hes, count, sizeof (HE *), he_cmp_slow);
395
396 FREETMPS;
397 LEAVE;
398 }
399
400 for (i = 0; i < count; ++i)
401 {
402 encode_indent (enc);
403 encode_he (enc, hes [i]);
404
405 if (i < count - 1)
406 encode_comma (enc);
407 }
408
409 encode_nl (enc);
410 }
411 else
412 {
413 HE *he = hv_iternext (hv);
414
415 for (;;)
416 {
417 encode_indent (enc);
418 encode_he (enc, he);
419
420 if (!(he = hv_iternext (hv)))
421 break;
422
423 encode_comma (enc);
424 }
425
426 encode_nl (enc);
427 }
428 }
429
430 --enc->indent; encode_indent (enc); encode_ch (enc, '}');
431 }
432
433 // encode objects, arrays and special \0=false and \1=true values.
434 static void
435 encode_rv (enc_t *enc, SV *sv)
436 {
437 svtype svt;
438
439 SvGETMAGIC (sv);
440 svt = SvTYPE (sv);
441
442 if (svt == SVt_PVHV)
443 encode_hv (enc, (HV *)sv);
444 else if (svt == SVt_PVAV)
445 encode_av (enc, (AV *)sv);
446 else if (svt < SVt_PVAV)
447 {
448 if (SvNIOK (sv) && SvIV (sv) == 0)
449 encode_str (enc, "false", 5, 0);
450 else if (SvNIOK (sv) && SvIV (sv) == 1)
451 encode_str (enc, "true", 4, 0);
452 else
453 croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1",
454 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
455 }
456 else
457 croak ("encountered %s, but JSON can only represent references to arrays or hashes",
458 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
459 }
460
461 static void
462 encode_sv (enc_t *enc, SV *sv)
463 {
464 SvGETMAGIC (sv);
465
466 if (SvPOKp (sv))
467 {
468 STRLEN len;
469 char *str = SvPV (sv, len);
470 encode_ch (enc, '"');
471 encode_str (enc, str, len, SvUTF8 (sv));
472 encode_ch (enc, '"');
473 }
474 else if (SvNOKp (sv))
475 {
476 need (enc, NV_DIG + 32);
477 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
478 enc->cur += strlen (enc->cur);
479 }
480 else if (SvIOKp (sv))
481 {
482 need (enc, 64);
483 enc->cur +=
484 SvIsUV(sv)
485 ? snprintf (enc->cur, 64, "%"UVuf, (UV)SvUVX (sv))
486 : snprintf (enc->cur, 64, "%"IVdf, (IV)SvIVX (sv));
487 }
488 else if (SvROK (sv))
489 encode_rv (enc, SvRV (sv));
490 else if (!SvOK (sv))
491 encode_str (enc, "null", 4, 0);
492 else
493 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this",
494 SvPV_nolen (sv), SvFLAGS (sv));
495 }
496
497 static SV *
498 encode_json (SV *scalar, U32 flags)
499 {
500 enc_t enc;
501
502 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar))
503 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)");
504
505 enc.flags = flags;
506 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
507 enc.cur = SvPVX (enc.sv);
508 enc.end = SvEND (enc.sv);
509 enc.indent = 0;
510 enc.maxdepth = DEC_DEPTH (flags);
511
512 SvPOK_only (enc.sv);
513 encode_sv (&enc, scalar);
514
515 if (!(flags & (F_ASCII | F_UTF8)))
516 SvUTF8_on (enc.sv);
517
518 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
519
520 if (enc.flags & F_SHRINK)
521 shrink (enc.sv);
522
523 return enc.sv;
524 }
525
526 /////////////////////////////////////////////////////////////////////////////
527 // decoder
528
529 // structure used for decoding JSON
530 typedef struct
531 {
532 char *cur; // current parser pointer
533 char *end; // end of input string
534 const char *err; // parse error, if != 0
535 U32 flags; // F_*
536 U32 depth; // recursion depth
537 U32 maxdepth; // recursion depth limit
538 } dec_t;
539
540 static void
541 decode_ws (dec_t *dec)
542 {
543 for (;;)
544 {
545 char ch = *dec->cur;
546
547 if (ch > 0x20
548 || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09))
549 break;
550
551 ++dec->cur;
552 }
553 }
554
555 #define ERR(reason) SB dec->err = reason; goto fail; SE
556
557 #define EXPECT_CH(ch) SB \
558 if (*dec->cur != ch) \
559 ERR (# ch " expected"); \
560 ++dec->cur; \
561 SE
562
563 #define DEC_INC_DEPTH if (++dec->depth > dec->maxdepth) ERR ("json datastructure exceeds maximum nesting level (set a higher max_depth)")
564 #define DEC_DEC_DEPTH --dec->depth
565
566 static SV *decode_sv (dec_t *dec);
567
568 static signed char decode_hexdigit[256];
569
570 static UV
571 decode_4hex (dec_t *dec)
572 {
573 signed char d1, d2, d3, d4;
574 unsigned char *cur = (unsigned char *)dec->cur;
575
576 d1 = decode_hexdigit [cur [0]]; if (d1 < 0) ERR ("four hexadecimal digits expected");
577 d2 = decode_hexdigit [cur [1]]; if (d2 < 0) ERR ("four hexadecimal digits expected");
578 d3 = decode_hexdigit [cur [2]]; if (d3 < 0) ERR ("four hexadecimal digits expected");
579 d4 = decode_hexdigit [cur [3]]; if (d4 < 0) ERR ("four hexadecimal digits expected");
580
581 dec->cur += 4;
582
583 return ((UV)d1) << 12
584 | ((UV)d2) << 8
585 | ((UV)d3) << 4
586 | ((UV)d4);
587
588 fail:
589 return (UV)-1;
590 }
591
592 static SV *
593 decode_str (dec_t *dec)
594 {
595 SV *sv = 0;
596 int utf8 = 0;
597
598 do
599 {
600 char buf [SHORT_STRING_LEN + UTF8_MAX_LEN];
601 char *cur = buf;
602
603 do
604 {
605 unsigned char ch = *(unsigned char *)dec->cur++;
606
607 if (ch == '"')
608 {
609 --dec->cur;
610 break;
611 }
612 else if (ch == '\\')
613 {
614 switch (*dec->cur)
615 {
616 case '\\':
617 case '/':
618 case '"': *cur++ = *dec->cur++; break;
619
620 case 'b': ++dec->cur; *cur++ = '\010'; break;
621 case 't': ++dec->cur; *cur++ = '\011'; break;
622 case 'n': ++dec->cur; *cur++ = '\012'; break;
623 case 'f': ++dec->cur; *cur++ = '\014'; break;
624 case 'r': ++dec->cur; *cur++ = '\015'; break;
625
626 case 'u':
627 {
628 UV lo, hi;
629 ++dec->cur;
630
631 hi = decode_4hex (dec);
632 if (hi == (UV)-1)
633 goto fail;
634
635 // possibly a surrogate pair
636 if (hi >= 0xd800)
637 if (hi < 0xdc00)
638 {
639 if (dec->cur [0] != '\\' || dec->cur [1] != 'u')
640 ERR ("missing low surrogate character in surrogate pair");
641
642 dec->cur += 2;
643
644 lo = decode_4hex (dec);
645 if (lo == (UV)-1)
646 goto fail;
647
648 if (lo < 0xdc00 || lo >= 0xe000)
649 ERR ("surrogate pair expected");
650
651 hi = (hi - 0xD800) * 0x400 + (lo - 0xDC00) + 0x10000;
652 }
653 else if (hi < 0xe000)
654 ERR ("missing high surrogate character in surrogate pair");
655
656 if (hi >= 0x80)
657 {
658 utf8 = 1;
659
660 cur = (char *)uvuni_to_utf8_flags (cur, hi, 0);
661 }
662 else
663 *cur++ = hi;
664 }
665 break;
666
667 default:
668 --dec->cur;
669 ERR ("illegal backslash escape sequence in string");
670 }
671 }
672 else if (ch >= 0x20 && ch <= 0x7f)
673 *cur++ = ch;
674 else if (ch >= 0x80)
675 {
676 STRLEN clen;
677 UV uch;
678
679 --dec->cur;
680
681 uch = decode_utf8 (dec->cur, dec->end - dec->cur, &clen);
682 if (clen == (STRLEN)-1)
683 ERR ("malformed UTF-8 character in JSON string");
684
685 do
686 *cur++ = *dec->cur++;
687 while (--clen);
688
689 utf8 = 1;
690 }
691 else
692 {
693 --dec->cur;
694
695 if (!ch)
696 ERR ("unexpected end of string while parsing JSON string");
697 else
698 ERR ("invalid character encountered while parsing JSON string");
699 }
700 }
701 while (cur < buf + SHORT_STRING_LEN);
702
703 {
704 STRLEN len = cur - buf;
705
706 if (sv)
707 {
708 SvGROW (sv, SvCUR (sv) + len + 1);
709 memcpy (SvPVX (sv) + SvCUR (sv), buf, len);
710 SvCUR_set (sv, SvCUR (sv) + len);
711 }
712 else
713 sv = newSVpvn (buf, len);
714 }
715 }
716 while (*dec->cur != '"');
717
718 ++dec->cur;
719
720 if (sv)
721 {
722 SvPOK_only (sv);
723 *SvEND (sv) = 0;
724
725 if (utf8)
726 SvUTF8_on (sv);
727 }
728 else
729 sv = newSVpvn ("", 0);
730
731 return sv;
732
733 fail:
734 return 0;
735 }
736
737 static SV *
738 decode_num (dec_t *dec)
739 {
740 int is_nv = 0;
741 char *start = dec->cur;
742
743 // [minus]
744 if (*dec->cur == '-')
745 ++dec->cur;
746
747 if (*dec->cur == '0')
748 {
749 ++dec->cur;
750 if (*dec->cur >= '0' && *dec->cur <= '9')
751 ERR ("malformed number (leading zero must not be followed by another digit)");
752 }
753 else if (*dec->cur < '0' || *dec->cur > '9')
754 ERR ("malformed number (no digits after initial minus)");
755 else
756 do
757 {
758 ++dec->cur;
759 }
760 while (*dec->cur >= '0' && *dec->cur <= '9');
761
762 // [frac]
763 if (*dec->cur == '.')
764 {
765 ++dec->cur;
766
767 if (*dec->cur < '0' || *dec->cur > '9')
768 ERR ("malformed number (no digits after decimal point)");
769
770 do
771 {
772 ++dec->cur;
773 }
774 while (*dec->cur >= '0' && *dec->cur <= '9');
775
776 is_nv = 1;
777 }
778
779 // [exp]
780 if (*dec->cur == 'e' || *dec->cur == 'E')
781 {
782 ++dec->cur;
783
784 if (*dec->cur == '-' || *dec->cur == '+')
785 ++dec->cur;
786
787 if (*dec->cur < '0' || *dec->cur > '9')
788 ERR ("malformed number (no digits after exp sign)");
789
790 do
791 {
792 ++dec->cur;
793 }
794 while (*dec->cur >= '0' && *dec->cur <= '9');
795
796 is_nv = 1;
797 }
798
799 if (!is_nv)
800 {
801 UV uv;
802 int numtype = grok_number (start, dec->cur - start, &uv);
803 if (numtype & IS_NUMBER_IN_UV)
804 if (numtype & IS_NUMBER_NEG)
805 {
806 if (uv < (UV)IV_MIN)
807 return newSViv (-(IV)uv);
808 }
809 else
810 return newSVuv (uv);
811 }
812
813 return newSVnv (Atof (start));
814
815 fail:
816 return 0;
817 }
818
819 static SV *
820 decode_av (dec_t *dec)
821 {
822 AV *av = newAV ();
823
824 DEC_INC_DEPTH;
825 decode_ws (dec);
826
827 if (*dec->cur == ']')
828 ++dec->cur;
829 else
830 for (;;)
831 {
832 SV *value;
833
834 value = decode_sv (dec);
835 if (!value)
836 goto fail;
837
838 av_push (av, value);
839
840 decode_ws (dec);
841
842 if (*dec->cur == ']')
843 {
844 ++dec->cur;
845 break;
846 }
847
848 if (*dec->cur != ',')
849 ERR (", or ] expected while parsing array");
850
851 ++dec->cur;
852 }
853
854 DEC_DEC_DEPTH;
855 return newRV_noinc ((SV *)av);
856
857 fail:
858 SvREFCNT_dec (av);
859 DEC_DEC_DEPTH;
860 return 0;
861 }
862
863 static SV *
864 decode_hv (dec_t *dec)
865 {
866 HV *hv = newHV ();
867
868 DEC_INC_DEPTH;
869 decode_ws (dec);
870
871 if (*dec->cur == '}')
872 ++dec->cur;
873 else
874 for (;;)
875 {
876 SV *key, *value;
877
878 decode_ws (dec); EXPECT_CH ('"');
879
880 key = decode_str (dec);
881 if (!key)
882 goto fail;
883
884 decode_ws (dec); EXPECT_CH (':');
885
886 value = decode_sv (dec);
887 if (!value)
888 {
889 SvREFCNT_dec (key);
890 goto fail;
891 }
892
893 hv_store_ent (hv, key, value, 0);
894 SvREFCNT_dec (key);
895
896 decode_ws (dec);
897
898 if (*dec->cur == '}')
899 {
900 ++dec->cur;
901 break;
902 }
903
904 if (*dec->cur != ',')
905 ERR (", or } expected while parsing object/hash");
906
907 ++dec->cur;
908 }
909
910 DEC_DEC_DEPTH;
911 return newRV_noinc ((SV *)hv);
912
913 fail:
914 SvREFCNT_dec (hv);
915 DEC_DEC_DEPTH;
916 return 0;
917 }
918
919 static SV *
920 decode_sv (dec_t *dec)
921 {
922 decode_ws (dec);
923 switch (*dec->cur)
924 {
925 case '"': ++dec->cur; return decode_str (dec);
926 case '[': ++dec->cur; return decode_av (dec);
927 case '{': ++dec->cur; return decode_hv (dec);
928
929 case '-':
930 case '0': case '1': case '2': case '3': case '4':
931 case '5': case '6': case '7': case '8': case '9':
932 return decode_num (dec);
933
934 case 't':
935 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
936 {
937 dec->cur += 4;
938 return newSViv (1);
939 }
940 else
941 ERR ("'true' expected");
942
943 break;
944
945 case 'f':
946 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
947 {
948 dec->cur += 5;
949 return newSViv (0);
950 }
951 else
952 ERR ("'false' expected");
953
954 break;
955
956 case 'n':
957 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "null", 4))
958 {
959 dec->cur += 4;
960 return newSVsv (&PL_sv_undef);
961 }
962 else
963 ERR ("'null' expected");
964
965 break;
966
967 default:
968 ERR ("malformed JSON string, neither array, object, number, string or atom");
969 break;
970 }
971
972 fail:
973 return 0;
974 }
975
976 static SV *
977 decode_json (SV *string, U32 flags)
978 {
979 dec_t dec;
980 SV *sv;
981
982 SvUPGRADE (string, SVt_PV);
983
984 if (flags & F_UTF8)
985 sv_utf8_downgrade (string, 0);
986 else
987 sv_utf8_upgrade (string);
988
989 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
990
991 dec.flags = flags;
992 dec.cur = SvPVX (string);
993 dec.end = SvEND (string);
994 dec.err = 0;
995 dec.depth = 0;
996 dec.maxdepth = DEC_DEPTH (dec.flags);
997
998 *dec.end = 0; // this should basically be a nop, too, but make sure its there
999 sv = decode_sv (&dec);
1000
1001 if (!sv)
1002 {
1003 IV offset = dec.flags & F_UTF8
1004 ? dec.cur - SvPVX (string)
1005 : utf8_distance (dec.cur, SvPVX (string));
1006 SV *uni = sv_newmortal ();
1007
1008 // horrible hack to silence warning inside pv_uni_display
1009 COP cop = *PL_curcop;
1010 cop.cop_warnings = pWARN_NONE;
1011 ENTER;
1012 SAVEVPTR (PL_curcop);
1013 PL_curcop = &cop;
1014 pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ);
1015 LEAVE;
1016
1017 croak ("%s, at character offset %d [\"%s\"]",
1018 dec.err,
1019 (int)offset,
1020 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
1021 }
1022
1023 sv = sv_2mortal (sv);
1024
1025 if (!(dec.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)");
1027
1028 return sv;
1029 }
1030
1031 /////////////////////////////////////////////////////////////////////////////
1032 // XS interface functions
1033
1034 MODULE = JSON::XS PACKAGE = JSON::XS
1035
1036 BOOT:
1037 {
1038 int i;
1039
1040 memset (decode_hexdigit, 0xff, 256);
1041
1042 for (i = 0; i < 256; ++i)
1043 decode_hexdigit [i] =
1044 i >= '0' && i <= '9' ? i - '0'
1045 : i >= 'a' && i <= 'f' ? i - 'a' + 10
1046 : i >= 'A' && i <= 'F' ? i - 'A' + 10
1047 : -1;
1048
1049 json_stash = gv_stashpv ("JSON::XS", 1);
1050 }
1051
1052 PROTOTYPES: DISABLE
1053
1054 SV *new (char *dummy)
1055 CODE:
1056 RETVAL = sv_bless (newRV_noinc (newSVuv (F_DEFAULT)), json_stash);
1057 OUTPUT:
1058 RETVAL
1059
1060 SV *ascii (SV *self, int enable = 1)
1061 ALIAS:
1062 ascii = F_ASCII
1063 utf8 = F_UTF8
1064 indent = F_INDENT
1065 canonical = F_CANONICAL
1066 space_before = F_SPACE_BEFORE
1067 space_after = F_SPACE_AFTER
1068 pretty = F_PRETTY
1069 allow_nonref = F_ALLOW_NONREF
1070 shrink = F_SHRINK
1071 CODE:
1072 {
1073 UV *uv = SvJSON (self);
1074 if (enable)
1075 *uv |= ix;
1076 else
1077 *uv &= ~ix;
1078
1079 RETVAL = newSVsv (self);
1080 }
1081 OUTPUT:
1082 RETVAL
1083
1084 SV *max_depth (SV *self, UV max_depth = 0x80000000UL)
1085 CODE:
1086 {
1087 UV *uv = SvJSON (self);
1088 UV log2 = 0;
1089
1090 if (max_depth > 0x80000000UL) max_depth = 0x80000000UL;
1091
1092 while ((1UL << log2) < max_depth)
1093 ++log2;
1094
1095 *uv = *uv & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1096
1097 RETVAL = newSVsv (self);
1098 }
1099 OUTPUT:
1100 RETVAL
1101
1102 void encode (SV *self, SV *scalar)
1103 PPCODE:
1104 XPUSHs (encode_json (scalar, *SvJSON (self)));
1105
1106 void decode (SV *self, SV *jsonstr)
1107 PPCODE:
1108 XPUSHs (decode_json (jsonstr, *SvJSON (self)));
1109
1110 PROTOTYPES: ENABLE
1111
1112 void to_json (SV *scalar)
1113 ALIAS:
1114 objToJson = 0
1115 PPCODE:
1116 XPUSHs (encode_json (scalar, F_DEFAULT | F_UTF8));
1117
1118 void from_json (SV *jsonstr)
1119 ALIAS:
1120 jsonToObj = 0
1121 PPCODE:
1122 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8));
1123