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