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