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