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.63 by root, Mon Aug 27 01:49:01 2007 UTC vs.
Revision 1.134 by root, Thu Nov 15 20:13:03 2018 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines