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