ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/JSON-XS/XS.xs
Revision: 1.76
Committed: Thu Mar 20 00:56:37 2008 UTC (16 years, 2 months ago) by root
Branch: MAIN
Changes since 1.75: +8 -2 lines
Log Message:
prepare for last phase of api change

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