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