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