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