ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/JSON-XS/XS.xs
Revision: 1.44
Committed: Mon Jun 25 04:08:17 2007 UTC (16 years, 10 months ago) by root
Branch: MAIN
Changes since 1.43: +83 -27 lines
Log Message:
*** empty log message ***

File Contents

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