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