ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/JSON-XS/XS.xs
Revision: 1.40
Committed: Tue Jun 12 01:27:02 2007 UTC (16 years, 11 months ago) by root
Branch: MAIN
Changes since 1.39: +12 -9 lines
Log Message:
cleanup

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