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