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