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