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.3 by root, Thu Mar 22 18:10:29 2007 UTC vs.
Revision 1.134 by root, Thu Nov 15 20:13:03 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>
9#include <limits.h>
10#include <float.h>
11#include <inttypes.h>
8 12
13#if defined(__BORLANDC__) || defined(_MSC_VER)
14# define snprintf _snprintf // C compilers have this in stdio.h
15#endif
16
17// some old perls do not have this, try to make it work, no
18// guarantees, though. if it breaks, you get to keep the pieces.
19#ifndef UTF8_MAXBYTES
20# define UTF8_MAXBYTES 13
21#endif
22
23// compatibility with perl <5.18
24#ifndef HvNAMELEN_get
25# define HvNAMELEN_get(hv) strlen (HvNAME (hv))
26#endif
27#ifndef HvNAMELEN
28# define HvNAMELEN(hv) HvNAMELEN_get (hv)
29#endif
30#ifndef HvNAMEUTF8
31# define HvNAMEUTF8(hv) 0
32#endif
33
34// three extra for rounding, sign, and end of string
35#define IVUV_MAXCHARS (sizeof (UV) * CHAR_BIT * 28 / 93 + 3)
36
9#define F_ASCII 0x00000001 37#define F_ASCII 0x00000001UL
38#define F_LATIN1 0x00000002UL
10#define F_UTF8 0x00000002 39#define F_UTF8 0x00000004UL
11#define F_INDENT 0x00000004 40#define F_INDENT 0x00000008UL
12#define F_CANONICAL 0x00000008 41#define F_CANONICAL 0x00000010UL
13#define F_SPACE_BEFORE 0x00000010 42#define F_SPACE_BEFORE 0x00000020UL
14#define F_SPACE_AFTER 0x00000020 43#define F_SPACE_AFTER 0x00000040UL
15#define F_JSON_RPC 0x00000040
16#define F_ALLOW_NONREF 0x00000080 44#define F_ALLOW_NONREF 0x00000100UL
45#define F_SHRINK 0x00000200UL
46#define F_ALLOW_BLESSED 0x00000400UL
47#define F_CONV_BLESSED 0x00000800UL
48#define F_RELAXED 0x00001000UL
49#define F_ALLOW_UNKNOWN 0x00002000UL
50#define F_ALLOW_TAGS 0x00004000UL
51#define F_HOOK 0x00080000UL // some hooks exist, so slow-path processing
17 52
18#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER 53#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER
19#define F_DEFAULT 0
20 54
21#define INIT_SIZE 32 // initial scalar size to be allocated 55#define INIT_SIZE 64 // initial scalar size to be allocated
56#define INDENT_STEP 3 // spaces per indentation level
57
58#define SHORT_STRING_LEN 16384 // special-case strings of up to this size
59
60#define DECODE_WANTS_OCTETS(json) ((json)->flags & F_UTF8)
22 61
23#define SB do { 62#define SB do {
24#define SE } while (0) 63#define SE } while (0)
25 64
26static HV *json_stash; 65#if __GNUC__ >= 3
66# define expect(expr,value) __builtin_expect ((expr), (value))
67# define INLINE static inline
68#else
69# define expect(expr,value) (expr)
70# define INLINE static
71#endif
72
73#define expect_false(expr) expect ((expr) != 0, 0)
74#define expect_true(expr) expect ((expr) != 0, 1)
75
76#define IN_RANGE_INC(type,val,beg,end) \
77 ((unsigned type)((unsigned type)(val) - (unsigned type)(beg)) \
78 <= (unsigned type)((unsigned type)(end) - (unsigned type)(beg)))
79
80#define ERR_NESTING_EXCEEDED "json text or perl structure exceeds maximum nesting level (max_depth set too low?)"
81
82#ifdef USE_ITHREADS
83# define JSON_STASH (expect_true (json_stash) ? json_stash : gv_stashpv ("JSON::XS", 1))
84# define BOOL_STASH (expect_true (bool_stash) ? bool_stash : gv_stashpv ("Types::Serialiser::Boolean", 1))
85# define GET_BOOL(value) (expect_true (bool_ ## value) ? bool_ ## value : get_bool ("Types::Serialiser::" # value))
86#else
87# define JSON_STASH json_stash
88# define BOOL_STASH bool_stash
89# define GET_BOOL(value) bool_ ## value
90#endif
91
92// the amount of HEs to allocate on the stack, when sorting keys
93#define STACK_HES 64
94
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}
133
134/////////////////////////////////////////////////////////////////////////////
135// utility functions
136
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
149shrink (SV *sv)
150{
151 sv_utf8_downgrade (sv, 1);
152
153 if (SvLEN (sv) > SvCUR (sv) + 1)
154 {
155#ifdef SvPV_shrink_to_cur
156 SvPV_shrink_to_cur (sv);
157#elif defined (SvPV_renew)
158 SvPV_renew (sv, SvCUR (sv) + 1);
159#endif
160 }
161}
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
188// decode a utf-8 character and return it, or (UV)-1 in
189// case of an error.
190// we special-case "safe" characters from U+80 .. U+7FF,
191// but use the very good perl function to parse anything else.
192// note that we never call this function for a ascii codepoints
193INLINE UV
194decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
195{
196 if (expect_true (len >= 2
197 && IN_RANGE_INC (char, s[0], 0xc2, 0xdf)
198 && IN_RANGE_INC (char, s[1], 0x80, 0xbf)))
199 {
200 *clen = 2;
201 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
202 }
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 }
306 }
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)
369 return 1;
370
371 if (!SvOBJECT (scalar) && ref_bool_type (scalar) >= 0)
372 return 1;
373 }
374
375 return 0;
376}
377
378/////////////////////////////////////////////////////////////////////////////
379// encoder
27 380
28// structure used for encoding JSON 381// structure used for encoding JSON
29typedef struct 382typedef struct
30{ 383{
31 char *cur; 384 char *cur; // SvPVX (sv) + current output position
32 STRLEN len; // SvLEN (sv)
33 char *end; // SvEND (sv) 385 char *end; // SvEND (sv)
34 SV *sv; 386 SV *sv; // result scalar
35 UV flags; 387 JSON json;
36 int max_recurse; 388 U32 indent; // indentation level
37 int indent; 389 UV limit; // escape character values >= this value when encoding
38} enc_t; 390} enc_t;
39 391
40// structure used for decoding JSON 392INLINE void
41typedef struct
42{
43 char *cur;
44 char *end;
45 char *err;
46 UV flags;
47} dec_t;
48
49static UV *
50SvJSON (SV *sv)
51{
52 if (!(SvROK (sv) && SvOBJECT (SvRV (sv)) && SvSTASH (SvRV (sv)) == json_stash))
53 croak ("object is not of type JSON::XS");
54
55 return &SvUVX (SvRV (sv));
56}
57
58/////////////////////////////////////////////////////////////////////////////
59
60static void
61need (enc_t *enc, STRLEN len) 393need (enc_t *enc, STRLEN len)
62{ 394{
63 if (enc->cur + len >= enc->end) 395 if (expect_false ((uintptr_t)(enc->end - enc->cur) < len))
64 { 396 {
65 STRLEN cur = enc->cur - SvPVX (enc->sv); 397 STRLEN cur = enc->cur - (char *)SvPVX (enc->sv);
66 SvGROW (enc->sv, cur + len + 1); 398 char *buf = json_sv_grow (enc->sv, cur, len);
67 enc->cur = SvPVX (enc->sv) + cur; 399 enc->cur = buf + cur;
68 enc->end = SvEND (enc->sv); 400 enc->end = buf + SvLEN (enc->sv) - 1;
69 } 401 }
70} 402}
71 403
72static void 404INLINE void
73encode_ch (enc_t *enc, char ch) 405encode_ch (enc_t *enc, char ch)
74{ 406{
75 need (enc, 1); 407 need (enc, 1);
76 *enc->cur++ = ch; 408 *enc->cur++ = ch;
77} 409}
79static void 411static void
80encode_str (enc_t *enc, char *str, STRLEN len, int is_utf8) 412encode_str (enc_t *enc, char *str, STRLEN len, int is_utf8)
81{ 413{
82 char *end = str + len; 414 char *end = str + len;
83 415
416 need (enc, len);
417
84 while (str < end) 418 while (str < end)
85 { 419 {
86 unsigned char ch = *(unsigned char *)str; 420 unsigned char ch = *(unsigned char *)str;
421
87 if (ch >= 0x20 && ch < 0x80) // most common case 422 if (expect_true (ch >= 0x20 && ch < 0x80)) // most common case
88 { 423 {
424 if (expect_false (ch == '"')) // but with slow exceptions
425 {
426 need (enc, len + 1);
427 *enc->cur++ = '\\';
428 *enc->cur++ = '"';
429 }
430 else if (expect_false (ch == '\\'))
431 {
432 need (enc, len + 1);
433 *enc->cur++ = '\\';
434 *enc->cur++ = '\\';
435 }
436 else
89 *enc->cur++ = ch; 437 *enc->cur++ = ch;
438
90 str++; 439 ++str;
91 } 440 }
92 else 441 else
93 { 442 {
94 STRLEN clen; 443 switch (ch)
95 UV uch;
96
97 if (is_utf8)
98 { 444 {
99 uch = utf8n_to_uvuni (str, end - str, &clen, UTF8_CHECK_ONLY); 445 case '\010': need (enc, len + 1); *enc->cur++ = '\\'; *enc->cur++ = 'b'; ++str; break;
100 if (clen < 0) 446 case '\011': need (enc, len + 1); *enc->cur++ = '\\'; *enc->cur++ = 't'; ++str; break;
101 croak ("malformed UTF-8 character in string, cannot convert to JSON"); 447 case '\012': need (enc, len + 1); *enc->cur++ = '\\'; *enc->cur++ = 'n'; ++str; break;
102 } 448 case '\014': need (enc, len + 1); *enc->cur++ = '\\'; *enc->cur++ = 'f'; ++str; break;
103 else 449 case '\015': need (enc, len + 1); *enc->cur++ = '\\'; *enc->cur++ = 'r'; ++str; break;
104 {
105 uch = ch;
106 clen = 1;
107 }
108 450
109 need (enc, len += 6); 451 default:
110
111 if (uch < 0xa0 || enc->flags & F_ASCII)
112 {
113 if (uch > 0xFFFFUL)
114 { 452 {
453 STRLEN clen;
454 UV uch;
455
456 if (is_utf8)
457 {
458 uch = decode_utf8 (str, end - str, &clen);
459 if (clen == (STRLEN)-1)
460 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str);
461 }
462 else
463 {
464 uch = ch;
115 len += 6; 465 clen = 1;
466 }
467
468 if (uch < 0x80/*0x20*/ || uch >= enc->limit)
469 {
470 if (uch >= 0x10000UL)
471 {
472 if (uch >= 0x110000UL)
473 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
474
116 need (enc, len += 6); 475 need (enc, len + 11);
117 sprintf (enc->cur, "\\u%04x\\u%04x", 476 sprintf (enc->cur, "\\u%04x\\u%04x",
118 (uch - 0x10000) / 0x400 + 0xD800, 477 (int)((uch - 0x10000) / 0x400 + 0xD800),
119 (uch - 0x10000) % 0x400 + 0xDC00); 478 (int)((uch - 0x10000) % 0x400 + 0xDC00));
120 enc->cur += 12; 479 enc->cur += 12;
480 }
481 else
482 {
483 need (enc, len + 5);
484 *enc->cur++ = '\\';
485 *enc->cur++ = 'u';
486 *enc->cur++ = PL_hexdigit [ uch >> 12 ];
487 *enc->cur++ = PL_hexdigit [(uch >> 8) & 15];
488 *enc->cur++ = PL_hexdigit [(uch >> 4) & 15];
489 *enc->cur++ = PL_hexdigit [(uch >> 0) & 15];
490 }
491
492 str += clen;
121 } 493 }
494 else if (enc->json.flags & F_LATIN1)
495 {
496 *enc->cur++ = uch;
497 str += clen;
498 }
499 else if (is_utf8)
500 {
501 need (enc, len + clen);
502 do
503 {
504 *enc->cur++ = *str++;
505 }
506 while (--clen);
507 }
122 else 508 else
123 { 509 {
124 sprintf (enc->cur, "\\u%04x", uch); 510 need (enc, len + UTF8_MAXBYTES - 1); // never more than 11 bytes needed
125 enc->cur += 6; 511 enc->cur = encode_utf8 (enc->cur, uch);
512 ++str;
513 }
126 } 514 }
127 } 515 }
128 else if (is_utf8)
129 {
130 memcpy (enc->cur, str, clen);
131 enc->cur += clen;
132 }
133 else
134 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0);
135
136 str += clen;
137 } 516 }
138 517
139 --len; 518 --len;
140 } 519 }
141} 520}
142 521
143#define INDENT SB \ 522INLINE void
523encode_indent (enc_t *enc)
524{
144 if (enc->flags & F_INDENT) \ 525 if (enc->json.flags & F_INDENT)
145 { \ 526 {
146 int i_; \ 527 int spaces = enc->indent * INDENT_STEP;
147 need (enc, enc->indent); \ 528
148 for (i_ = enc->indent * 3; i_--; )\ 529 need (enc, spaces);
530 memset (enc->cur, ' ', spaces);
531 enc->cur += spaces;
532 }
533}
534
535INLINE void
536encode_space (enc_t *enc)
537{
538 need (enc, 1);
539 encode_ch (enc, ' ');
540}
541
542INLINE void
543encode_nl (enc_t *enc)
544{
545 if (enc->json.flags & F_INDENT)
546 {
547 need (enc, 1);
149 encode_ch (enc, ' '); \ 548 encode_ch (enc, '\n');
150 } \ 549 }
151 SE 550}
152 551
153#define SPACE SB need (enc, 1); encode_ch (enc, ' '); SE 552INLINE void
154#define NL SB if (enc->flags & F_INDENT) { need (enc, 1); encode_ch (enc, '\n'); } SE 553encode_comma (enc_t *enc)
155#define COMMA SB \ 554{
156 encode_ch (enc, ','); \ 555 encode_ch (enc, ',');
556
157 if (enc->flags & F_INDENT) \ 557 if (enc->json.flags & F_INDENT)
158 NL; \ 558 encode_nl (enc);
159 else if (enc->flags & F_SPACE_AFTER) \ 559 else if (enc->json.flags & F_SPACE_AFTER)
160 SPACE; \ 560 encode_space (enc);
161 SE 561}
162 562
163static void encode_sv (enc_t *enc, SV *sv); 563static void encode_sv (enc_t *enc, SV *sv);
164 564
165static void 565static void
166encode_av (enc_t *enc, AV *av) 566encode_av (enc_t *enc, AV *av)
167{ 567{
168 int i, len = av_len (av); 568 int i, len = av_len (av);
169 569
570 if (enc->indent >= enc->json.max_depth)
571 croak (ERR_NESTING_EXCEEDED);
572
170 encode_ch (enc, '['); NL; 573 encode_ch (enc, '[');
171 ++enc->indent;
172 574
575 if (len >= 0)
576 {
577 encode_nl (enc); ++enc->indent;
578
173 for (i = 0; i <= len; ++i) 579 for (i = 0; i <= len; ++i)
174 { 580 {
175 INDENT; 581 SV **svp = av_fetch (av, i, 0);
176 encode_sv (enc, *av_fetch (av, i, 0));
177 582
583 encode_indent (enc);
584
585 if (svp)
586 encode_sv (enc, *svp);
587 else
588 encode_str (enc, "null", 4, 0);
589
178 if (i < len) 590 if (i < len)
179 COMMA; 591 encode_comma (enc);
180 } 592 }
181 593
182 NL; 594 encode_nl (enc); --enc->indent; encode_indent (enc);
595 }
183 596
184 --enc->indent;
185 INDENT; encode_ch (enc, ']'); 597 encode_ch (enc, ']');
186} 598}
187 599
188static void 600static void
189encode_he (enc_t *enc, HE *he) 601encode_hk (enc_t *enc, HE *he)
190{ 602{
191 encode_ch (enc, '"'); 603 encode_ch (enc, '"');
192 604
193 if (HeKLEN (he) == HEf_SVKEY) 605 if (HeKLEN (he) == HEf_SVKEY)
194 { 606 {
195 SV *sv = HeSVKEY (he); 607 SV *sv = HeSVKEY (he);
196 STRLEN len; 608 STRLEN len;
609 char *str;
610
611 SvGETMAGIC (sv);
197 char *str = SvPV (sv, len); 612 str = SvPV (sv, len);
198 613
199 encode_str (enc, str, len, SvUTF8 (sv)); 614 encode_str (enc, str, len, SvUTF8 (sv));
200 } 615 }
201 else 616 else
202 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he)); 617 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he));
203 618
204 encode_ch (enc, '"'); 619 encode_ch (enc, '"');
205 620
206 if (enc->flags & F_SPACE_BEFORE) SPACE; 621 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc);
207 encode_ch (enc, ':'); 622 encode_ch (enc, ':');
208 if (enc->flags & F_SPACE_AFTER ) SPACE; 623 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc);
209 encode_sv (enc, HeVAL (he));
210} 624}
211 625
212// compare hash entries, used when all keys are bytestrings 626// compare hash entries, used when all keys are bytestrings
213static int 627static int
214he_cmp_fast (const void *a_, const void *b_) 628he_cmp_fast (const void *a_, const void *b_)
219 HE *b = *(HE **)b_; 633 HE *b = *(HE **)b_;
220 634
221 STRLEN la = HeKLEN (a); 635 STRLEN la = HeKLEN (a);
222 STRLEN lb = HeKLEN (b); 636 STRLEN lb = HeKLEN (b);
223 637
224 if (!(cmp == memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb))) 638 if (!(cmp = memcmp (HeKEY (b), HeKEY (a), lb < la ? lb : la)))
225 cmp = la < lb ? -1 : la == lb ? 0 : 1; 639 cmp = lb - la;
226 640
227 return cmp; 641 return cmp;
228} 642}
229 643
230// 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
231static int 645static int
232he_cmp_slow (const void *a, const void *b) 646he_cmp_slow (const void *a, const void *b)
233{ 647{
234 return sv_cmp (HeSVKEY_force (*(HE **)a), HeSVKEY_force (*(HE **)b)); 648 return sv_cmp (HeSVKEY_force (*(HE **)b), HeSVKEY_force (*(HE **)a));
235} 649}
236 650
237static void 651static void
238encode_hv (enc_t *enc, HV *hv) 652encode_hv (enc_t *enc, HV *hv)
239{ 653{
240 int count, i; 654 HE *he;
241 655
242 encode_ch (enc, '{'); NL; ++enc->indent; 656 if (enc->indent >= enc->json.max_depth)
657 croak (ERR_NESTING_EXCEEDED);
243 658
244 if ((count = hv_iterinit (hv))) 659 encode_ch (enc, '{');
245 { 660
246 // for canonical output we have to sort by keys first 661 // for canonical output we have to sort by keys first
247 // actually, this is mostly due to the stupid so-called 662 // actually, this is mostly due to the stupid so-called
248 // security workaround added somewhere in 5.8.x. 663 // security workaround added somewhere in 5.8.x
249 // that randomises hash orderings 664 // that randomises hash orderings
250 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))
251 { 670 {
252 HE *he, *hes [count]; 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 {
253 int fast = 1; 685 int i, fast = 1;
686 HE *hes_stack [STACK_HES];
687 HE **hes = hes_stack;
688
689 // allocate larger arrays on the heap
690 if (count > STACK_HES)
691 {
692 SV *sv = sv_2mortal (NEWSV (0, count * sizeof (*hes)));
693 hes = (HE **)SvPVX (sv);
694 }
254 695
255 i = 0; 696 i = 0;
256 while ((he = hv_iternext (hv))) 697 while ((he = hv_iternext (hv)))
257 { 698 {
258 hes [i++] = he; 699 hes [i++] = he;
264 705
265 if (fast) 706 if (fast)
266 qsort (hes, count, sizeof (HE *), he_cmp_fast); 707 qsort (hes, count, sizeof (HE *), he_cmp_fast);
267 else 708 else
268 { 709 {
269 // hack to disable "use bytes" 710 // hack to forcefully disable "use bytes"
270 COP *oldcop = PL_curcop, cop; 711 COP cop = *PL_curcop;
271 cop.op_private = 0; 712 cop.op_private = 0;
713
714 ENTER;
715 SAVETMPS;
716
717 SAVEVPTR (PL_curcop);
272 PL_curcop = &cop; 718 PL_curcop = &cop;
273 719
274 SAVETMPS;
275 qsort (hes, count, sizeof (HE *), he_cmp_slow); 720 qsort (hes, count, sizeof (HE *), he_cmp_slow);
721
276 FREETMPS; 722 FREETMPS;
277 723 LEAVE;
278 PL_curcop = oldcop;
279 } 724 }
280 725
281 for (i = 0; i < count; ++i) 726 encode_nl (enc); ++enc->indent;
727
728 while (count--)
282 { 729 {
283 INDENT; 730 encode_indent (enc);
731 he = hes [count];
284 encode_he (enc, hes [i]); 732 encode_hk (enc, he);
733 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
285 734
286 if (i < count - 1) 735 if (count)
287 COMMA; 736 encode_comma (enc);
288 } 737 }
289 738
290 NL; 739 encode_nl (enc); --enc->indent; encode_indent (enc);
291 } 740 }
741 }
742 else
743 {
744 if (hv_iterinit (hv) || SvMAGICAL (hv))
745 if ((he = hv_iternext (hv)))
746 {
747 encode_nl (enc); ++enc->indent;
748
749 for (;;)
750 {
751 encode_indent (enc);
752 encode_hk (enc, he);
753 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
754
755 if (!(he = hv_iternext (hv)))
756 break;
757
758 encode_comma (enc);
759 }
760
761 encode_nl (enc); --enc->indent; encode_indent (enc);
762 }
763 }
764
765 encode_ch (enc, '}');
766}
767
768// encode objects, arrays and special \0=false and \1=true values.
769static void
770encode_rv (enc_t *enc, SV *sv)
771{
772 svtype svt;
773 GV *method;
774
775 SvGETMAGIC (sv);
776 svt = SvTYPE (sv);
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 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);
292 else 859 else
293 { 860 croak ("encountered object '%s', but neither allow_blessed, convert_blessed nor allow_tags settings are enabled (or TO_JSON/FREEZE method missing)",
294 SV *sv; 861 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
295 HE *he = hv_iternext (hv); 862 }
296 863 else if (svt == SVt_PVHV)
297 for (;;) 864 encode_hv (enc, (HV *)sv);
298 { 865 else if (svt == SVt_PVAV)
299 INDENT; 866 encode_av (enc, (AV *)sv);
300 encode_he (enc, he); 867 else if (svt < SVt_PVAV)
301
302 if (!(he = hv_iternext (hv)))
303 break;
304
305 COMMA;
306 }
307
308 NL;
309 }
310 } 868 {
869 int bool_type = ref_bool_type (sv);
311 870
312 --enc->indent; INDENT; encode_ch (enc, '}'); 871 if (bool_type == 1)
872 encode_str (enc, "true", 4, 0);
873 else if (bool_type == 0)
874 encode_str (enc, "false", 5, 0);
875 else if (enc->json.flags & F_ALLOW_UNKNOWN)
876 encode_str (enc, "null", 4, 0);
877 else
878 croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1",
879 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
880 }
881 else if (enc->json.flags & F_ALLOW_UNKNOWN)
882 encode_str (enc, "null", 4, 0);
883 else
884 croak ("encountered %s, but JSON can only represent references to arrays or hashes",
885 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
313} 886}
314 887
315static void 888static void
316encode_sv (enc_t *enc, SV *sv) 889encode_sv (enc_t *enc, SV *sv)
317{ 890{
891 SvGETMAGIC (sv);
892
318 if (SvPOKp (sv)) 893 if (SvPOKp (sv))
319 { 894 {
320 STRLEN len; 895 STRLEN len;
321 char *str = SvPV (sv, len); 896 char *str = SvPV (sv, len);
322 encode_ch (enc, '"'); 897 encode_ch (enc, '"');
323 encode_str (enc, str, len, SvUTF8 (sv)); 898 encode_str (enc, str, len, SvUTF8 (sv));
324 encode_ch (enc, '"'); 899 encode_ch (enc, '"');
325 } 900 }
326 else if (SvNOKp (sv)) 901 else if (SvNOKp (sv))
327 { 902 {
903 // trust that perl will do the right thing w.r.t. JSON syntax.
328 need (enc, NV_DIG + 32); 904 need (enc, NV_DIG + 32);
329 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur); 905 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
330 enc->cur += strlen (enc->cur); 906 enc->cur += strlen (enc->cur);
331 } 907 }
332 else if (SvIOKp (sv)) 908 else if (SvIOKp (sv))
333 { 909 {
910 // we assume we can always read an IV as a UV and vice versa
911 // we assume two's complement
912 // we assume no aliasing issues in the union
913 if (SvIsUV (sv) ? SvUVX (sv) <= 59000
914 : SvIVX (sv) <= 59000 && SvIVX (sv) >= -59000)
915 {
916 // optimise the "small number case"
917 // code will likely be branchless and use only a single multiplication
918 // works for numbers up to 59074
919 I32 i = SvIVX (sv);
920 U32 u;
921 char digit, nz = 0;
922
334 need (enc, 64); 923 need (enc, 6);
924
925 *enc->cur = '-'; enc->cur += i < 0 ? 1 : 0;
926 u = i < 0 ? -i : i;
927
928 // convert to 4.28 fixed-point representation
929 u = u * ((0xfffffff + 10000) / 10000); // 10**5, 5 fractional digits
930
931 // now output digit by digit, each time masking out the integer part
932 // and multiplying by 5 while moving the decimal point one to the right,
933 // resulting in a net multiplication by 10.
934 // we always write the digit to memory but conditionally increment
935 // the pointer, to enable the use of conditional move instructions.
936 digit = u >> 28; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0xfffffffUL) * 5;
937 digit = u >> 27; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x7ffffffUL) * 5;
938 digit = u >> 26; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x3ffffffUL) * 5;
939 digit = u >> 25; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x1ffffffUL) * 5;
940 digit = u >> 24; *enc->cur = digit + '0'; enc->cur += 1; // correctly generate '0'
941 }
942 else
943 {
944 // large integer, use the (rather slow) snprintf way.
945 need (enc, IVUV_MAXCHARS);
335 enc->cur += 946 enc->cur +=
336 SvIsUV(sv) 947 SvIsUV(sv)
337 ? snprintf (enc->cur, 64, "%"UVuf, (UV)SvUVX (sv)) 948 ? snprintf (enc->cur, IVUV_MAXCHARS, "%"UVuf, (UV)SvUVX (sv))
338 : snprintf (enc->cur, 64, "%"IVdf, (IV)SvIVX (sv)); 949 : snprintf (enc->cur, IVUV_MAXCHARS, "%"IVdf, (IV)SvIVX (sv));
950 }
339 } 951 }
340 else if (SvROK (sv)) 952 else if (SvROK (sv))
341 { 953 encode_rv (enc, SvRV (sv));
342 if (!--enc->max_recurse) 954 else if (!SvOK (sv) || enc->json.flags & F_ALLOW_UNKNOWN)
343 croak ("data structure too deep (hit recursion limit)");
344
345 sv = SvRV (sv);
346
347 switch (SvTYPE (sv))
348 {
349 case SVt_PVAV: encode_av (enc, (AV *)sv); break;
350 case SVt_PVHV: encode_hv (enc, (HV *)sv); break;
351
352 default:
353 croak ("JSON can only represent references to arrays or hashes");
354 }
355 }
356 else if (!SvOK (sv))
357 encode_str (enc, "null", 4, 0); 955 encode_str (enc, "null", 4, 0);
358 else 956 else
359 croak ("encountered perl type that JSON cannot handle"); 957 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, check your input data",
958 SvPV_nolen (sv), (unsigned int)SvFLAGS (sv));
360} 959}
361 960
362static SV * 961static SV *
363encode_json (SV *scalar, UV flags) 962encode_json (SV *scalar, JSON *json)
364{ 963{
365 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar))
366 croak ("hash- or arraref required (not a simple scalar, use allow_nonref to allow this)");
367
368 enc_t enc; 964 enc_t enc;
369 enc.flags = flags; 965
966 if (!(json->flags & F_ALLOW_NONREF) && json_nonref (scalar))
967 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)");
968
969 enc.json = *json;
370 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 970 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
371 enc.cur = SvPVX (enc.sv); 971 enc.cur = SvPVX (enc.sv);
372 enc.end = SvEND (enc.sv); 972 enc.end = SvEND (enc.sv);
373 enc.max_recurse = 0;
374 enc.indent = 0; 973 enc.indent = 0;
974 enc.limit = enc.json.flags & F_ASCII ? 0x000080UL
975 : enc.json.flags & F_LATIN1 ? 0x000100UL
976 : 0x110000UL;
375 977
376 SvPOK_only (enc.sv); 978 SvPOK_only (enc.sv);
377 encode_sv (&enc, scalar); 979 encode_sv (&enc, scalar);
980 encode_nl (&enc);
378 981
982 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
983 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings
984
379 if (!(flags & (F_ASCII | F_UTF8))) 985 if (!(enc.json.flags & (F_ASCII | F_LATIN1 | F_UTF8)))
380 SvUTF8_on (enc.sv); 986 SvUTF8_on (enc.sv);
381 987
382 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); 988 if (enc.json.flags & F_SHRINK)
989 shrink (enc.sv);
990
383 return enc.sv; 991 return enc.sv;
384} 992}
385 993
386///////////////////////////////////////////////////////////////////////////// 994/////////////////////////////////////////////////////////////////////////////
995// decoder
387 996
388#define WS \ 997// structure used for decoding JSON
998typedef struct
999{
1000 char *cur; // current parser pointer
1001 char *end; // end of input string
1002 const char *err; // parse error, if != 0
1003 JSON json;
1004 U32 depth; // recursion depth
1005 U32 maxdepth; // recursion depth limit
1006} dec_t;
1007
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
1018decode_ws (dec_t *dec)
1019{
389 for (;;) \ 1020 for (;;)
390 { \ 1021 {
391 char ch = *dec->cur; \ 1022 char ch = *dec->cur;
1023
392 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 }
393 || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)) \ 1036 else if (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)
394 break; \ 1037 break; // parse error, but let higher level handle it, gives better error messages
1038
395 ++dec->cur; \ 1039 ++dec->cur;
396 } 1040 }
1041}
397 1042
398#define ERR(reason) SB dec->err = reason; goto fail; SE 1043#define ERR(reason) SB dec->err = reason; goto fail; SE
1044
399#define EXPECT_CH(ch) SB \ 1045#define EXPECT_CH(ch) SB \
400 if (*dec->cur != ch) \ 1046 if (*dec->cur != ch) \
401 ERR (# ch " expected"); \ 1047 ERR (# ch " expected"); \
402 ++dec->cur; \ 1048 ++dec->cur; \
403 SE 1049 SE
404 1050
1051#define DEC_INC_DEPTH if (++dec->depth > dec->json.max_depth) ERR (ERR_NESTING_EXCEEDED)
1052#define DEC_DEC_DEPTH --dec->depth
1053
405static SV *decode_sv (dec_t *dec); 1054static SV *decode_sv (dec_t *dec);
406
407#define APPEND_CH(ch) SB \
408 SvGROW (sv, cur + 1 + 1); \
409 SvPVX (sv)[cur++] = (ch); \
410 SE
411 1055
412static signed char decode_hexdigit[256]; 1056static signed char decode_hexdigit[256];
413 1057
414static UV 1058static UV
415decode_4hex (dec_t *dec) 1059decode_4hex (dec_t *dec)
416{ 1060{
417 signed char d1, d2, d3, d4; 1061 signed char d1, d2, d3, d4;
1062 unsigned char *cur = (unsigned char *)dec->cur;
418 1063
419 d1 = decode_hexdigit [((unsigned char *)dec->cur) [0]]; 1064 d1 = decode_hexdigit [cur [0]]; if (expect_false (d1 < 0)) ERR ("exactly four hexadecimal digits expected");
420 if (d1 < 0) ERR ("four hexadecimal digits expected"); 1065 d2 = decode_hexdigit [cur [1]]; if (expect_false (d2 < 0)) ERR ("exactly four hexadecimal digits expected");
421 d2 = decode_hexdigit [((unsigned char *)dec->cur) [1]]; 1066 d3 = decode_hexdigit [cur [2]]; if (expect_false (d3 < 0)) ERR ("exactly four hexadecimal digits expected");
422 if (d2 < 0) ERR ("four hexadecimal digits expected"); 1067 d4 = decode_hexdigit [cur [3]]; if (expect_false (d4 < 0)) ERR ("exactly four hexadecimal digits expected");
423 d3 = decode_hexdigit [((unsigned char *)dec->cur) [2]];
424 if (d3 < 0) ERR ("four hexadecimal digits expected");
425 d4 = decode_hexdigit [((unsigned char *)dec->cur) [3]];
426 if (d4 < 0) ERR ("four hexadecimal digits expected");
427 1068
428 dec->cur += 4; 1069 dec->cur += 4;
429 1070
430 return ((UV)d1) << 12 1071 return ((UV)d1) << 12
431 | ((UV)d2) << 8 1072 | ((UV)d2) << 8
437} 1078}
438 1079
439static SV * 1080static SV *
440decode_str (dec_t *dec) 1081decode_str (dec_t *dec)
441{ 1082{
442 SV *sv = NEWSV (0,2); 1083 SV *sv = 0;
443 STRLEN cur = 0;
444 int utf8 = 0; 1084 int utf8 = 0;
1085 char *dec_cur = dec->cur;
445 1086
446 for (;;) 1087 do
447 { 1088 {
448 unsigned char ch = *(unsigned char *)dec->cur; 1089 char buf [SHORT_STRING_LEN + UTF8_MAXBYTES];
1090 char *cur = buf;
449 1091
450 if (ch == '"') 1092 do
451 break;
452 else if (ch == '\\')
453 { 1093 {
454 switch (*++dec->cur) 1094 unsigned char ch = *(unsigned char *)dec_cur++;
1095
1096 if (expect_false (ch == '"'))
455 { 1097 {
456 case '\\': 1098 --dec_cur;
457 case '/': 1099 break;
458 case '"': APPEND_CH (*dec->cur++); break; 1100 }
459 1101 else if (expect_false (ch == '\\'))
460 case 'b': APPEND_CH ('\010'); ++dec->cur; break; 1102 {
461 case 't': APPEND_CH ('\011'); ++dec->cur; break; 1103 switch (*dec_cur)
462 case 'n': APPEND_CH ('\012'); ++dec->cur; break;
463 case 'f': APPEND_CH ('\014'); ++dec->cur; break;
464 case 'r': APPEND_CH ('\015'); ++dec->cur; break;
465
466 case 'u':
467 { 1104 {
468 UV lo, hi; 1105 case '\\':
469 ++dec->cur; 1106 case '/':
1107 case '"': *cur++ = *dec_cur++; break;
470 1108
471 hi = decode_4hex (dec); 1109 case 'b': ++dec_cur; *cur++ = '\010'; break;
472 if (hi == (UV)-1) 1110 case 't': ++dec_cur; *cur++ = '\011'; break;
473 goto fail; 1111 case 'n': ++dec_cur; *cur++ = '\012'; break;
1112 case 'f': ++dec_cur; *cur++ = '\014'; break;
1113 case 'r': ++dec_cur; *cur++ = '\015'; break;
474 1114
475 // possibly a surrogate pair 1115 case 'u':
476 if (hi >= 0xd800 && hi < 0xdc00)
477 { 1116 {
478 if (dec->cur [0] != '\\' || dec->cur [1] != 'u') 1117 UV lo, hi;
479 ERR ("illegal surrogate character"); 1118 ++dec_cur;
480 1119
481 dec->cur += 2; 1120 dec->cur = dec_cur;
482
483 lo = decode_4hex (dec); 1121 hi = decode_4hex (dec);
1122 dec_cur = dec->cur;
484 if (lo == (UV)-1) 1123 if (hi == (UV)-1)
485 goto fail; 1124 goto fail;
486 1125
1126 // possibly a surrogate pair
1127 if (hi >= 0xd800)
1128 if (hi < 0xdc00)
1129 {
1130 if (dec_cur [0] != '\\' || dec_cur [1] != 'u')
1131 ERR ("missing low surrogate character in surrogate pair");
1132
1133 dec_cur += 2;
1134
1135 dec->cur = dec_cur;
1136 lo = decode_4hex (dec);
1137 dec_cur = dec->cur;
1138 if (lo == (UV)-1)
1139 goto fail;
1140
487 if (lo < 0xdc00 || lo >= 0xe000) 1141 if (lo < 0xdc00 || lo >= 0xe000)
488 ERR ("surrogate pair expected"); 1142 ERR ("surrogate pair expected");
489 1143
490 hi = (hi - 0xD800) * 0x400 + (lo - 0xDC00) + 0x10000; 1144 hi = (hi - 0xD800) * 0x400 + (lo - 0xDC00) + 0x10000;
1145 }
1146 else if (hi < 0xe000)
1147 ERR ("missing high surrogate character in surrogate pair");
1148
1149 if (hi >= 0x80)
1150 {
1151 utf8 = 1;
1152
1153 cur = encode_utf8 (cur, hi);
1154 }
1155 else
1156 *cur++ = hi;
491 } 1157 }
492 else if (lo >= 0xdc00 && lo < 0xe000)
493 ERR ("illegal surrogate character");
494
495 if (hi >= 0x80)
496 { 1158 break;
497 utf8 = 1;
498 1159
499 SvGROW (sv, cur + 4 + 1); // at most 4 bytes for 21 bits
500 cur = (char *)uvuni_to_utf8_flags (SvPVX (sv) + cur, hi, 0) - SvPVX (sv);
501 }
502 else 1160 default:
503 APPEND_CH (hi); 1161 --dec_cur;
1162 ERR ("illegal backslash escape sequence in string");
504 } 1163 }
1164 }
1165 else if (expect_true (ch >= 0x20 && ch < 0x80))
1166 *cur++ = ch;
1167 else if (ch >= 0x80)
1168 {
1169 STRLEN clen;
1170
1171 --dec_cur;
1172
1173 decode_utf8 (dec_cur, dec->end - dec_cur, &clen);
1174 if (clen == (STRLEN)-1)
1175 ERR ("malformed UTF-8 character in JSON string");
1176
1177 do
1178 *cur++ = *dec_cur++;
1179 while (--clen);
1180
1181 utf8 = 1;
1182 }
1183 else if (ch == '\t' && dec->json.flags & F_RELAXED)
1184 *cur++ = ch;
1185 else
1186 {
1187 --dec_cur;
1188
1189 if (!ch)
1190 ERR ("unexpected end of string while parsing JSON string");
505 break; 1191 else
1192 ERR ("invalid character encountered while parsing JSON string");
506 } 1193 }
507 } 1194 }
508 else if (ch >= 0x20 && ch <= 0x7f) 1195 while (cur < buf + SHORT_STRING_LEN);
509 APPEND_CH (*dec->cur++); 1196
510 else if (ch >= 0x80) 1197 {
1198 STRLEN len = cur - buf;
1199
1200 if (sv)
511 { 1201 {
512 STRLEN clen; 1202 STRLEN cur = SvCUR (sv);
513 UV uch = utf8n_to_uvuni (dec->cur, dec->end - dec->cur, &clen, UTF8_CHECK_ONLY);
514 if (clen < 0)
515 ERR ("malformed UTF-8 character in string, cannot convert to JSON");
516 1203
517 SvGROW (sv, cur + clen + 1); // at most 4 bytes for 21 bits 1204 if (SvLEN (sv) - cur <= len)
518 memcpy (SvPVX (sv) + cur, dec->cur, clen); 1205 json_sv_grow (sv, cur, len);
519 dec->cur += clen; 1206
1207 memcpy (SvPVX (sv) + SvCUR (sv), buf, len);
1208 SvCUR_set (sv, SvCUR (sv) + len);
520 } 1209 }
521 else 1210 else
522 ERR ("invalid character encountered"); 1211 sv = newSVpvn (buf, len);
523 } 1212 }
1213 }
1214 while (*dec_cur != '"');
524 1215
525 ++dec->cur; 1216 ++dec_cur;
526 1217
1218 if (sv)
1219 {
527 SvPOK_only (sv); 1220 SvPOK_only (sv);
528
529 SvCUR_set (sv, cur);
530 *SvEND (sv) = 0; 1221 *SvEND (sv) = 0;
531 1222
532 if (utf8) 1223 if (utf8)
533 SvUTF8_on (sv); 1224 SvUTF8_on (sv);
1225 }
1226 else
1227 sv = newSVpvn ("", 0);
534 1228
1229 dec->cur = dec_cur;
535 return sv; 1230 return sv;
536 1231
537fail: 1232fail:
538 SvREFCNT_dec (sv); 1233 dec->cur = dec_cur;
539 return 0; 1234 return 0;
540} 1235}
541 1236
542static SV * 1237static SV *
543decode_num (dec_t *dec) 1238decode_num (dec_t *dec)
553 { 1248 {
554 ++dec->cur; 1249 ++dec->cur;
555 if (*dec->cur >= '0' && *dec->cur <= '9') 1250 if (*dec->cur >= '0' && *dec->cur <= '9')
556 ERR ("malformed number (leading zero must not be followed by another digit)"); 1251 ERR ("malformed number (leading zero must not be followed by another digit)");
557 } 1252 }
558 1253 else if (*dec->cur < '0' || *dec->cur > '9')
559 // int 1254 ERR ("malformed number (no digits after initial minus)");
1255 else
1256 do
1257 {
1258 ++dec->cur;
1259 }
560 while (*dec->cur >= '0' && *dec->cur <= '9') 1260 while (*dec->cur >= '0' && *dec->cur <= '9');
561 ++dec->cur;
562 1261
563 // [frac] 1262 // [frac]
564 if (*dec->cur == '.') 1263 if (*dec->cur == '.')
565 { 1264 {
566 is_nv = 1; 1265 ++dec->cur;
1266
1267 if (*dec->cur < '0' || *dec->cur > '9')
1268 ERR ("malformed number (no digits after decimal point)");
567 1269
568 do 1270 do
569 { 1271 {
570 ++dec->cur; 1272 ++dec->cur;
571 } 1273 }
572 while (*dec->cur >= '0' && *dec->cur <= '9'); 1274 while (*dec->cur >= '0' && *dec->cur <= '9');
1275
1276 is_nv = 1;
573 } 1277 }
574 1278
575 // [exp] 1279 // [exp]
576 if (*dec->cur == 'e' || *dec->cur == 'E') 1280 if (*dec->cur == 'e' || *dec->cur == 'E')
577 { 1281 {
578 is_nv = 1;
579
580 ++dec->cur; 1282 ++dec->cur;
1283
581 if (*dec->cur == '-' || *dec->cur == '+') 1284 if (*dec->cur == '-' || *dec->cur == '+')
582 ++dec->cur; 1285 ++dec->cur;
583 1286
1287 if (*dec->cur < '0' || *dec->cur > '9')
1288 ERR ("malformed number (no digits after exp sign)");
1289
1290 do
1291 {
1292 ++dec->cur;
1293 }
584 while (*dec->cur >= '0' && *dec->cur <= '9') 1294 while (*dec->cur >= '0' && *dec->cur <= '9');
585 ++dec->cur; 1295
1296 is_nv = 1;
586 } 1297 }
587 1298
588 if (!is_nv) 1299 if (!is_nv)
589 { 1300 {
590 UV uv; 1301 int len = dec->cur - start;
591 int numtype = grok_number (start, dec->cur - start, &uv); 1302
592 if (numtype & IS_NUMBER_IN_UV) 1303 // special case the rather common 1..5-digit-int case
593 if (numtype & IS_NUMBER_NEG) 1304 if (*start == '-')
1305 switch (len)
594 { 1306 {
595 if (uv < (UV)IV_MIN) 1307 case 2: return newSViv (-(IV)( start [1] - '0' * 1));
596 return newSViv (-(IV)uv); 1308 case 3: return newSViv (-(IV)( start [1] * 10 + start [2] - '0' * 11));
1309 case 4: return newSViv (-(IV)( start [1] * 100 + start [2] * 10 + start [3] - '0' * 111));
1310 case 5: return newSViv (-(IV)( start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111));
1311 case 6: return newSViv (-(IV)(start [1] * 10000 + start [2] * 1000 + start [3] * 100 + start [4] * 10 + start [5] - '0' * 11111));
597 } 1312 }
1313 else
1314 switch (len)
1315 {
1316 case 1: return newSViv ( start [0] - '0' * 1);
1317 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11);
1318 case 3: return newSViv ( start [0] * 100 + start [1] * 10 + start [2] - '0' * 111);
1319 case 4: return newSViv ( start [0] * 1000 + start [1] * 100 + start [2] * 10 + start [3] - '0' * 1111);
1320 case 5: return newSViv ( start [0] * 10000 + start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 11111);
1321 }
1322
1323 {
1324 UV uv;
1325 int numtype = grok_number (start, len, &uv);
1326 if (numtype & IS_NUMBER_IN_UV)
1327 if (numtype & IS_NUMBER_NEG)
1328 {
1329 if (uv < (UV)IV_MIN)
1330 return newSViv (-(IV)uv);
1331 }
598 else 1332 else
599 return newSVuv (uv); 1333 return newSVuv (uv);
600 } 1334 }
601 1335
1336 len -= *start == '-' ? 1 : 0;
1337
1338 // does not fit into IV or UV, try NV
1339 if (len <= NV_DIG)
1340 // fits into NV without loss of precision
1341 return newSVnv (json_atof (start));
1342
1343 // everything else fails, convert it to a string
1344 return newSVpvn (start, dec->cur - start);
1345 }
1346
1347 // loss of precision here
602 return newSVnv (Atof (start)); 1348 return newSVnv (json_atof (start));
603 1349
604fail: 1350fail:
605 return 0; 1351 return 0;
606} 1352}
607 1353
608static SV * 1354static SV *
609decode_av (dec_t *dec) 1355decode_av (dec_t *dec)
610{ 1356{
611 AV *av = newAV (); 1357 AV *av = newAV ();
612 1358
1359 DEC_INC_DEPTH;
1360 decode_ws (dec);
1361
1362 if (*dec->cur == ']')
1363 ++dec->cur;
1364 else
613 for (;;) 1365 for (;;)
614 { 1366 {
615 SV *value; 1367 SV *value;
616 1368
617 value = decode_sv (dec); 1369 value = decode_sv (dec);
618 if (!value) 1370 if (!value)
619 goto fail; 1371 goto fail;
620 1372
621 av_push (av, value); 1373 av_push (av, value);
622 1374
623 WS; 1375 decode_ws (dec);
624 1376
625 if (*dec->cur == ']') 1377 if (*dec->cur == ']')
626 { 1378 {
627 ++dec->cur; 1379 ++dec->cur;
628 break; 1380 break;
629 } 1381 }
630 1382
631 if (*dec->cur != ',') 1383 if (*dec->cur != ',')
632 ERR (", or ] expected while parsing array"); 1384 ERR (", or ] expected while parsing array");
633 1385
634 ++dec->cur; 1386 ++dec->cur;
1387
1388 decode_ws (dec);
1389
1390 if (*dec->cur == ']' && dec->json.flags & F_RELAXED)
1391 {
1392 ++dec->cur;
1393 break;
1394 }
635 } 1395 }
636 1396
1397 DEC_DEC_DEPTH;
637 return newRV_noinc ((SV *)av); 1398 return newRV_noinc ((SV *)av);
638 1399
639fail: 1400fail:
640 SvREFCNT_dec (av); 1401 SvREFCNT_dec (av);
1402 DEC_DEC_DEPTH;
641 return 0; 1403 return 0;
642} 1404}
643 1405
644static SV * 1406static SV *
645decode_hv (dec_t *dec) 1407decode_hv (dec_t *dec)
646{ 1408{
1409 SV *sv;
647 HV *hv = newHV (); 1410 HV *hv = newHV ();
648 1411
1412 DEC_INC_DEPTH;
1413 decode_ws (dec);
1414
1415 if (*dec->cur == '}')
1416 ++dec->cur;
1417 else
649 for (;;) 1418 for (;;)
650 { 1419 {
651 SV *key, *value;
652
653 WS; EXPECT_CH ('"'); 1420 EXPECT_CH ('"');
654 1421
655 key = decode_str (dec); 1422 // heuristic: assume that
656 if (!key) 1423 // a) decode_str + hv_store_ent are abysmally slow.
657 goto fail; 1424 // b) most hash keys are short, simple ascii text.
658 1425 // => try to "fast-match" such strings to avoid
659 WS; EXPECT_CH (':'); 1426 // the overhead of decode_str + hv_store_ent.
660
661 value = decode_sv (dec);
662 if (!value)
663 { 1427 {
1428 SV *value;
1429 char *p = dec->cur;
1430 char *e = p + 24; // only try up to 24 bytes
1431
1432 for (;;)
1433 {
1434 // the >= 0x80 is false on most architectures
1435 if (p == e || *p < 0x20 || *p >= 0x80 || *p == '\\')
1436 {
1437 // slow path, back up and use decode_str
1438 SV *key = decode_str (dec);
1439 if (!key)
1440 goto fail;
1441
1442 decode_ws (dec); EXPECT_CH (':');
1443
1444 decode_ws (dec);
1445 value = decode_sv (dec);
1446 if (!value)
1447 {
1448 SvREFCNT_dec (key);
1449 goto fail;
1450 }
1451
1452 hv_store_ent (hv, key, value, 0);
664 SvREFCNT_dec (key); 1453 SvREFCNT_dec (key);
1454
1455 break;
1456 }
1457 else if (*p == '"')
1458 {
1459 // fast path, got a simple key
1460 char *key = dec->cur;
1461 int len = p - key;
1462 dec->cur = p + 1;
1463
1464 decode_ws (dec); EXPECT_CH (':');
1465
1466 decode_ws (dec);
1467 value = decode_sv (dec);
1468 if (!value)
665 goto fail; 1469 goto fail;
1470
1471 hv_store (hv, key, len, value, 0);
1472
1473 break;
1474 }
1475
1476 ++p;
1477 }
666 } 1478 }
667 1479
668 //TODO: optimise 1480 decode_ws (dec);
669 hv_store_ent (hv, key, value, 0);
670 1481
671 WS;
672
673 if (*dec->cur == '}') 1482 if (*dec->cur == '}')
1483 {
1484 ++dec->cur;
1485 break;
1486 }
1487
1488 if (*dec->cur != ',')
1489 ERR (", or } expected while parsing object/hash");
1490
1491 ++dec->cur;
1492
1493 decode_ws (dec);
1494
1495 if (*dec->cur == '}' && dec->json.flags & F_RELAXED)
1496 {
1497 ++dec->cur;
1498 break;
1499 }
1500 }
1501
1502 DEC_DEC_DEPTH;
1503 sv = newRV_noinc ((SV *)hv);
1504
1505 // check filter callbacks
1506 if (dec->json.flags & F_HOOK)
1507 {
1508 if (dec->json.cb_sk_object && HvKEYS (hv) == 1)
674 { 1509 {
675 ++dec->cur; 1510 HE *cb, *he;
676 break; 1511
1512 hv_iterinit (hv);
1513 he = hv_iternext (hv);
1514 hv_iterinit (hv);
1515
1516 // the next line creates a mortal sv each time it's called.
1517 // might want to optimise this for common cases.
1518 cb = hv_fetch_ent (dec->json.cb_sk_object, hv_iterkeysv (he), 0, 0);
1519
1520 if (cb)
1521 {
1522 dSP;
1523 int count;
1524
1525 ENTER; SAVETMPS;
1526 PUSHMARK (SP);
1527 XPUSHs (HeVAL (he));
1528 sv_2mortal (sv);
1529
1530 PUTBACK; count = call_sv (HeVAL (cb), G_ARRAY); SPAGAIN;
1531
1532 if (count == 1)
1533 {
1534 sv = newSVsv (POPs);
1535 FREETMPS; LEAVE;
1536 return sv;
1537 }
1538 else if (count)
1539 croak ("filter_json_single_key_object callbacks must not return more than one scalar");
1540
1541 SvREFCNT_inc (sv);
1542 FREETMPS; LEAVE;
1543 }
677 } 1544 }
678 1545
679 if (*dec->cur != ',') 1546 if (dec->json.cb_object)
680 ERR (", or } expected while parsing object/hash"); 1547 {
1548 dSP;
1549 int count;
681 1550
682 ++dec->cur; 1551 ENTER; SAVETMPS;
683 } 1552 PUSHMARK (SP);
1553 XPUSHs (sv_2mortal (sv));
684 1554
685 return newRV_noinc ((SV *)hv); 1555 PUTBACK; count = call_sv (dec->json.cb_object, G_ARRAY); SPAGAIN;
1556
1557 if (count == 1)
1558 {
1559 sv = newSVsv (POPs);
1560 FREETMPS; LEAVE;
1561 return sv;
1562 }
1563 else if (count)
1564 croak ("filter_json_object callbacks must not return more than one scalar");
1565
1566 SvREFCNT_inc (sv);
1567 FREETMPS; LEAVE;
1568 }
1569 }
1570
1571 return sv;
686 1572
687fail: 1573fail:
688 SvREFCNT_dec (hv); 1574 SvREFCNT_dec (hv);
1575 DEC_DEC_DEPTH;
1576 return 0;
1577}
1578
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);
689 return 0; 1659 return 0;
690} 1660}
691 1661
692static SV * 1662static SV *
693decode_sv (dec_t *dec) 1663decode_sv (dec_t *dec)
694{ 1664{
695 WS; 1665 // the beauty of JSON: you need exactly one character lookahead
1666 // to parse everything.
696 switch (*dec->cur) 1667 switch (*dec->cur)
697 { 1668 {
698 case '"': ++dec->cur; return decode_str (dec); 1669 case '"': ++dec->cur; return decode_str (dec);
699 case '[': ++dec->cur; return decode_av (dec); 1670 case '[': ++dec->cur; return decode_av (dec);
700 case '{': ++dec->cur; return decode_hv (dec); 1671 case '{': ++dec->cur; return decode_hv (dec);
1672 case '(': return decode_tag (dec);
701 1673
702 case '-': 1674 case '-':
703 case '0': case '1': case '2': case '3': case '4': 1675 case '0': case '1': case '2': case '3': case '4':
704 case '5': case '6': case '7': case '8': case '9': 1676 case '5': case '6': case '7': case '8': case '9':
705 return decode_num (dec); 1677 return decode_num (dec);
706 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
707 case 't': 1694 case 't':
708 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1695 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
709 { 1696 {
710 dec->cur += 4; 1697 dec->cur += 4;
1698
1699 if (expect_false (!dec->json.v_true))
1700 dec->json.v_true = GET_BOOL (true);
1701
711 return newSViv (1); 1702 return newSVsv (dec->json.v_true);
712 } 1703 }
713 else 1704 else
714 ERR ("'true' expected"); 1705 ERR ("'true' expected");
715
716 break;
717
718 case 'f':
719 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
720 {
721 dec->cur += 5;
722 return newSViv (0);
723 }
724 else
725 ERR ("'false' expected");
726 1706
727 break; 1707 break;
728 1708
729 case 'n': 1709 case 'n':
730 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "null", 4)) 1710 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "null", 4))
731 { 1711 {
732 dec->cur += 4; 1712 dec->cur += 4;
733 return newSViv (1); 1713 return newSVsv (&PL_sv_undef);
734 } 1714 }
735 else 1715 else
736 ERR ("'null' expected"); 1716 ERR ("'null' expected");
737 1717
738 break; 1718 break;
739 1719
740 default: 1720 default:
741 ERR ("malformed json string"); 1721 ERR ("malformed JSON string, neither tag, array, object, number, string or atom");
742 break; 1722 break;
743 } 1723 }
744 1724
745fail: 1725fail:
746 return 0; 1726 return 0;
747} 1727}
748 1728
749static SV * 1729static SV *
750decode_json (SV *string, UV flags) 1730decode_json (SV *string, JSON *json, STRLEN *offset_return)
751{ 1731{
1732 dec_t dec;
752 SV *sv; 1733 SV *sv;
753 1734
754 if (!(flags & F_UTF8)) 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 */
1743 /*SvGETMAGIC (string);*/
1744 if (SvMAGICAL (string) || !SvPOK (string) || SvIsCOW_shared_hash (string))
1745 string = sv_2mortal (newSVsv (string));
1746
1747 SvUPGRADE (string, SVt_PV);
1748
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)
1767 croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu",
1768 (unsigned long)SvCUR (string), (unsigned long)json->max_size);
1769 }
1770
1771 if (DECODE_WANTS_OCTETS (json))
1772 sv_utf8_downgrade (string, 0);
1773 else
755 sv_utf8_upgrade (string); 1774 sv_utf8_upgrade (string);
756 1775
757 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP 1776 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
758 1777
759 dec_t dec; 1778 dec.json = *json;
760 dec.flags = flags;
761 dec.cur = SvPVX (string); 1779 dec.cur = SvPVX (string);
762 dec.end = SvEND (string); 1780 dec.end = SvEND (string);
763 dec.err = 0; 1781 dec.err = 0;
1782 dec.depth = 0;
764 1783
765 *dec.end = 1; // invalid anywhere 1784 if (dec.json.cb_object || dec.json.cb_sk_object)
1785 dec.json.flags |= F_HOOK;
1786
1787 *dec.end = 0; // this should basically be a nop, too, but make sure it's there
1788
1789 decode_ws (&dec);
766 sv = decode_sv (&dec); 1790 sv = decode_sv (&dec);
767 *dec.end = 0; 1791
1792 if (offset_return)
1793 *offset_return = dec.cur - SvPVX (string);
1794 else if (sv)
1795 {
1796 // check for trailing garbage
1797 decode_ws (&dec);
1798
1799 if (*dec.cur)
1800 {
1801 dec.err = "garbage after JSON object";
1802 SvREFCNT_dec (sv);
1803 sv = 0;
1804 }
1805 }
768 1806
769 if (!sv) 1807 if (!sv)
770 { 1808 {
771 IV offset = utf8_distance (dec.cur, SvPVX (string));
772 SV *uni = sv_newmortal (); 1809 SV *uni = sv_newmortal ();
773 1810
1811 // horrible hack to silence warning inside pv_uni_display
1812 COP cop = *PL_curcop;
1813 cop.cop_warnings = pWARN_NONE;
1814 ENTER;
1815 SAVEVPTR (PL_curcop);
1816 PL_curcop = &cop;
774 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);
1818 LEAVE;
1819
775 croak ("%s, at character %d (%s)", 1820 croak ("%s, at character offset %d (before \"%s\")",
776 dec.err, 1821 dec.err,
777 (int)offset, 1822 (int)ptr_to_index (string, dec.cur),
778 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); 1823 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
779 } 1824 }
780 1825
781 sv = sv_2mortal (sv); 1826 sv = sv_2mortal (sv);
782 1827
783 if (!(dec.flags & F_ALLOW_NONREF) && !SvROK (sv)) 1828 if (!(dec.json.flags & F_ALLOW_NONREF) && json_nonref (sv))
784 croak ("JSON object or array expected (but number, string, true, false or null found, 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)");
785 1830
786 return sv; 1831 return sv;
787} 1832}
788 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
1990}
1991
1992/////////////////////////////////////////////////////////////////////////////
1993// XS interface functions
1994
789MODULE = JSON::XS PACKAGE = JSON::XS 1995MODULE = JSON::XS PACKAGE = JSON::XS
790 1996
791BOOT: 1997BOOT:
792{ 1998{
793 int i; 1999 int i;
794 2000
795 memset (decode_hexdigit, 0xff, 256);
796 for (i = 10; i--; ) 2001 for (i = 0; i < 256; ++i)
797 decode_hexdigit ['0' + i] = i; 2002 decode_hexdigit [i] =
2003 i >= '0' && i <= '9' ? i - '0'
2004 : i >= 'a' && i <= 'f' ? i - 'a' + 10
2005 : i >= 'A' && i <= 'F' ? i - 'A' + 10
2006 : -1;
798 2007
799 for (i = 6; --i; ) 2008 json_stash = gv_stashpv ("JSON::XS" , 1);
800 { 2009 bool_stash = gv_stashpv ("Types::Serialiser::Boolean", 1);
801 decode_hexdigit ['a' + i] = 10 + i; 2010 bool_false = get_bool ("Types::Serialiser::false");
802 decode_hexdigit ['A' + i] = 10 + i; 2011 bool_true = get_bool ("Types::Serialiser::true");
2012
2013 sv_json = newSVpv ("JSON", 0);
2014 SvREADONLY_on (sv_json);
2015
2016 CvNODEBUG_on (get_cv ("JSON::XS::incr_text", 0)); /* the debugger completely breaks lvalue subs */
2017}
2018
2019PROTOTYPES: DISABLE
2020
2021void CLONE (...)
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.
2026 json_stash = 0;
2027 bool_stash = 0;
2028 bool_false = 0;
2029 bool_true = 0;
2030
2031void new (char *klass)
2032 PPCODE:
2033{
2034 SV *pv = NEWSV (0, sizeof (JSON));
2035 SvPOK_only (pv);
2036 json_init ((JSON *)SvPVX (pv));
2037 XPUSHs (sv_2mortal (sv_bless (
2038 newRV_noinc (pv),
2039 strEQ (klass, "JSON::XS") ? JSON_STASH : gv_stashpv (klass, 1)
2040 )));
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);
803 } 2056 }
804 2057
805 json_stash = gv_stashpv ("JSON::XS", 1); 2058void ascii (JSON *self, int enable = 1)
806} 2059 ALIAS:
2060 ascii = F_ASCII
2061 latin1 = F_LATIN1
2062 utf8 = F_UTF8
2063 indent = F_INDENT
2064 canonical = F_CANONICAL
2065 space_before = F_SPACE_BEFORE
2066 space_after = F_SPACE_AFTER
2067 pretty = F_PRETTY
2068 allow_nonref = F_ALLOW_NONREF
2069 shrink = F_SHRINK
2070 allow_blessed = F_ALLOW_BLESSED
2071 convert_blessed = F_CONV_BLESSED
2072 relaxed = F_RELAXED
2073 allow_unknown = F_ALLOW_UNKNOWN
2074 allow_tags = F_ALLOW_TAGS
2075 PPCODE:
2076{
2077 if (enable)
2078 self->flags |= ix;
2079 else
2080 self->flags &= ~ix;
807 2081
808SV *new (char *dummy) 2082 XPUSHs (ST (0));
2083}
2084
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
2101 PPCODE:
2102 XPUSHs (boolSV (self->flags & ix));
2103
2104void max_depth (JSON *self, U32 max_depth = 0x80000000UL)
2105 PPCODE:
2106 self->max_depth = max_depth;
2107 XPUSHs (ST (0));
2108
2109U32 get_max_depth (JSON *self)
809 CODE: 2110 CODE:
810 RETVAL = sv_bless (newRV_noinc (newSVuv (F_DEFAULT)), json_stash); 2111 RETVAL = self->max_depth;
811 OUTPUT: 2112 OUTPUT:
812 RETVAL 2113 RETVAL
813 2114
814SV *ascii (SV *self, int enable) 2115void max_size (JSON *self, U32 max_size = 0)
815 ALIAS: 2116 PPCODE:
816 ascii = F_ASCII 2117 self->max_size = max_size;
817 utf8 = F_UTF8 2118 XPUSHs (ST (0));
818 indent = F_INDENT 2119
819 canonical = F_CANONICAL 2120int get_max_size (JSON *self)
820 space_before = F_SPACE_BEFORE
821 space_after = F_SPACE_AFTER
822 json_rpc = F_JSON_RPC
823 pretty = F_PRETTY
824 allow_nonref = F_ALLOW_NONREF
825 CODE: 2121 CODE:
826{ 2122 RETVAL = self->max_size;
827 UV *uv = SvJSON (self);
828 if (enable)
829 *uv |= ix;
830 else
831 *uv &= ~ix;
832
833 RETVAL = newSVsv (self);
834}
835 OUTPUT: 2123 OUTPUT:
836 RETVAL 2124 RETVAL
837 2125
838void encode (SV *self, SV *scalar) 2126void filter_json_object (JSON *self, SV *cb = &PL_sv_undef)
839 PPCODE: 2127 PPCODE:
840 XPUSHs (encode_json (scalar, *SvJSON (self))); 2128{
2129 SvREFCNT_dec (self->cb_object);
2130 self->cb_object = SvOK (cb) ? newSVsv (cb) : 0;
841 2131
842void decode (SV *self, SV *jsonstr) 2132 XPUSHs (ST (0));
2133}
2134
2135void filter_json_single_key_object (JSON *self, SV *key, SV *cb = &PL_sv_undef)
843 PPCODE: 2136 PPCODE:
844 XPUSHs (decode_json (jsonstr, *SvJSON (self))); 2137{
2138 if (!self->cb_sk_object)
2139 self->cb_sk_object = newHV ();
845 2140
846void to_json (SV *scalar) 2141 if (SvOK (cb))
2142 hv_store_ent (self->cb_sk_object, key, newSVsv (cb), 0);
2143 else
2144 {
2145 hv_delete_ent (self->cb_sk_object, key, G_DISCARD, 0);
2146
2147 if (!HvKEYS (self->cb_sk_object))
2148 {
2149 SvREFCNT_dec (self->cb_sk_object);
2150 self->cb_sk_object = 0;
2151 }
2152 }
2153
2154 XPUSHs (ST (0));
2155}
2156
2157void encode (JSON *self, SV *scalar)
847 PPCODE: 2158 PPCODE:
848 XPUSHs (encode_json (scalar, F_UTF8)); 2159 PUTBACK; scalar = encode_json (scalar, self); SPAGAIN;
2160 XPUSHs (scalar);
849 2161
850void from_json (SV *jsonstr) 2162void decode (JSON *self, SV *jsonstr)
851 PPCODE: 2163 PPCODE:
852 XPUSHs (decode_json (jsonstr, F_UTF8)); 2164 PUTBACK; jsonstr = decode_json (jsonstr, self, 0); SPAGAIN;
2165 XPUSHs (jsonstr);
853 2166
2167void decode_prefix (JSON *self, SV *jsonstr)
2168 PPCODE:
2169{
2170 SV *sv;
2171 STRLEN offset;
2172 PUTBACK; sv = decode_json (jsonstr, self, &offset); SPAGAIN;
2173 EXTEND (SP, 2);
2174 PUSHs (sv);
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;
2299}
2300
2301void DESTROY (JSON *self)
2302 CODE:
2303 SvREFCNT_dec (self->v_false);
2304 SvREFCNT_dec (self->v_true);
2305 SvREFCNT_dec (self->cb_sk_object);
2306 SvREFCNT_dec (self->cb_object);
2307 SvREFCNT_dec (self->incr_text);
2308
2309PROTOTYPES: ENABLE
2310
2311void encode_json (SV *scalar)
2312 PPCODE:
2313{
2314 JSON json;
2315 json_init (&json);
2316 json.flags |= F_UTF8;
2317 PUTBACK; scalar = encode_json (scalar, &json); SPAGAIN;
2318 XPUSHs (scalar);
2319}
2320
2321void decode_json (SV *jsonstr)
2322 PPCODE:
2323{
2324 JSON json;
2325 json_init (&json);
2326 json.flags |= F_UTF8;
2327 PUTBACK; jsonstr = decode_json (jsonstr, &json, 0); SPAGAIN;
2328 XPUSHs (jsonstr);
2329}
2330

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines