ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/JSON-XS/XS.xs
(Generate patch)

Comparing JSON-XS/XS.xs (file contents):
Revision 1.36 by root, Wed Jun 6 17:27:33 2007 UTC vs.
Revision 1.133 by root, Tue Aug 28 16:16:17 2018 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines