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