ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/JSON-XS/XS.xs
Revision: 1.134
Committed: Thu Nov 15 20:13:03 2018 UTC (5 years, 6 months ago) by root
Branch: MAIN
Changes since 1.133: +15 -8 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.130 #include <inttypes.h>
12 root 1.26
13     #if defined(__BORLANDC__) || defined(_MSC_VER)
14     # define snprintf _snprintf // C compilers have this in stdio.h
15     #endif
16 root 1.1
17 root 1.41 // some old perls do not have this, try to make it work, no
18 root 1.99 // guarantees, though. if it breaks, you get to keep the pieces.
19 root 1.41 #ifndef UTF8_MAXBYTES
20     # define UTF8_MAXBYTES 13
21     #endif
22    
23 root 1.122 // compatibility with perl <5.18
24     #ifndef HvNAMELEN_get
25     # define HvNAMELEN_get(hv) strlen (HvNAME (hv))
26     #endif
27     #ifndef HvNAMELEN
28     # define HvNAMELEN(hv) HvNAMELEN_get (hv)
29     #endif
30     #ifndef HvNAMEUTF8
31     # define HvNAMEUTF8(hv) 0
32     #endif
33    
34 root 1.102 // three extra for rounding, sign, and end of string
35     #define IVUV_MAXCHARS (sizeof (UV) * CHAR_BIT * 28 / 93 + 3)
36 root 1.75
37 root 1.44 #define F_ASCII 0x00000001UL
38     #define F_LATIN1 0x00000002UL
39     #define F_UTF8 0x00000004UL
40     #define F_INDENT 0x00000008UL
41     #define F_CANONICAL 0x00000010UL
42     #define F_SPACE_BEFORE 0x00000020UL
43     #define F_SPACE_AFTER 0x00000040UL
44     #define F_ALLOW_NONREF 0x00000100UL
45     #define F_SHRINK 0x00000200UL
46     #define F_ALLOW_BLESSED 0x00000400UL
47 root 1.49 #define F_CONV_BLESSED 0x00000800UL
48 root 1.63 #define F_RELAXED 0x00001000UL
49 root 1.84 #define F_ALLOW_UNKNOWN 0x00002000UL
50 root 1.119 #define F_ALLOW_TAGS 0x00004000UL
51 root 1.49 #define F_HOOK 0x00080000UL // some hooks exist, so slow-path processing
52 root 1.18
53 root 1.2 #define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER
54 root 1.1
55 root 1.134 #define INIT_SIZE 64 // initial scalar size to be allocated
56 root 1.12 #define INDENT_STEP 3 // spaces per indentation level
57    
58 root 1.38 #define SHORT_STRING_LEN 16384 // special-case strings of up to this size
59 root 1.1
60 root 1.108 #define DECODE_WANTS_OCTETS(json) ((json)->flags & F_UTF8)
61    
62 root 1.1 #define SB do {
63     #define SE } while (0)
64    
65 root 1.35 #if __GNUC__ >= 3
66 root 1.71 # define expect(expr,value) __builtin_expect ((expr), (value))
67     # define INLINE static inline
68 root 1.35 #else
69     # define expect(expr,value) (expr)
70 root 1.71 # define INLINE static
71 root 1.35 #endif
72    
73     #define expect_false(expr) expect ((expr) != 0, 0)
74     #define expect_true(expr) expect ((expr) != 0, 1)
75    
76 root 1.72 #define IN_RANGE_INC(type,val,beg,end) \
77     ((unsigned type)((unsigned type)(val) - (unsigned type)(beg)) \
78     <= (unsigned type)((unsigned type)(end) - (unsigned type)(beg)))
79    
80 root 1.85 #define ERR_NESTING_EXCEEDED "json text or perl structure exceeds maximum nesting level (max_depth set too low?)"
81    
82 root 1.57 #ifdef USE_ITHREADS
83 root 1.133 # define JSON_STASH (expect_true (json_stash) ? json_stash : gv_stashpv ("JSON::XS", 1))
84     # define BOOL_STASH (expect_true (bool_stash) ? bool_stash : gv_stashpv ("Types::Serialiser::Boolean", 1))
85     # define GET_BOOL(value) (expect_true (bool_ ## value) ? bool_ ## value : get_bool ("Types::Serialiser::" # value))
86 root 1.57 #else
87 root 1.59 # define JSON_STASH json_stash
88 root 1.126 # define BOOL_STASH bool_stash
89 root 1.133 # define GET_BOOL(value) bool_ ## value
90 root 1.57 #endif
91    
92 root 1.115 // the amount of HEs to allocate on the stack, when sorting keys
93     #define STACK_HES 64
94    
95 root 1.126 static HV *json_stash, *bool_stash; // JSON::XS::, Types::Serialiser::Boolean::
96 root 1.133 static SV *bool_false, *bool_true;
97     static SV *sv_json;
98 root 1.1
99 root 1.77 enum {
100     INCR_M_WS = 0, // initial whitespace skipping, must be 0
101     INCR_M_STR, // inside string
102     INCR_M_BS, // inside backslash
103 root 1.103 INCR_M_C0, // inside comment in initial whitespace sequence
104     INCR_M_C1, // inside comment in other places
105 root 1.77 INCR_M_JSON // outside anything, count nesting
106     };
107    
108 root 1.88 #define INCR_DONE(json) ((json)->incr_nest <= 0 && (json)->incr_mode == INCR_M_JSON)
109 root 1.77
110 root 1.48 typedef struct {
111 root 1.47 U32 flags;
112 root 1.85 U32 max_depth;
113     STRLEN max_size;
114    
115 root 1.52 SV *cb_object;
116     HV *cb_sk_object;
117 root 1.77
118     // for the incremental parser
119     SV *incr_text; // the source text so far
120     STRLEN incr_pos; // the current offset into the text
121 root 1.88 int incr_nest; // {[]}-nesting level
122 root 1.85 unsigned char incr_mode;
123 root 1.133
124     SV *v_false, *v_true;
125 root 1.48 } JSON;
126 root 1.47
127 root 1.85 INLINE void
128     json_init (JSON *json)
129     {
130     Zero (json, 1, JSON);
131     json->max_depth = 512;
132     }
133    
134 root 1.12 /////////////////////////////////////////////////////////////////////////////
135     // utility functions
136 root 1.1
137 root 1.83 INLINE SV *
138     get_bool (const char *name)
139     {
140     SV *sv = get_sv (name, 1);
141    
142     SvREADONLY_on (sv);
143     SvREADONLY_on (SvRV (sv));
144    
145     return sv;
146     }
147    
148 root 1.71 INLINE void
149 root 1.7 shrink (SV *sv)
150     {
151     sv_utf8_downgrade (sv, 1);
152 root 1.87
153 root 1.12 if (SvLEN (sv) > SvCUR (sv) + 1)
154     {
155 root 1.7 #ifdef SvPV_shrink_to_cur
156 root 1.12 SvPV_shrink_to_cur (sv);
157     #elif defined (SvPV_renew)
158     SvPV_renew (sv, SvCUR (sv) + 1);
159 root 1.7 #endif
160 root 1.12 }
161 root 1.7 }
162    
163 root 1.131 /* adds two STRLENs together, slow, and with paranoia */
164     STRLEN
165     strlen_sum (STRLEN l1, STRLEN l2)
166     {
167     size_t sum = l1 + l2;
168    
169     if (sum < (size_t)l2 || sum != (size_t)(STRLEN)sum)
170     croak ("JSON::XS: string size overflow");
171    
172     return sum;
173     }
174    
175     /* similar to SvGROW, but somewhat safer and guarantees exponential realloc strategy */
176     static char *
177     json_sv_grow (SV *sv, size_t len1, size_t len2)
178     {
179     len1 = strlen_sum (len1, len2);
180     len1 = strlen_sum (len1, len1 >> 1);
181    
182     if (len1 > 4096 - 24)
183     len1 = (len1 | 4095) - 24;
184    
185     return SvGROW (sv, len1);
186     }
187    
188 root 1.132 // decode a utf-8 character and return it, or (UV)-1 in
189 root 1.13 // case of an error.
190     // we special-case "safe" characters from U+80 .. U+7FF,
191     // but use the very good perl function to parse anything else.
192     // note that we never call this function for a ascii codepoints
193 root 1.71 INLINE UV
194 root 1.13 decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
195     {
196 root 1.72 if (expect_true (len >= 2
197     && IN_RANGE_INC (char, s[0], 0xc2, 0xdf)
198     && IN_RANGE_INC (char, s[1], 0x80, 0xbf)))
199 root 1.13 {
200     *clen = 2;
201     return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
202     }
203     else
204 root 1.72 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY);
205     }
206    
207     // likewise for encoding, also never called for ascii codepoints
208     // this function takes advantage of this fact, although current gccs
209     // seem to optimise the check for >= 0x80 away anyways
210     INLINE unsigned char *
211     encode_utf8 (unsigned char *s, UV ch)
212     {
213 root 1.74 if (expect_false (ch < 0x000080))
214     *s++ = ch;
215     else if (expect_true (ch < 0x000800))
216     *s++ = 0xc0 | ( ch >> 6),
217     *s++ = 0x80 | ( ch & 0x3f);
218     else if ( ch < 0x010000)
219     *s++ = 0xe0 | ( ch >> 12),
220     *s++ = 0x80 | ((ch >> 6) & 0x3f),
221     *s++ = 0x80 | ( ch & 0x3f);
222     else if ( ch < 0x110000)
223     *s++ = 0xf0 | ( ch >> 18),
224     *s++ = 0x80 | ((ch >> 12) & 0x3f),
225     *s++ = 0x80 | ((ch >> 6) & 0x3f),
226     *s++ = 0x80 | ( ch & 0x3f);
227 root 1.72
228     return s;
229 root 1.13 }
230    
231 root 1.96 // convert offset pointer to character index, sv must be string
232     static STRLEN
233     ptr_to_index (SV *sv, char *offset)
234     {
235     return SvUTF8 (sv)
236     ? utf8_distance (offset, SvPVX (sv))
237     : offset - SvPVX (sv);
238     }
239    
240 root 1.1 /////////////////////////////////////////////////////////////////////////////
241 root 1.104 // fp hell
242    
243     // scan a group of digits, and a trailing exponent
244     static void
245 root 1.106 json_atof_scan1 (const char *s, NV *accum, int *expo, int postdp, int maxdepth)
246 root 1.104 {
247     UV uaccum = 0;
248     int eaccum = 0;
249    
250 root 1.106 // if we recurse too deep, skip all remaining digits
251     // to avoid a stack overflow attack
252     if (expect_false (--maxdepth <= 0))
253     while (((U8)*s - '0') < 10)
254     ++s;
255    
256 root 1.104 for (;;)
257     {
258     U8 dig = (U8)*s - '0';
259    
260     if (expect_false (dig >= 10))
261     {
262     if (dig == (U8)((U8)'.' - (U8)'0'))
263     {
264     ++s;
265 root 1.106 json_atof_scan1 (s, accum, expo, 1, maxdepth);
266 root 1.104 }
267     else if ((dig | ' ') == 'e' - '0')
268     {
269     int exp2 = 0;
270     int neg = 0;
271    
272     ++s;
273    
274     if (*s == '-')
275     {
276     ++s;
277     neg = 1;
278     }
279     else if (*s == '+')
280     ++s;
281    
282     while ((dig = (U8)*s - '0') < 10)
283     exp2 = exp2 * 10 + *s++ - '0';
284    
285     *expo += neg ? -exp2 : exp2;
286     }
287    
288     break;
289     }
290    
291     ++s;
292    
293     uaccum = uaccum * 10 + dig;
294     ++eaccum;
295    
296     // if we have too many digits, then recurse for more
297     // we actually do this for rather few digits
298     if (uaccum >= (UV_MAX - 9) / 10)
299     {
300     if (postdp) *expo -= eaccum;
301 root 1.106 json_atof_scan1 (s, accum, expo, postdp, maxdepth);
302 root 1.104 if (postdp) *expo += eaccum;
303    
304     break;
305     }
306     }
307    
308 root 1.105 // this relies greatly on the quality of the pow ()
309     // implementation of the platform, but a good
310     // implementation is hard to beat.
311 root 1.110 // (IEEE 754 conformant ones are required to be exact)
312 root 1.104 if (postdp) *expo -= eaccum;
313 root 1.105 *accum += uaccum * Perl_pow (10., *expo);
314 root 1.104 *expo += eaccum;
315     }
316    
317     static NV
318     json_atof (const char *s)
319     {
320     NV accum = 0.;
321     int expo = 0;
322     int neg = 0;
323    
324     if (*s == '-')
325     {
326     ++s;
327     neg = 1;
328     }
329    
330 root 1.106 // a recursion depth of ten gives us >>500 bits
331     json_atof_scan1 (s, &accum, &expo, 0, 10);
332 root 1.104
333     return neg ? -accum : accum;
334     }
335 root 1.126
336     // target of scalar reference is bool? -1 == nope, 0 == false, 1 == true
337     static int
338     ref_bool_type (SV *sv)
339     {
340     svtype svt = SvTYPE (sv);
341    
342     if (svt < SVt_PVAV)
343     {
344     STRLEN len = 0;
345     char *pv = svt ? SvPV (sv, len) : 0;
346    
347     if (len == 1)
348     if (*pv == '1')
349     return 1;
350     else if (*pv == '0')
351     return 0;
352     }
353    
354     return -1;
355     }
356    
357     // returns whether scalar is not a reference in the sense of allow_nonref
358     static int
359     json_nonref (SV *scalar)
360     {
361     if (!SvROK (scalar))
362     return 1;
363    
364     scalar = SvRV (scalar);
365    
366 root 1.128 if (SvTYPE (scalar) >= SVt_PVMG)
367     {
368     if (SvSTASH (scalar) == bool_stash)
369     return 1;
370 root 1.126
371 root 1.128 if (!SvOBJECT (scalar) && ref_bool_type (scalar) >= 0)
372     return 1;
373     }
374 root 1.126
375     return 0;
376     }
377    
378 root 1.104 /////////////////////////////////////////////////////////////////////////////
379 root 1.12 // encoder
380    
381     // structure used for encoding JSON
382     typedef struct
383     {
384     char *cur; // SvPVX (sv) + current output position
385     char *end; // SvEND (sv)
386     SV *sv; // result scalar
387 root 1.48 JSON json;
388 root 1.18 U32 indent; // indentation level
389 root 1.71 UV limit; // escape character values >= this value when encoding
390 root 1.12 } enc_t;
391 root 1.1
392 root 1.71 INLINE void
393 root 1.1 need (enc_t *enc, STRLEN len)
394     {
395 root 1.130 if (expect_false ((uintptr_t)(enc->end - enc->cur) < len))
396 root 1.1 {
397 root 1.93 STRLEN cur = enc->cur - (char *)SvPVX (enc->sv);
398 root 1.131 char *buf = json_sv_grow (enc->sv, cur, len);
399     enc->cur = buf + cur;
400     enc->end = buf + SvLEN (enc->sv) - 1;
401 root 1.1 }
402     }
403    
404 root 1.71 INLINE void
405 root 1.1 encode_ch (enc_t *enc, char ch)
406     {
407     need (enc, 1);
408     *enc->cur++ = ch;
409     }
410    
411     static void
412     encode_str (enc_t *enc, char *str, STRLEN len, int is_utf8)
413     {
414     char *end = str + len;
415    
416 root 1.4 need (enc, len);
417    
418 root 1.1 while (str < end)
419     {
420     unsigned char ch = *(unsigned char *)str;
421 root 1.4
422 root 1.35 if (expect_true (ch >= 0x20 && ch < 0x80)) // most common case
423 root 1.4 {
424 root 1.35 if (expect_false (ch == '"')) // but with slow exceptions
425 root 1.6 {
426 root 1.131 need (enc, len + 1);
427 root 1.6 *enc->cur++ = '\\';
428     *enc->cur++ = '"';
429     }
430 root 1.35 else if (expect_false (ch == '\\'))
431 root 1.6 {
432 root 1.131 need (enc, len + 1);
433 root 1.6 *enc->cur++ = '\\';
434     *enc->cur++ = '\\';
435     }
436     else
437     *enc->cur++ = ch;
438    
439 root 1.4 ++str;
440 root 1.1 }
441     else
442     {
443 root 1.6 switch (ch)
444 root 1.1 {
445 root 1.131 case '\010': need (enc, len + 1); *enc->cur++ = '\\'; *enc->cur++ = 'b'; ++str; break;
446     case '\011': need (enc, len + 1); *enc->cur++ = '\\'; *enc->cur++ = 't'; ++str; break;
447     case '\012': need (enc, len + 1); *enc->cur++ = '\\'; *enc->cur++ = 'n'; ++str; break;
448     case '\014': need (enc, len + 1); *enc->cur++ = '\\'; *enc->cur++ = 'f'; ++str; break;
449     case '\015': need (enc, len + 1); *enc->cur++ = '\\'; *enc->cur++ = 'r'; ++str; break;
450 root 1.1
451 root 1.6 default:
452 root 1.1 {
453 root 1.6 STRLEN clen;
454     UV uch;
455    
456     if (is_utf8)
457     {
458 root 1.13 uch = decode_utf8 (str, end - str, &clen);
459 root 1.6 if (clen == (STRLEN)-1)
460 root 1.9 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str);
461 root 1.6 }
462     else
463     {
464     uch = ch;
465     clen = 1;
466     }
467    
468 root 1.72 if (uch < 0x80/*0x20*/ || uch >= enc->limit)
469 root 1.6 {
470 root 1.74 if (uch >= 0x10000UL)
471 root 1.6 {
472 root 1.74 if (uch >= 0x110000UL)
473 root 1.71 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
474    
475 root 1.131 need (enc, len + 11);
476 root 1.6 sprintf (enc->cur, "\\u%04x\\u%04x",
477 root 1.10 (int)((uch - 0x10000) / 0x400 + 0xD800),
478     (int)((uch - 0x10000) % 0x400 + 0xDC00));
479 root 1.6 enc->cur += 12;
480     }
481     else
482     {
483 root 1.131 need (enc, len + 5);
484 root 1.6 *enc->cur++ = '\\';
485     *enc->cur++ = 'u';
486 root 1.91 *enc->cur++ = PL_hexdigit [ uch >> 12 ];
487     *enc->cur++ = PL_hexdigit [(uch >> 8) & 15];
488     *enc->cur++ = PL_hexdigit [(uch >> 4) & 15];
489     *enc->cur++ = PL_hexdigit [(uch >> 0) & 15];
490 root 1.6 }
491 root 1.4
492 root 1.6 str += clen;
493     }
494 root 1.47 else if (enc->json.flags & F_LATIN1)
495 root 1.30 {
496     *enc->cur++ = uch;
497     str += clen;
498     }
499 root 1.6 else if (is_utf8)
500     {
501 root 1.131 need (enc, len + clen);
502 root 1.6 do
503     {
504     *enc->cur++ = *str++;
505     }
506     while (--clen);
507     }
508     else
509     {
510 root 1.131 need (enc, len + UTF8_MAXBYTES - 1); // never more than 11 bytes needed
511 root 1.72 enc->cur = encode_utf8 (enc->cur, uch);
512 root 1.6 ++str;
513     }
514 root 1.5 }
515 root 1.4 }
516 root 1.1 }
517    
518     --len;
519     }
520     }
521    
522 root 1.71 INLINE void
523 root 1.12 encode_indent (enc_t *enc)
524     {
525 root 1.47 if (enc->json.flags & F_INDENT)
526 root 1.12 {
527     int spaces = enc->indent * INDENT_STEP;
528    
529     need (enc, spaces);
530     memset (enc->cur, ' ', spaces);
531     enc->cur += spaces;
532     }
533     }
534    
535 root 1.71 INLINE void
536 root 1.12 encode_space (enc_t *enc)
537     {
538     need (enc, 1);
539     encode_ch (enc, ' ');
540     }
541    
542 root 1.71 INLINE void
543 root 1.12 encode_nl (enc_t *enc)
544     {
545 root 1.47 if (enc->json.flags & F_INDENT)
546 root 1.12 {
547     need (enc, 1);
548     encode_ch (enc, '\n');
549     }
550     }
551    
552 root 1.71 INLINE void
553 root 1.12 encode_comma (enc_t *enc)
554     {
555     encode_ch (enc, ',');
556 root 1.1
557 root 1.47 if (enc->json.flags & F_INDENT)
558 root 1.12 encode_nl (enc);
559 root 1.47 else if (enc->json.flags & F_SPACE_AFTER)
560 root 1.12 encode_space (enc);
561     }
562 root 1.1
563     static void encode_sv (enc_t *enc, SV *sv);
564    
565     static void
566     encode_av (enc_t *enc, AV *av)
567     {
568     int i, len = av_len (av);
569    
570 root 1.85 if (enc->indent >= enc->json.max_depth)
571     croak (ERR_NESTING_EXCEEDED);
572 root 1.21
573 root 1.65 encode_ch (enc, '[');
574 root 1.117
575 root 1.65 if (len >= 0)
576 root 1.1 {
577 root 1.65 encode_nl (enc); ++enc->indent;
578 root 1.55
579 root 1.65 for (i = 0; i <= len; ++i)
580     {
581     SV **svp = av_fetch (av, i, 0);
582 root 1.55
583 root 1.65 encode_indent (enc);
584 root 1.1
585 root 1.65 if (svp)
586     encode_sv (enc, *svp);
587     else
588     encode_str (enc, "null", 4, 0);
589 root 1.1
590 root 1.65 if (i < len)
591     encode_comma (enc);
592     }
593 root 1.1
594 root 1.65 encode_nl (enc); --enc->indent; encode_indent (enc);
595     }
596 root 1.117
597 root 1.65 encode_ch (enc, ']');
598 root 1.1 }
599    
600     static void
601 root 1.61 encode_hk (enc_t *enc, HE *he)
602 root 1.1 {
603     encode_ch (enc, '"');
604    
605     if (HeKLEN (he) == HEf_SVKEY)
606     {
607     SV *sv = HeSVKEY (he);
608     STRLEN len;
609 root 1.4 char *str;
610 root 1.117
611 root 1.4 SvGETMAGIC (sv);
612     str = SvPV (sv, len);
613 root 1.1
614     encode_str (enc, str, len, SvUTF8 (sv));
615     }
616     else
617     encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he));
618    
619     encode_ch (enc, '"');
620    
621 root 1.47 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc);
622 root 1.1 encode_ch (enc, ':');
623 root 1.47 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc);
624 root 1.1 }
625    
626     // compare hash entries, used when all keys are bytestrings
627     static int
628     he_cmp_fast (const void *a_, const void *b_)
629     {
630     int cmp;
631    
632     HE *a = *(HE **)a_;
633     HE *b = *(HE **)b_;
634    
635     STRLEN la = HeKLEN (a);
636     STRLEN lb = HeKLEN (b);
637    
638 root 1.61 if (!(cmp = memcmp (HeKEY (b), HeKEY (a), lb < la ? lb : la)))
639     cmp = lb - la;
640 root 1.1
641     return cmp;
642     }
643    
644     // compare hash entries, used when some keys are sv's or utf-x
645     static int
646     he_cmp_slow (const void *a, const void *b)
647     {
648 root 1.61 return sv_cmp (HeSVKEY_force (*(HE **)b), HeSVKEY_force (*(HE **)a));
649 root 1.1 }
650    
651     static void
652     encode_hv (enc_t *enc, HV *hv)
653     {
654 root 1.61 HE *he;
655 root 1.1
656 root 1.85 if (enc->indent >= enc->json.max_depth)
657     croak (ERR_NESTING_EXCEEDED);
658 root 1.21
659 root 1.65 encode_ch (enc, '{');
660 root 1.1
661 root 1.61 // for canonical output we have to sort by keys first
662     // actually, this is mostly due to the stupid so-called
663 root 1.92 // security workaround added somewhere in 5.8.x
664 root 1.61 // that randomises hash orderings
665 root 1.98 if (enc->json.flags & F_CANONICAL && !SvRMAGICAL (hv))
666 root 1.1 {
667 root 1.61 int count = hv_iterinit (hv);
668    
669     if (SvMAGICAL (hv))
670     {
671     // need to count by iterating. could improve by dynamically building the vector below
672     // but I don't care for the speed of this special case.
673     // note also that we will run into undefined behaviour when the two iterations
674     // do not result in the same count, something I might care for in some later release.
675    
676     count = 0;
677     while (hv_iternext (hv))
678     ++count;
679    
680     hv_iterinit (hv);
681     }
682    
683     if (count)
684 root 1.1 {
685 root 1.61 int i, fast = 1;
686 root 1.115 HE *hes_stack [STACK_HES];
687     HE **hes = hes_stack;
688 root 1.117
689 root 1.115 // allocate larger arrays on the heap
690     if (count > STACK_HES)
691     {
692     SV *sv = sv_2mortal (NEWSV (0, count * sizeof (*hes)));
693     hes = (HE **)SvPVX (sv);
694     }
695 root 1.1
696     i = 0;
697     while ((he = hv_iternext (hv)))
698     {
699     hes [i++] = he;
700     if (HeKLEN (he) < 0 || HeKUTF8 (he))
701     fast = 0;
702     }
703    
704     assert (i == count);
705    
706     if (fast)
707     qsort (hes, count, sizeof (HE *), he_cmp_fast);
708     else
709     {
710 root 1.8 // hack to forcefully disable "use bytes"
711     COP cop = *PL_curcop;
712 root 1.1 cop.op_private = 0;
713 root 1.8
714     ENTER;
715     SAVETMPS;
716    
717     SAVEVPTR (PL_curcop);
718 root 1.1 PL_curcop = &cop;
719    
720     qsort (hes, count, sizeof (HE *), he_cmp_slow);
721 root 1.8
722 root 1.1 FREETMPS;
723 root 1.8 LEAVE;
724 root 1.1 }
725    
726 root 1.65 encode_nl (enc); ++enc->indent;
727    
728 root 1.61 while (count--)
729 root 1.1 {
730 root 1.12 encode_indent (enc);
731 root 1.61 he = hes [count];
732     encode_hk (enc, he);
733 root 1.62 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
734 root 1.1
735 root 1.61 if (count)
736 root 1.12 encode_comma (enc);
737 root 1.1 }
738 root 1.65
739     encode_nl (enc); --enc->indent; encode_indent (enc);
740 root 1.1 }
741 root 1.61 }
742     else
743     {
744     if (hv_iterinit (hv) || SvMAGICAL (hv))
745     if ((he = hv_iternext (hv)))
746 root 1.65 {
747     encode_nl (enc); ++enc->indent;
748    
749     for (;;)
750     {
751     encode_indent (enc);
752     encode_hk (enc, he);
753     encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
754    
755     if (!(he = hv_iternext (hv)))
756     break;
757 root 1.1
758 root 1.65 encode_comma (enc);
759     }
760 root 1.1
761 root 1.65 encode_nl (enc); --enc->indent; encode_indent (enc);
762     }
763 root 1.61 }
764 root 1.1
765 root 1.65 encode_ch (enc, '}');
766 root 1.1 }
767    
768 root 1.21 // encode objects, arrays and special \0=false and \1=true values.
769     static void
770     encode_rv (enc_t *enc, SV *sv)
771     {
772 root 1.25 svtype svt;
773 root 1.120 GV *method;
774 root 1.25
775 root 1.21 SvGETMAGIC (sv);
776 root 1.25 svt = SvTYPE (sv);
777 root 1.21
778 root 1.44 if (expect_false (SvOBJECT (sv)))
779     {
780 root 1.119 HV *stash = SvSTASH (sv);
781 root 1.57
782 root 1.126 if (stash == bool_stash)
783 root 1.44 {
784 root 1.133 if (SvIV (sv)) encode_str (enc, "true" , 4, 0);
785     else encode_str (enc, "false", 5, 0);
786 root 1.44 }
787 root 1.120 else if ((enc->json.flags & F_ALLOW_TAGS) && (method = gv_fetchmethod_autoload (stash, "FREEZE", 0)))
788 root 1.44 {
789 root 1.120 int count;
790     dSP;
791    
792 root 1.125 ENTER; SAVETMPS;
793     PUSHMARK (SP);
794 root 1.120 EXTEND (SP, 2);
795     // we re-bless the reference to get overload and other niceties right
796     PUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), stash));
797     PUSHs (sv_json);
798    
799     PUTBACK;
800     count = call_sv ((SV *)GvCV (method), G_ARRAY);
801     SPAGAIN;
802    
803     // catch this surprisingly common error
804     if (SvROK (TOPs) && SvRV (TOPs) == sv)
805 root 1.123 croak ("%s::FREEZE method returned same object as was passed instead of a new one", HvNAME (SvSTASH (sv)));
806 root 1.120
807     encode_ch (enc, '(');
808     encode_ch (enc, '"');
809     encode_str (enc, HvNAME (stash), HvNAMELEN (stash), HvNAMEUTF8 (stash));
810     encode_ch (enc, '"');
811     encode_ch (enc, ')');
812     encode_ch (enc, '[');
813 root 1.119
814 root 1.134 if (count)
815 root 1.44 {
816 root 1.134 int i;
817 root 1.119
818 root 1.134 for (i = 0; i < count - 1; ++i)
819     {
820     encode_sv (enc, SP[i + 1 - count]);
821     encode_ch (enc, ',');
822     }
823    
824     encode_sv (enc, TOPs);
825     SP -= count;
826 root 1.120 }
827 root 1.119
828 root 1.120 encode_ch (enc, ']');
829 root 1.119
830 root 1.120 FREETMPS; LEAVE;
831 root 1.119 }
832 root 1.120 else if ((enc->json.flags & F_CONV_BLESSED) && (method = gv_fetchmethod_autoload (stash, "TO_JSON", 0)))
833 root 1.119 {
834 root 1.120 dSP;
835 root 1.119
836 root 1.125 ENTER; SAVETMPS;
837     PUSHMARK (SP);
838 root 1.120 // we re-bless the reference to get overload and other niceties right
839     XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), stash));
840 root 1.119
841 root 1.120 // calling with G_SCALAR ensures that we always get a 1 return value
842     PUTBACK;
843     call_sv ((SV *)GvCV (method), G_SCALAR);
844     SPAGAIN;
845    
846     // catch this surprisingly common error
847     if (SvROK (TOPs) && SvRV (TOPs) == sv)
848     croak ("%s::TO_JSON method returned same object as was passed instead of a new one", HvNAME (SvSTASH (sv)));
849 root 1.44
850 root 1.120 sv = POPs;
851     PUTBACK;
852 root 1.53
853 root 1.120 encode_sv (enc, sv);
854 root 1.44
855 root 1.120 FREETMPS; LEAVE;
856 root 1.44 }
857 root 1.119 else if (enc->json.flags & F_ALLOW_BLESSED)
858     encode_str (enc, "null", 4, 0);
859     else
860 root 1.120 croak ("encountered object '%s', but neither allow_blessed, convert_blessed nor allow_tags settings are enabled (or TO_JSON/FREEZE method missing)",
861 root 1.119 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
862 root 1.44 }
863     else if (svt == SVt_PVHV)
864 root 1.21 encode_hv (enc, (HV *)sv);
865     else if (svt == SVt_PVAV)
866     encode_av (enc, (AV *)sv);
867     else if (svt < SVt_PVAV)
868     {
869 root 1.126 int bool_type = ref_bool_type (sv);
870 root 1.50
871 root 1.126 if (bool_type == 1)
872 root 1.51 encode_str (enc, "true", 4, 0);
873 root 1.126 else if (bool_type == 0)
874 root 1.21 encode_str (enc, "false", 5, 0);
875 root 1.84 else if (enc->json.flags & F_ALLOW_UNKNOWN)
876     encode_str (enc, "null", 4, 0);
877 root 1.21 else
878     croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1",
879     SvPV_nolen (sv_2mortal (newRV_inc (sv))));
880     }
881 root 1.84 else if (enc->json.flags & F_ALLOW_UNKNOWN)
882     encode_str (enc, "null", 4, 0);
883 root 1.21 else
884     croak ("encountered %s, but JSON can only represent references to arrays or hashes",
885     SvPV_nolen (sv_2mortal (newRV_inc (sv))));
886     }
887    
888 root 1.1 static void
889     encode_sv (enc_t *enc, SV *sv)
890     {
891 root 1.4 SvGETMAGIC (sv);
892    
893 root 1.1 if (SvPOKp (sv))
894     {
895     STRLEN len;
896     char *str = SvPV (sv, len);
897     encode_ch (enc, '"');
898     encode_str (enc, str, len, SvUTF8 (sv));
899     encode_ch (enc, '"');
900     }
901     else if (SvNOKp (sv))
902     {
903 root 1.39 // trust that perl will do the right thing w.r.t. JSON syntax.
904 root 1.1 need (enc, NV_DIG + 32);
905     Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
906     enc->cur += strlen (enc->cur);
907     }
908     else if (SvIOKp (sv))
909     {
910 root 1.74 // we assume we can always read an IV as a UV and vice versa
911     // we assume two's complement
912     // we assume no aliasing issues in the union
913 root 1.75 if (SvIsUV (sv) ? SvUVX (sv) <= 59000
914     : SvIVX (sv) <= 59000 && SvIVX (sv) >= -59000)
915 root 1.35 {
916     // optimise the "small number case"
917     // code will likely be branchless and use only a single multiplication
918 root 1.74 // works for numbers up to 59074
919     I32 i = SvIVX (sv);
920 root 1.35 U32 u;
921 root 1.39 char digit, nz = 0;
922 root 1.35
923     need (enc, 6);
924    
925     *enc->cur = '-'; enc->cur += i < 0 ? 1 : 0;
926     u = i < 0 ? -i : i;
927    
928     // convert to 4.28 fixed-point representation
929     u = u * ((0xfffffff + 10000) / 10000); // 10**5, 5 fractional digits
930    
931 root 1.39 // now output digit by digit, each time masking out the integer part
932     // and multiplying by 5 while moving the decimal point one to the right,
933     // resulting in a net multiplication by 10.
934     // we always write the digit to memory but conditionally increment
935 root 1.75 // the pointer, to enable the use of conditional move instructions.
936     digit = u >> 28; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0xfffffffUL) * 5;
937     digit = u >> 27; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x7ffffffUL) * 5;
938     digit = u >> 26; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x3ffffffUL) * 5;
939     digit = u >> 25; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x1ffffffUL) * 5;
940 root 1.39 digit = u >> 24; *enc->cur = digit + '0'; enc->cur += 1; // correctly generate '0'
941 root 1.35 }
942 root 1.75 else
943     {
944     // large integer, use the (rather slow) snprintf way.
945     need (enc, IVUV_MAXCHARS);
946 root 1.114 enc->cur +=
947 root 1.75 SvIsUV(sv)
948     ? snprintf (enc->cur, IVUV_MAXCHARS, "%"UVuf, (UV)SvUVX (sv))
949     : snprintf (enc->cur, IVUV_MAXCHARS, "%"IVdf, (IV)SvIVX (sv));
950     }
951 root 1.1 }
952     else if (SvROK (sv))
953 root 1.21 encode_rv (enc, SvRV (sv));
954 root 1.84 else if (!SvOK (sv) || enc->json.flags & F_ALLOW_UNKNOWN)
955 root 1.1 encode_str (enc, "null", 4, 0);
956     else
957 root 1.117 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, check your input data",
958 root 1.113 SvPV_nolen (sv), (unsigned int)SvFLAGS (sv));
959 root 1.1 }
960    
961     static SV *
962 root 1.48 encode_json (SV *scalar, JSON *json)
963 root 1.1 {
964 root 1.25 enc_t enc;
965    
966 root 1.126 if (!(json->flags & F_ALLOW_NONREF) && json_nonref (scalar))
967 root 1.9 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)");
968 root 1.3
969 root 1.47 enc.json = *json;
970 root 1.12 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
971     enc.cur = SvPVX (enc.sv);
972     enc.end = SvEND (enc.sv);
973     enc.indent = 0;
974 root 1.71 enc.limit = enc.json.flags & F_ASCII ? 0x000080UL
975     : enc.json.flags & F_LATIN1 ? 0x000100UL
976 root 1.74 : 0x110000UL;
977 root 1.1
978     SvPOK_only (enc.sv);
979     encode_sv (&enc, scalar);
980 root 1.100 encode_nl (&enc);
981 root 1.1
982     SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
983 root 1.27 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings
984 root 1.6
985 root 1.47 if (!(enc.json.flags & (F_ASCII | F_LATIN1 | F_UTF8)))
986 root 1.30 SvUTF8_on (enc.sv);
987    
988 root 1.47 if (enc.json.flags & F_SHRINK)
989 root 1.7 shrink (enc.sv);
990    
991 root 1.1 return enc.sv;
992     }
993    
994     /////////////////////////////////////////////////////////////////////////////
995 root 1.12 // decoder
996 root 1.1
997 root 1.12 // structure used for decoding JSON
998     typedef struct
999     {
1000     char *cur; // current parser pointer
1001     char *end; // end of input string
1002     const char *err; // parse error, if != 0
1003 root 1.48 JSON json;
1004 root 1.18 U32 depth; // recursion depth
1005     U32 maxdepth; // recursion depth limit
1006 root 1.12 } dec_t;
1007    
1008 root 1.71 INLINE void
1009 root 1.64 decode_comment (dec_t *dec)
1010     {
1011     // only '#'-style comments allowed a.t.m.
1012    
1013     while (*dec->cur && *dec->cur != 0x0a && *dec->cur != 0x0d)
1014     ++dec->cur;
1015     }
1016    
1017 root 1.71 INLINE void
1018 root 1.12 decode_ws (dec_t *dec)
1019     {
1020     for (;;)
1021     {
1022     char ch = *dec->cur;
1023    
1024 root 1.64 if (ch > 0x20)
1025     {
1026     if (expect_false (ch == '#'))
1027     {
1028     if (dec->json.flags & F_RELAXED)
1029     decode_comment (dec);
1030     else
1031     break;
1032     }
1033     else
1034     break;
1035     }
1036     else if (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)
1037     break; // parse error, but let higher level handle it, gives better error messages
1038 root 1.63
1039 root 1.12 ++dec->cur;
1040 root 1.1 }
1041 root 1.12 }
1042 root 1.1
1043     #define ERR(reason) SB dec->err = reason; goto fail; SE
1044 root 1.18
1045 root 1.1 #define EXPECT_CH(ch) SB \
1046     if (*dec->cur != ch) \
1047     ERR (# ch " expected"); \
1048     ++dec->cur; \
1049     SE
1050    
1051 root 1.85 #define DEC_INC_DEPTH if (++dec->depth > dec->json.max_depth) ERR (ERR_NESTING_EXCEEDED)
1052 root 1.18 #define DEC_DEC_DEPTH --dec->depth
1053    
1054 root 1.1 static SV *decode_sv (dec_t *dec);
1055    
1056     static signed char decode_hexdigit[256];
1057    
1058     static UV
1059     decode_4hex (dec_t *dec)
1060     {
1061     signed char d1, d2, d3, d4;
1062 root 1.12 unsigned char *cur = (unsigned char *)dec->cur;
1063 root 1.1
1064 root 1.40 d1 = decode_hexdigit [cur [0]]; if (expect_false (d1 < 0)) ERR ("exactly four hexadecimal digits expected");
1065     d2 = decode_hexdigit [cur [1]]; if (expect_false (d2 < 0)) ERR ("exactly four hexadecimal digits expected");
1066     d3 = decode_hexdigit [cur [2]]; if (expect_false (d3 < 0)) ERR ("exactly four hexadecimal digits expected");
1067     d4 = decode_hexdigit [cur [3]]; if (expect_false (d4 < 0)) ERR ("exactly four hexadecimal digits expected");
1068 root 1.1
1069     dec->cur += 4;
1070    
1071     return ((UV)d1) << 12
1072     | ((UV)d2) << 8
1073     | ((UV)d3) << 4
1074     | ((UV)d4);
1075    
1076     fail:
1077     return (UV)-1;
1078     }
1079    
1080     static SV *
1081     decode_str (dec_t *dec)
1082     {
1083 root 1.12 SV *sv = 0;
1084 root 1.1 int utf8 = 0;
1085 root 1.38 char *dec_cur = dec->cur;
1086 root 1.1
1087 root 1.12 do
1088 root 1.1 {
1089 root 1.28 char buf [SHORT_STRING_LEN + UTF8_MAXBYTES];
1090 root 1.12 char *cur = buf;
1091 root 1.1
1092 root 1.12 do
1093 root 1.1 {
1094 root 1.38 unsigned char ch = *(unsigned char *)dec_cur++;
1095 root 1.12
1096 root 1.35 if (expect_false (ch == '"'))
1097 root 1.12 {
1098 root 1.38 --dec_cur;
1099 root 1.12 break;
1100     }
1101 root 1.35 else if (expect_false (ch == '\\'))
1102 root 1.1 {
1103 root 1.38 switch (*dec_cur)
1104 root 1.1 {
1105 root 1.12 case '\\':
1106     case '/':
1107 root 1.38 case '"': *cur++ = *dec_cur++; break;
1108 root 1.12
1109 root 1.38 case 'b': ++dec_cur; *cur++ = '\010'; break;
1110     case 't': ++dec_cur; *cur++ = '\011'; break;
1111     case 'n': ++dec_cur; *cur++ = '\012'; break;
1112     case 'f': ++dec_cur; *cur++ = '\014'; break;
1113     case 'r': ++dec_cur; *cur++ = '\015'; break;
1114 root 1.1
1115 root 1.12 case 'u':
1116 root 1.1 {
1117 root 1.12 UV lo, hi;
1118 root 1.38 ++dec_cur;
1119 root 1.1
1120 root 1.38 dec->cur = dec_cur;
1121 root 1.12 hi = decode_4hex (dec);
1122 root 1.38 dec_cur = dec->cur;
1123 root 1.12 if (hi == (UV)-1)
1124     goto fail;
1125 root 1.1
1126 root 1.12 // possibly a surrogate pair
1127     if (hi >= 0xd800)
1128     if (hi < 0xdc00)
1129     {
1130 root 1.38 if (dec_cur [0] != '\\' || dec_cur [1] != 'u')
1131 root 1.12 ERR ("missing low surrogate character in surrogate pair");
1132    
1133 root 1.38 dec_cur += 2;
1134 root 1.12
1135 root 1.38 dec->cur = dec_cur;
1136 root 1.12 lo = decode_4hex (dec);
1137 root 1.38 dec_cur = dec->cur;
1138 root 1.12 if (lo == (UV)-1)
1139     goto fail;
1140    
1141     if (lo < 0xdc00 || lo >= 0xe000)
1142     ERR ("surrogate pair expected");
1143    
1144     hi = (hi - 0xD800) * 0x400 + (lo - 0xDC00) + 0x10000;
1145     }
1146     else if (hi < 0xe000)
1147     ERR ("missing high surrogate character in surrogate pair");
1148 root 1.1
1149 root 1.12 if (hi >= 0x80)
1150     {
1151     utf8 = 1;
1152 root 1.1
1153 root 1.72 cur = encode_utf8 (cur, hi);
1154 root 1.12 }
1155     else
1156     *cur++ = hi;
1157 root 1.1 }
1158 root 1.12 break;
1159    
1160     default:
1161 root 1.38 --dec_cur;
1162 root 1.12 ERR ("illegal backslash escape sequence in string");
1163     }
1164     }
1165 root 1.74 else if (expect_true (ch >= 0x20 && ch < 0x80))
1166 root 1.12 *cur++ = ch;
1167     else if (ch >= 0x80)
1168     {
1169 root 1.25 STRLEN clen;
1170    
1171 root 1.38 --dec_cur;
1172 root 1.1
1173 root 1.101 decode_utf8 (dec_cur, dec->end - dec_cur, &clen);
1174 root 1.12 if (clen == (STRLEN)-1)
1175     ERR ("malformed UTF-8 character in JSON string");
1176 root 1.1
1177 root 1.12 do
1178 root 1.38 *cur++ = *dec_cur++;
1179 root 1.12 while (--clen);
1180 root 1.5
1181 root 1.12 utf8 = 1;
1182 root 1.1 }
1183 root 1.124 else if (ch == '\t' && dec->json.flags & F_RELAXED)
1184     *cur++ = ch;
1185 root 1.12 else
1186 root 1.23 {
1187 root 1.38 --dec_cur;
1188 root 1.12
1189 root 1.23 if (!ch)
1190 root 1.24 ERR ("unexpected end of string while parsing JSON string");
1191 root 1.23 else
1192 root 1.24 ERR ("invalid character encountered while parsing JSON string");
1193 root 1.23 }
1194 root 1.1 }
1195 root 1.12 while (cur < buf + SHORT_STRING_LEN);
1196 root 1.1
1197 root 1.25 {
1198     STRLEN len = cur - buf;
1199 root 1.5
1200 root 1.25 if (sv)
1201     {
1202 root 1.95 STRLEN cur = SvCUR (sv);
1203    
1204 root 1.131 if (SvLEN (sv) - cur <= len)
1205     json_sv_grow (sv, cur, len);
1206 root 1.95
1207 root 1.25 memcpy (SvPVX (sv) + SvCUR (sv), buf, len);
1208     SvCUR_set (sv, SvCUR (sv) + len);
1209     }
1210     else
1211     sv = newSVpvn (buf, len);
1212     }
1213 root 1.1 }
1214 root 1.38 while (*dec_cur != '"');
1215 root 1.1
1216 root 1.38 ++dec_cur;
1217 root 1.1
1218 root 1.12 if (sv)
1219     {
1220     SvPOK_only (sv);
1221     *SvEND (sv) = 0;
1222 root 1.4
1223 root 1.12 if (utf8)
1224     SvUTF8_on (sv);
1225     }
1226     else
1227     sv = newSVpvn ("", 0);
1228 root 1.6
1229 root 1.38 dec->cur = dec_cur;
1230 root 1.1 return sv;
1231    
1232     fail:
1233 root 1.38 dec->cur = dec_cur;
1234 root 1.1 return 0;
1235     }
1236    
1237     static SV *
1238     decode_num (dec_t *dec)
1239     {
1240     int is_nv = 0;
1241     char *start = dec->cur;
1242    
1243     // [minus]
1244     if (*dec->cur == '-')
1245     ++dec->cur;
1246    
1247     if (*dec->cur == '0')
1248     {
1249     ++dec->cur;
1250     if (*dec->cur >= '0' && *dec->cur <= '9')
1251     ERR ("malformed number (leading zero must not be followed by another digit)");
1252     }
1253 root 1.5 else if (*dec->cur < '0' || *dec->cur > '9')
1254     ERR ("malformed number (no digits after initial minus)");
1255     else
1256     do
1257     {
1258     ++dec->cur;
1259     }
1260     while (*dec->cur >= '0' && *dec->cur <= '9');
1261 root 1.1
1262     // [frac]
1263     if (*dec->cur == '.')
1264     {
1265 root 1.5 ++dec->cur;
1266    
1267     if (*dec->cur < '0' || *dec->cur > '9')
1268     ERR ("malformed number (no digits after decimal point)");
1269 root 1.1
1270     do
1271     {
1272     ++dec->cur;
1273     }
1274     while (*dec->cur >= '0' && *dec->cur <= '9');
1275 root 1.5
1276     is_nv = 1;
1277 root 1.1 }
1278    
1279     // [exp]
1280     if (*dec->cur == 'e' || *dec->cur == 'E')
1281     {
1282 root 1.5 ++dec->cur;
1283 root 1.1
1284     if (*dec->cur == '-' || *dec->cur == '+')
1285     ++dec->cur;
1286    
1287 root 1.5 if (*dec->cur < '0' || *dec->cur > '9')
1288     ERR ("malformed number (no digits after exp sign)");
1289    
1290     do
1291     {
1292     ++dec->cur;
1293     }
1294     while (*dec->cur >= '0' && *dec->cur <= '9');
1295    
1296     is_nv = 1;
1297 root 1.1 }
1298    
1299     if (!is_nv)
1300     {
1301 root 1.56 int len = dec->cur - start;
1302    
1303 root 1.70 // special case the rather common 1..5-digit-int case
1304 root 1.35 if (*start == '-')
1305 root 1.56 switch (len)
1306 root 1.1 {
1307 root 1.97 case 2: return newSViv (-(IV)( start [1] - '0' * 1));
1308     case 3: return newSViv (-(IV)( start [1] * 10 + start [2] - '0' * 11));
1309     case 4: return newSViv (-(IV)( start [1] * 100 + start [2] * 10 + start [3] - '0' * 111));
1310     case 5: return newSViv (-(IV)( start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111));
1311     case 6: return newSViv (-(IV)(start [1] * 10000 + start [2] * 1000 + start [3] * 100 + start [4] * 10 + start [5] - '0' * 11111));
1312 root 1.1 }
1313 root 1.35 else
1314 root 1.56 switch (len)
1315 root 1.35 {
1316 root 1.97 case 1: return newSViv ( start [0] - '0' * 1);
1317     case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11);
1318     case 3: return newSViv ( start [0] * 100 + start [1] * 10 + start [2] - '0' * 111);
1319     case 4: return newSViv ( start [0] * 1000 + start [1] * 100 + start [2] * 10 + start [3] - '0' * 1111);
1320     case 5: return newSViv ( start [0] * 10000 + start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 11111);
1321 root 1.35 }
1322    
1323     {
1324     UV uv;
1325 root 1.56 int numtype = grok_number (start, len, &uv);
1326 root 1.35 if (numtype & IS_NUMBER_IN_UV)
1327     if (numtype & IS_NUMBER_NEG)
1328     {
1329     if (uv < (UV)IV_MIN)
1330     return newSViv (-(IV)uv);
1331     }
1332     else
1333     return newSVuv (uv);
1334 root 1.56 }
1335    
1336     len -= *start == '-' ? 1 : 0;
1337 root 1.40
1338 root 1.56 // does not fit into IV or UV, try NV
1339 root 1.104 if (len <= NV_DIG)
1340 root 1.56 // fits into NV without loss of precision
1341 root 1.104 return newSVnv (json_atof (start));
1342 root 1.56
1343     // everything else fails, convert it to a string
1344     return newSVpvn (start, dec->cur - start);
1345 root 1.1 }
1346    
1347 root 1.56 // loss of precision here
1348 root 1.104 return newSVnv (json_atof (start));
1349 root 1.1
1350     fail:
1351     return 0;
1352     }
1353    
1354     static SV *
1355     decode_av (dec_t *dec)
1356     {
1357     AV *av = newAV ();
1358    
1359 root 1.18 DEC_INC_DEPTH;
1360 root 1.12 decode_ws (dec);
1361 root 1.18
1362 root 1.5 if (*dec->cur == ']')
1363     ++dec->cur;
1364     else
1365     for (;;)
1366     {
1367     SV *value;
1368 root 1.1
1369 root 1.5 value = decode_sv (dec);
1370     if (!value)
1371     goto fail;
1372 root 1.1
1373 root 1.5 av_push (av, value);
1374 root 1.1
1375 root 1.12 decode_ws (dec);
1376 root 1.1
1377 root 1.5 if (*dec->cur == ']')
1378     {
1379     ++dec->cur;
1380     break;
1381     }
1382 root 1.117
1383 root 1.5 if (*dec->cur != ',')
1384     ERR (", or ] expected while parsing array");
1385 root 1.1
1386 root 1.5 ++dec->cur;
1387 root 1.63
1388     decode_ws (dec);
1389    
1390     if (*dec->cur == ']' && dec->json.flags & F_RELAXED)
1391     {
1392     ++dec->cur;
1393     break;
1394     }
1395 root 1.5 }
1396 root 1.1
1397 root 1.18 DEC_DEC_DEPTH;
1398 root 1.1 return newRV_noinc ((SV *)av);
1399    
1400     fail:
1401     SvREFCNT_dec (av);
1402 root 1.18 DEC_DEC_DEPTH;
1403 root 1.1 return 0;
1404     }
1405    
1406     static SV *
1407     decode_hv (dec_t *dec)
1408     {
1409 root 1.49 SV *sv;
1410 root 1.1 HV *hv = newHV ();
1411    
1412 root 1.18 DEC_INC_DEPTH;
1413 root 1.12 decode_ws (dec);
1414 root 1.18
1415 root 1.5 if (*dec->cur == '}')
1416     ++dec->cur;
1417     else
1418     for (;;)
1419     {
1420 root 1.63 EXPECT_CH ('"');
1421 root 1.1
1422 root 1.46 // heuristic: assume that
1423 root 1.47 // a) decode_str + hv_store_ent are abysmally slow.
1424     // b) most hash keys are short, simple ascii text.
1425     // => try to "fast-match" such strings to avoid
1426     // the overhead of decode_str + hv_store_ent.
1427 root 1.46 {
1428     SV *value;
1429     char *p = dec->cur;
1430     char *e = p + 24; // only try up to 24 bytes
1431    
1432     for (;;)
1433     {
1434 root 1.77 // the >= 0x80 is false on most architectures
1435 root 1.46 if (p == e || *p < 0x20 || *p >= 0x80 || *p == '\\')
1436     {
1437     // slow path, back up and use decode_str
1438     SV *key = decode_str (dec);
1439     if (!key)
1440     goto fail;
1441    
1442     decode_ws (dec); EXPECT_CH (':');
1443    
1444 root 1.63 decode_ws (dec);
1445 root 1.46 value = decode_sv (dec);
1446     if (!value)
1447     {
1448     SvREFCNT_dec (key);
1449     goto fail;
1450     }
1451    
1452     hv_store_ent (hv, key, value, 0);
1453     SvREFCNT_dec (key);
1454    
1455     break;
1456     }
1457     else if (*p == '"')
1458     {
1459     // fast path, got a simple key
1460     char *key = dec->cur;
1461     int len = p - key;
1462     dec->cur = p + 1;
1463    
1464     decode_ws (dec); EXPECT_CH (':');
1465    
1466 root 1.63 decode_ws (dec);
1467 root 1.46 value = decode_sv (dec);
1468     if (!value)
1469     goto fail;
1470 root 1.1
1471 root 1.46 hv_store (hv, key, len, value, 0);
1472 root 1.1
1473 root 1.46 break;
1474     }
1475 root 1.1
1476 root 1.46 ++p;
1477     }
1478     }
1479 root 1.1
1480 root 1.12 decode_ws (dec);
1481 root 1.1
1482 root 1.5 if (*dec->cur == '}')
1483     {
1484     ++dec->cur;
1485     break;
1486     }
1487 root 1.1
1488 root 1.5 if (*dec->cur != ',')
1489     ERR (", or } expected while parsing object/hash");
1490 root 1.1
1491 root 1.5 ++dec->cur;
1492 root 1.63
1493     decode_ws (dec);
1494    
1495     if (*dec->cur == '}' && dec->json.flags & F_RELAXED)
1496     {
1497     ++dec->cur;
1498     break;
1499     }
1500 root 1.5 }
1501 root 1.1
1502 root 1.18 DEC_DEC_DEPTH;
1503 root 1.49 sv = newRV_noinc ((SV *)hv);
1504    
1505     // check filter callbacks
1506     if (dec->json.flags & F_HOOK)
1507     {
1508 root 1.51 if (dec->json.cb_sk_object && HvKEYS (hv) == 1)
1509 root 1.49 {
1510 root 1.52 HE *cb, *he;
1511 root 1.49
1512 root 1.52 hv_iterinit (hv);
1513     he = hv_iternext (hv);
1514     hv_iterinit (hv);
1515 root 1.49
1516 root 1.125 // the next line creates a mortal sv each time it's called.
1517 root 1.52 // might want to optimise this for common cases.
1518     cb = hv_fetch_ent (dec->json.cb_sk_object, hv_iterkeysv (he), 0, 0);
1519 root 1.49
1520 root 1.52 if (cb)
1521 root 1.51 {
1522 root 1.53 dSP;
1523 root 1.52 int count;
1524    
1525 root 1.125 ENTER; SAVETMPS;
1526     PUSHMARK (SP);
1527 root 1.52 XPUSHs (HeVAL (he));
1528 root 1.107 sv_2mortal (sv);
1529 root 1.52
1530     PUTBACK; count = call_sv (HeVAL (cb), G_ARRAY); SPAGAIN;
1531    
1532     if (count == 1)
1533     {
1534     sv = newSVsv (POPs);
1535     FREETMPS; LEAVE;
1536     return sv;
1537     }
1538 root 1.134 else if (count)
1539     croak ("filter_json_single_key_object callbacks must not return more than one scalar");
1540 root 1.52
1541 root 1.107 SvREFCNT_inc (sv);
1542 root 1.52 FREETMPS; LEAVE;
1543 root 1.51 }
1544 root 1.49 }
1545    
1546     if (dec->json.cb_object)
1547     {
1548 root 1.53 dSP;
1549 root 1.49 int count;
1550    
1551 root 1.125 ENTER; SAVETMPS;
1552     PUSHMARK (SP);
1553 root 1.49 XPUSHs (sv_2mortal (sv));
1554    
1555     PUTBACK; count = call_sv (dec->json.cb_object, G_ARRAY); SPAGAIN;
1556    
1557     if (count == 1)
1558 root 1.51 {
1559     sv = newSVsv (POPs);
1560 root 1.52 FREETMPS; LEAVE;
1561     return sv;
1562 root 1.51 }
1563 root 1.134 else if (count)
1564     croak ("filter_json_object callbacks must not return more than one scalar");
1565 root 1.51
1566     SvREFCNT_inc (sv);
1567 root 1.52 FREETMPS; LEAVE;
1568 root 1.49 }
1569     }
1570    
1571 root 1.51 return sv;
1572 root 1.1
1573     fail:
1574     SvREFCNT_dec (hv);
1575 root 1.18 DEC_DEC_DEPTH;
1576 root 1.1 return 0;
1577     }
1578    
1579     static SV *
1580 root 1.119 decode_tag (dec_t *dec)
1581     {
1582     SV *tag = 0;
1583     SV *val = 0;
1584    
1585     if (!(dec->json.flags & F_ALLOW_TAGS))
1586     ERR ("malformed JSON string, neither array, object, number, string or atom");
1587    
1588     ++dec->cur;
1589    
1590 root 1.121 decode_ws (dec);
1591    
1592 root 1.119 tag = decode_sv (dec);
1593     if (!tag)
1594     goto fail;
1595    
1596     if (!SvPOK (tag))
1597     ERR ("malformed JSON string, (tag) must be a string");
1598    
1599 root 1.121 decode_ws (dec);
1600    
1601 root 1.119 if (*dec->cur != ')')
1602     ERR (") expected after tag");
1603    
1604     ++dec->cur;
1605    
1606 root 1.121 decode_ws (dec);
1607    
1608 root 1.119 val = decode_sv (dec);
1609     if (!val)
1610     goto fail;
1611    
1612     if (!SvROK (val) || SvTYPE (SvRV (val)) != SVt_PVAV)
1613     ERR ("malformed JSON string, tag value must be an array");
1614    
1615     {
1616     AV *av = (AV *)SvRV (val);
1617     int i, len = av_len (av) + 1;
1618     HV *stash = gv_stashsv (tag, 0);
1619     SV *sv;
1620    
1621     if (!stash)
1622     ERR ("cannot decode perl-object (package does not exist)");
1623    
1624     GV *method = gv_fetchmethod_autoload (stash, "THAW", 0);
1625    
1626     if (!method)
1627     ERR ("cannot decode perl-object (package does not have a THAW method)");
1628    
1629     dSP;
1630    
1631 root 1.125 ENTER; SAVETMPS;
1632     PUSHMARK (SP);
1633 root 1.119 EXTEND (SP, len + 2);
1634     // we re-bless the reference to get overload and other niceties right
1635     PUSHs (tag);
1636     PUSHs (sv_json);
1637    
1638     for (i = 0; i < len; ++i)
1639     PUSHs (*av_fetch (av, i, 1));
1640    
1641     PUTBACK;
1642     call_sv ((SV *)GvCV (method), G_SCALAR);
1643     SPAGAIN;
1644    
1645     SvREFCNT_dec (tag);
1646     SvREFCNT_dec (val);
1647     sv = SvREFCNT_inc (POPs);
1648    
1649     PUTBACK;
1650    
1651     FREETMPS; LEAVE;
1652    
1653     return sv;
1654     }
1655    
1656     fail:
1657     SvREFCNT_dec (tag);
1658     SvREFCNT_dec (val);
1659     return 0;
1660     }
1661    
1662     static SV *
1663 root 1.1 decode_sv (dec_t *dec)
1664     {
1665 root 1.40 // the beauty of JSON: you need exactly one character lookahead
1666 root 1.73 // to parse everything.
1667 root 1.1 switch (*dec->cur)
1668     {
1669 root 1.117 case '"': ++dec->cur; return decode_str (dec);
1670     case '[': ++dec->cur; return decode_av (dec);
1671 root 1.73 case '{': ++dec->cur; return decode_hv (dec);
1672 root 1.119 case '(': return decode_tag (dec);
1673 root 1.1
1674     case '-':
1675     case '0': case '1': case '2': case '3': case '4':
1676     case '5': case '6': case '7': case '8': case '9':
1677     return decode_num (dec);
1678    
1679 root 1.133 case 'f':
1680     if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
1681 root 1.1 {
1682 root 1.133 dec->cur += 5;
1683    
1684     if (expect_false (!dec->json.v_false))
1685     dec->json.v_false = GET_BOOL (false);
1686    
1687     return newSVsv (dec->json.v_false);
1688 root 1.1 }
1689     else
1690 root 1.133 ERR ("'false' expected");
1691 root 1.1
1692     break;
1693    
1694 root 1.133 case 't':
1695     if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
1696 root 1.1 {
1697 root 1.133 dec->cur += 4;
1698    
1699     if (expect_false (!dec->json.v_true))
1700     dec->json.v_true = GET_BOOL (true);
1701    
1702     return newSVsv (dec->json.v_true);
1703 root 1.1 }
1704     else
1705 root 1.133 ERR ("'true' expected");
1706 root 1.1
1707     break;
1708    
1709     case 'n':
1710     if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "null", 4))
1711     {
1712     dec->cur += 4;
1713 root 1.5 return newSVsv (&PL_sv_undef);
1714 root 1.1 }
1715     else
1716     ERR ("'null' expected");
1717    
1718     break;
1719    
1720     default:
1721 root 1.119 ERR ("malformed JSON string, neither tag, array, object, number, string or atom");
1722 root 1.1 break;
1723     }
1724    
1725     fail:
1726     return 0;
1727     }
1728    
1729     static SV *
1730 root 1.129 decode_json (SV *string, JSON *json, STRLEN *offset_return)
1731 root 1.1 {
1732 root 1.25 dec_t dec;
1733 root 1.1 SV *sv;
1734    
1735 root 1.94 /* work around bugs in 5.10 where manipulating magic values
1736 root 1.116 * makes perl ignore the magic in subsequent accesses.
1737 root 1.109 * also make a copy of non-PV values, to get them into a clean
1738     * state (SvPV should do that, but it's buggy, see below).
1739 root 1.127 *
1740     * SvIsCOW_shared_hash works around a bug in perl (possibly 5.16),
1741     * as reported by Reini Urban.
1742 root 1.94 */
1743     /*SvGETMAGIC (string);*/
1744 root 1.127 if (SvMAGICAL (string) || !SvPOK (string) || SvIsCOW_shared_hash (string))
1745 root 1.94 string = sv_2mortal (newSVsv (string));
1746    
1747 root 1.22 SvUPGRADE (string, SVt_PV);
1748    
1749 root 1.87 /* work around a bug in perl 5.10, which causes SvCUR to fail an
1750     * assertion with -DDEBUGGING, although SvCUR is documented to
1751     * return the xpv_cur field which certainly exists after upgrading.
1752     * according to nicholas clark, calling SvPOK fixes this.
1753 root 1.89 * But it doesn't fix it, so try another workaround, call SvPV_nolen
1754     * and hope for the best.
1755 root 1.90 * Damnit, SvPV_nolen still trips over yet another assertion. This
1756     * assertion business is seriously broken, try yet another workaround
1757     * for the broken -DDEBUGGING.
1758 root 1.87 */
1759 root 1.96 {
1760 root 1.89 #ifdef DEBUGGING
1761 root 1.96 STRLEN offset = SvOK (string) ? sv_len (string) : 0;
1762 root 1.90 #else
1763 root 1.96 STRLEN offset = SvCUR (string);
1764 root 1.89 #endif
1765 root 1.87
1766 root 1.96 if (offset > json->max_size && json->max_size)
1767     croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu",
1768     (unsigned long)SvCUR (string), (unsigned long)json->max_size);
1769     }
1770 root 1.45
1771 root 1.108 if (DECODE_WANTS_OCTETS (json))
1772 root 1.5 sv_utf8_downgrade (string, 0);
1773     else
1774 root 1.1 sv_utf8_upgrade (string);
1775    
1776     SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
1777    
1778 root 1.85 dec.json = *json;
1779     dec.cur = SvPVX (string);
1780     dec.end = SvEND (string);
1781     dec.err = 0;
1782     dec.depth = 0;
1783 root 1.1
1784 root 1.49 if (dec.json.cb_object || dec.json.cb_sk_object)
1785     dec.json.flags |= F_HOOK;
1786    
1787 root 1.31 *dec.end = 0; // this should basically be a nop, too, but make sure it's there
1788 root 1.63
1789     decode_ws (&dec);
1790 root 1.1 sv = decode_sv (&dec);
1791    
1792 root 1.96 if (offset_return)
1793 root 1.129 *offset_return = dec.cur - SvPVX (string);
1794     else if (sv)
1795 root 1.31 {
1796     // check for trailing garbage
1797     decode_ws (&dec);
1798    
1799     if (*dec.cur)
1800     {
1801     dec.err = "garbage after JSON object";
1802     SvREFCNT_dec (sv);
1803     sv = 0;
1804     }
1805     }
1806    
1807 root 1.1 if (!sv)
1808     {
1809     SV *uni = sv_newmortal ();
1810 root 1.8
1811 root 1.5 // horrible hack to silence warning inside pv_uni_display
1812 root 1.8 COP cop = *PL_curcop;
1813 root 1.5 cop.cop_warnings = pWARN_NONE;
1814 root 1.8 ENTER;
1815 root 1.5 SAVEVPTR (PL_curcop);
1816     PL_curcop = &cop;
1817 root 1.8 pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ);
1818     LEAVE;
1819 root 1.1
1820 root 1.96 croak ("%s, at character offset %d (before \"%s\")",
1821 root 1.1 dec.err,
1822 root 1.113 (int)ptr_to_index (string, dec.cur),
1823 root 1.1 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
1824     }
1825    
1826 root 1.3 sv = sv_2mortal (sv);
1827    
1828 root 1.126 if (!(dec.json.flags & F_ALLOW_NONREF) && json_nonref (sv))
1829 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)");
1830 root 1.3
1831     return sv;
1832 root 1.1 }
1833    
1834 root 1.12 /////////////////////////////////////////////////////////////////////////////
1835 root 1.77 // incremental parser
1836    
1837     static void
1838     incr_parse (JSON *self)
1839     {
1840     const char *p = SvPVX (self->incr_text) + self->incr_pos;
1841    
1842 root 1.103 // the state machine here is a bit convoluted and could be simplified a lot
1843     // but this would make it slower, so...
1844    
1845 root 1.77 for (;;)
1846     {
1847     //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
1848     switch (self->incr_mode)
1849     {
1850 root 1.103 // only used for initial whitespace skipping
1851 root 1.77 case INCR_M_WS:
1852     for (;;)
1853     {
1854     if (*p > 0x20)
1855     {
1856 root 1.103 if (*p == '#')
1857     {
1858     self->incr_mode = INCR_M_C0;
1859     goto incr_m_c;
1860     }
1861     else
1862     {
1863     self->incr_mode = INCR_M_JSON;
1864     goto incr_m_json;
1865     }
1866 root 1.77 }
1867     else if (!*p)
1868     goto interrupt;
1869    
1870     ++p;
1871     }
1872    
1873     // skip a single char inside a string (for \\-processing)
1874     case INCR_M_BS:
1875     if (!*p)
1876     goto interrupt;
1877    
1878     ++p;
1879     self->incr_mode = INCR_M_STR;
1880     goto incr_m_str;
1881    
1882 root 1.103 // inside #-style comments
1883     case INCR_M_C0:
1884     case INCR_M_C1:
1885     incr_m_c:
1886     for (;;)
1887     {
1888     if (*p == '\n')
1889     {
1890     self->incr_mode = self->incr_mode == INCR_M_C0 ? INCR_M_WS : INCR_M_JSON;
1891     break;
1892     }
1893     else if (!*p)
1894     goto interrupt;
1895    
1896     ++p;
1897     }
1898    
1899     break;
1900    
1901 root 1.77 // inside a string
1902     case INCR_M_STR:
1903     incr_m_str:
1904     for (;;)
1905     {
1906     if (*p == '"')
1907     {
1908     ++p;
1909     self->incr_mode = INCR_M_JSON;
1910    
1911     if (!self->incr_nest)
1912     goto interrupt;
1913    
1914     goto incr_m_json;
1915     }
1916     else if (*p == '\\')
1917     {
1918     ++p; // "virtually" consumes character after \
1919    
1920     if (!*p) // if at end of string we have to switch modes
1921     {
1922     self->incr_mode = INCR_M_BS;
1923     goto interrupt;
1924     }
1925     }
1926     else if (!*p)
1927     goto interrupt;
1928    
1929     ++p;
1930     }
1931    
1932     // after initial ws, outside string
1933     case INCR_M_JSON:
1934     incr_m_json:
1935     for (;;)
1936     {
1937     switch (*p++)
1938     {
1939     case 0:
1940     --p;
1941     goto interrupt;
1942    
1943     case 0x09:
1944     case 0x0a:
1945     case 0x0d:
1946     case 0x20:
1947     if (!self->incr_nest)
1948     {
1949     --p; // do not eat the whitespace, let the next round do it
1950     goto interrupt;
1951     }
1952     break;
1953    
1954     case '"':
1955     self->incr_mode = INCR_M_STR;
1956     goto incr_m_str;
1957    
1958     case '[':
1959     case '{':
1960 root 1.119 case '(':
1961 root 1.85 if (++self->incr_nest > self->max_depth)
1962     croak (ERR_NESTING_EXCEEDED);
1963 root 1.77 break;
1964    
1965     case ']':
1966     case '}':
1967 root 1.88 if (--self->incr_nest <= 0)
1968 root 1.77 goto interrupt;
1969 root 1.103 break;
1970    
1971 root 1.119 case ')':
1972     --self->incr_nest;
1973     break;
1974    
1975 root 1.103 case '#':
1976     self->incr_mode = INCR_M_C1;
1977     goto incr_m_c;
1978 root 1.77 }
1979     }
1980     }
1981    
1982     modechange:
1983     ;
1984     }
1985    
1986     interrupt:
1987     self->incr_pos = p - SvPVX (self->incr_text);
1988 root 1.103 //printf ("interrupt<%.*s>\n", self->incr_pos, SvPVX(self->incr_text));//D
1989 root 1.77 //printf ("return pos %d mode %d nest %d\n", self->incr_pos, self->incr_mode, self->incr_nest);//D
1990     }
1991    
1992     /////////////////////////////////////////////////////////////////////////////
1993 root 1.12 // XS interface functions
1994    
1995 root 1.1 MODULE = JSON::XS PACKAGE = JSON::XS
1996    
1997     BOOT:
1998     {
1999     int i;
2000    
2001 root 1.18 for (i = 0; i < 256; ++i)
2002     decode_hexdigit [i] =
2003     i >= '0' && i <= '9' ? i - '0'
2004     : i >= 'a' && i <= 'f' ? i - 'a' + 10
2005     : i >= 'A' && i <= 'F' ? i - 'A' + 10
2006     : -1;
2007 root 1.1
2008 root 1.126 json_stash = gv_stashpv ("JSON::XS" , 1);
2009     bool_stash = gv_stashpv ("Types::Serialiser::Boolean", 1);
2010 root 1.133 bool_false = get_bool ("Types::Serialiser::false");
2011 root 1.126 bool_true = get_bool ("Types::Serialiser::true");
2012 root 1.43
2013 root 1.119 sv_json = newSVpv ("JSON", 0);
2014     SvREADONLY_on (sv_json);
2015 root 1.99
2016     CvNODEBUG_on (get_cv ("JSON::XS::incr_text", 0)); /* the debugger completely breaks lvalue subs */
2017 root 1.1 }
2018    
2019 root 1.4 PROTOTYPES: DISABLE
2020    
2021 root 1.57 void CLONE (...)
2022     CODE:
2023 root 1.133 // as long as these writes are atomic, the race should not matter
2024     // as existing threads either already use 0, or use the old value,
2025     // which is sitll correct for the initial thread.
2026 root 1.126 json_stash = 0;
2027     bool_stash = 0;
2028 root 1.133 bool_false = 0;
2029     bool_true = 0;
2030 root 1.57
2031 root 1.48 void new (char *klass)
2032     PPCODE:
2033     {
2034 root 1.115 SV *pv = NEWSV (0, sizeof (JSON));
2035 root 1.48 SvPOK_only (pv);
2036 root 1.85 json_init ((JSON *)SvPVX (pv));
2037 root 1.68 XPUSHs (sv_2mortal (sv_bless (
2038     newRV_noinc (pv),
2039     strEQ (klass, "JSON::XS") ? JSON_STASH : gv_stashpv (klass, 1)
2040     )));
2041 root 1.48 }
2042 root 1.1
2043 root 1.133 void boolean_values (JSON *self, SV *v_false = 0, SV *v_true = 0)
2044     PPCODE:
2045     self->v_false = newSVsv (v_false);
2046     self->v_true = newSVsv (v_true);
2047     XPUSHs (ST (0));
2048    
2049     void get_boolean_values (JSON *self)
2050     PPCODE:
2051     if (self->v_false && self->v_true)
2052     {
2053     EXTEND (SP, 2);
2054     PUSHs (self->v_false);
2055     PUSHs (self->v_true);
2056     }
2057    
2058 root 1.48 void ascii (JSON *self, int enable = 1)
2059 root 1.1 ALIAS:
2060 root 1.44 ascii = F_ASCII
2061     latin1 = F_LATIN1
2062     utf8 = F_UTF8
2063     indent = F_INDENT
2064     canonical = F_CANONICAL
2065     space_before = F_SPACE_BEFORE
2066     space_after = F_SPACE_AFTER
2067     pretty = F_PRETTY
2068     allow_nonref = F_ALLOW_NONREF
2069     shrink = F_SHRINK
2070     allow_blessed = F_ALLOW_BLESSED
2071     convert_blessed = F_CONV_BLESSED
2072 root 1.63 relaxed = F_RELAXED
2073 root 1.84 allow_unknown = F_ALLOW_UNKNOWN
2074 root 1.119 allow_tags = F_ALLOW_TAGS
2075 root 1.48 PPCODE:
2076 root 1.1 {
2077     if (enable)
2078 root 1.48 self->flags |= ix;
2079 root 1.1 else
2080 root 1.48 self->flags &= ~ix;
2081 root 1.1
2082 root 1.48 XPUSHs (ST (0));
2083 root 1.1 }
2084    
2085 root 1.66 void get_ascii (JSON *self)
2086     ALIAS:
2087     get_ascii = F_ASCII
2088     get_latin1 = F_LATIN1
2089     get_utf8 = F_UTF8
2090     get_indent = F_INDENT
2091     get_canonical = F_CANONICAL
2092     get_space_before = F_SPACE_BEFORE
2093     get_space_after = F_SPACE_AFTER
2094     get_allow_nonref = F_ALLOW_NONREF
2095     get_shrink = F_SHRINK
2096     get_allow_blessed = F_ALLOW_BLESSED
2097     get_convert_blessed = F_CONV_BLESSED
2098     get_relaxed = F_RELAXED
2099 root 1.84 get_allow_unknown = F_ALLOW_UNKNOWN
2100 root 1.119 get_allow_tags = F_ALLOW_TAGS
2101 root 1.66 PPCODE:
2102     XPUSHs (boolSV (self->flags & ix));
2103    
2104 root 1.85 void max_depth (JSON *self, U32 max_depth = 0x80000000UL)
2105 root 1.48 PPCODE:
2106 root 1.85 self->max_depth = max_depth;
2107 root 1.48 XPUSHs (ST (0));
2108 root 1.18
2109 root 1.67 U32 get_max_depth (JSON *self)
2110 root 1.66 CODE:
2111 root 1.85 RETVAL = self->max_depth;
2112 root 1.66 OUTPUT:
2113     RETVAL
2114    
2115 root 1.85 void max_size (JSON *self, U32 max_size = 0)
2116 root 1.48 PPCODE:
2117 root 1.85 self->max_size = max_size;
2118 root 1.48 XPUSHs (ST (0));
2119 root 1.45
2120 root 1.66 int get_max_size (JSON *self)
2121     CODE:
2122 root 1.85 RETVAL = self->max_size;
2123 root 1.66 OUTPUT:
2124     RETVAL
2125    
2126 root 1.51 void filter_json_object (JSON *self, SV *cb = &PL_sv_undef)
2127 root 1.49 PPCODE:
2128     {
2129 root 1.52 SvREFCNT_dec (self->cb_object);
2130     self->cb_object = SvOK (cb) ? newSVsv (cb) : 0;
2131    
2132     XPUSHs (ST (0));
2133     }
2134    
2135     void filter_json_single_key_object (JSON *self, SV *key, SV *cb = &PL_sv_undef)
2136     PPCODE:
2137     {
2138 root 1.114 if (!self->cb_sk_object)
2139 root 1.52 self->cb_sk_object = newHV ();
2140 root 1.51
2141 root 1.52 if (SvOK (cb))
2142     hv_store_ent (self->cb_sk_object, key, newSVsv (cb), 0);
2143 root 1.51 else
2144 root 1.52 {
2145     hv_delete_ent (self->cb_sk_object, key, G_DISCARD, 0);
2146 root 1.49
2147 root 1.52 if (!HvKEYS (self->cb_sk_object))
2148     {
2149     SvREFCNT_dec (self->cb_sk_object);
2150     self->cb_sk_object = 0;
2151     }
2152 root 1.49 }
2153    
2154     XPUSHs (ST (0));
2155     }
2156    
2157 root 1.48 void encode (JSON *self, SV *scalar)
2158 root 1.1 PPCODE:
2159 root 1.114 PUTBACK; scalar = encode_json (scalar, self); SPAGAIN;
2160     XPUSHs (scalar);
2161 root 1.1
2162 root 1.48 void decode (JSON *self, SV *jsonstr)
2163 root 1.1 PPCODE:
2164 root 1.114 PUTBACK; jsonstr = decode_json (jsonstr, self, 0); SPAGAIN;
2165     XPUSHs (jsonstr);
2166 root 1.31
2167 root 1.48 void decode_prefix (JSON *self, SV *jsonstr)
2168 root 1.31 PPCODE:
2169     {
2170 root 1.114 SV *sv;
2171 root 1.129 STRLEN offset;
2172 root 1.114 PUTBACK; sv = decode_json (jsonstr, self, &offset); SPAGAIN;
2173 root 1.31 EXTEND (SP, 2);
2174 root 1.114 PUSHs (sv);
2175 root 1.129 PUSHs (sv_2mortal (newSVuv (ptr_to_index (jsonstr, SvPV_nolen (jsonstr) + offset))));
2176 root 1.31 }
2177 root 1.2
2178 root 1.77 void incr_parse (JSON *self, SV *jsonstr = 0)
2179     PPCODE:
2180     {
2181     if (!self->incr_text)
2182     self->incr_text = newSVpvn ("", 0);
2183    
2184 root 1.108 /* if utf8-ness doesn't match the decoder, need to upgrade/downgrade */
2185     if (!DECODE_WANTS_OCTETS (self) == !SvUTF8 (self->incr_text))
2186     if (DECODE_WANTS_OCTETS (self))
2187     {
2188     if (self->incr_pos)
2189     self->incr_pos = utf8_length ((U8 *)SvPVX (self->incr_text),
2190     (U8 *)SvPVX (self->incr_text) + self->incr_pos);
2191    
2192     sv_utf8_downgrade (self->incr_text, 0);
2193     }
2194     else
2195     {
2196     sv_utf8_upgrade (self->incr_text);
2197    
2198     if (self->incr_pos)
2199     self->incr_pos = utf8_hop ((U8 *)SvPVX (self->incr_text), self->incr_pos)
2200     - (U8 *)SvPVX (self->incr_text);
2201     }
2202    
2203 root 1.77 // append data, if any
2204     if (jsonstr)
2205     {
2206 root 1.108 /* make sure both strings have same encoding */
2207     if (SvUTF8 (jsonstr) != SvUTF8 (self->incr_text))
2208     if (SvUTF8 (jsonstr))
2209     sv_utf8_downgrade (jsonstr, 0);
2210     else
2211     sv_utf8_upgrade (jsonstr);
2212 root 1.77
2213 root 1.108 /* and then just blindly append */
2214 root 1.77 {
2215     STRLEN len;
2216     const char *str = SvPV (jsonstr, len);
2217 root 1.95 STRLEN cur = SvCUR (self->incr_text);
2218    
2219 root 1.131 if (SvLEN (self->incr_text) - cur <= len)
2220     json_sv_grow (self->incr_text, cur, len);
2221 root 1.95
2222 root 1.77 Move (str, SvEND (self->incr_text), len, char);
2223     SvCUR_set (self->incr_text, SvCUR (self->incr_text) + len);
2224     *SvEND (self->incr_text) = 0; // this should basically be a nop, too, but make sure it's there
2225     }
2226     }
2227    
2228     if (GIMME_V != G_VOID)
2229     do
2230     {
2231 root 1.114 SV *sv;
2232 root 1.129 STRLEN offset;
2233 root 1.77
2234     if (!INCR_DONE (self))
2235 root 1.82 {
2236     incr_parse (self);
2237 root 1.85
2238     if (self->incr_pos > self->max_size && self->max_size)
2239     croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu",
2240     (unsigned long)self->incr_pos, (unsigned long)self->max_size);
2241    
2242 root 1.82 if (!INCR_DONE (self))
2243 root 1.111 {
2244     // as an optimisation, do not accumulate white space in the incr buffer
2245 root 1.112 if (self->incr_mode == INCR_M_WS && self->incr_pos)
2246     {
2247     self->incr_pos = 0;
2248     SvCUR_set (self->incr_text, 0);
2249     }
2250 root 1.111
2251     break;
2252     }
2253 root 1.82 }
2254 root 1.77
2255 root 1.114 PUTBACK; sv = decode_json (self->incr_text, self, &offset); SPAGAIN;
2256     XPUSHs (sv);
2257 root 1.77
2258 root 1.129 self->incr_pos -= offset;
2259 root 1.77 self->incr_nest = 0;
2260     self->incr_mode = 0;
2261 root 1.96
2262 root 1.129 sv_chop (self->incr_text, SvPVX (self->incr_text) + offset);
2263 root 1.77 }
2264     while (GIMME_V == G_ARRAY);
2265     }
2266    
2267     SV *incr_text (JSON *self)
2268     ATTRS: lvalue
2269     CODE:
2270     {
2271     if (self->incr_pos)
2272 root 1.82 croak ("incr_text can not be called when the incremental parser already started parsing");
2273 root 1.77
2274     RETVAL = self->incr_text ? SvREFCNT_inc (self->incr_text) : &PL_sv_undef;
2275     }
2276     OUTPUT:
2277     RETVAL
2278    
2279 root 1.79 void incr_skip (JSON *self)
2280     CODE:
2281     {
2282 root 1.81 if (self->incr_pos)
2283     {
2284     sv_chop (self->incr_text, SvPV_nolen (self->incr_text) + self->incr_pos);
2285     self->incr_pos = 0;
2286     self->incr_nest = 0;
2287     self->incr_mode = 0;
2288     }
2289 root 1.79 }
2290    
2291 root 1.86 void incr_reset (JSON *self)
2292     CODE:
2293     {
2294     SvREFCNT_dec (self->incr_text);
2295     self->incr_text = 0;
2296     self->incr_pos = 0;
2297     self->incr_nest = 0;
2298     self->incr_mode = 0;
2299     }
2300    
2301 root 1.52 void DESTROY (JSON *self)
2302     CODE:
2303 root 1.133 SvREFCNT_dec (self->v_false);
2304     SvREFCNT_dec (self->v_true);
2305 root 1.52 SvREFCNT_dec (self->cb_sk_object);
2306     SvREFCNT_dec (self->cb_object);
2307 root 1.77 SvREFCNT_dec (self->incr_text);
2308 root 1.52
2309 root 1.4 PROTOTYPES: ENABLE
2310    
2311 root 1.69 void encode_json (SV *scalar)
2312 root 1.2 PPCODE:
2313 root 1.47 {
2314 root 1.85 JSON json;
2315     json_init (&json);
2316 root 1.118 json.flags |= F_UTF8;
2317 root 1.114 PUTBACK; scalar = encode_json (scalar, &json); SPAGAIN;
2318     XPUSHs (scalar);
2319 root 1.47 }
2320 root 1.2
2321 root 1.69 void decode_json (SV *jsonstr)
2322 root 1.2 PPCODE:
2323 root 1.47 {
2324 root 1.85 JSON json;
2325     json_init (&json);
2326 root 1.118 json.flags |= F_UTF8;
2327 root 1.114 PUTBACK; jsonstr = decode_json (jsonstr, &json, 0); SPAGAIN;
2328     XPUSHs (jsonstr);
2329 root 1.47 }
2330 root 1.1