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.39 by root, Mon Jun 11 03:42:57 2007 UTC vs.
Revision 1.77 by root, Tue Mar 25 06:37:38 2008 UTC

1#include "EXTERN.h" 1#include "EXTERN.h"
2#include "perl.h" 2#include "perl.h"
3#include "XSUB.h" 3#include "XSUB.h"
4 4
5#include "assert.h" 5#include <assert.h>
6#include "string.h" 6#include <string.h>
7#include "stdlib.h" 7#include <stdlib.h>
8#include "stdio.h" 8#include <stdio.h>
9#include <limits.h>
10#include <float.h>
9 11
10#if defined(__BORLANDC__) || defined(_MSC_VER) 12#if defined(__BORLANDC__) || defined(_MSC_VER)
11# define snprintf _snprintf // C compilers have this in stdio.h 13# define snprintf _snprintf // C compilers have this in stdio.h
12#endif 14#endif
13 15
16// some old perls do not have this, try to make it work, no
17// guarentees, though. if it breaks, you get to keep the pieces.
18#ifndef UTF8_MAXBYTES
19# define UTF8_MAXBYTES 13
20#endif
21
22#define IVUV_MAXCHARS (sizeof (UV) * CHAR_BIT * 28 / 93 + 2)
23
14#define F_ASCII 0x00000001UL 24#define F_ASCII 0x00000001UL
15#define F_LATIN1 0x00000002UL 25#define F_LATIN1 0x00000002UL
16#define F_UTF8 0x00000004UL 26#define F_UTF8 0x00000004UL
17#define F_INDENT 0x00000008UL 27#define F_INDENT 0x00000008UL
18#define F_CANONICAL 0x00000010UL 28#define F_CANONICAL 0x00000010UL
19#define F_SPACE_BEFORE 0x00000020UL 29#define F_SPACE_BEFORE 0x00000020UL
20#define F_SPACE_AFTER 0x00000040UL 30#define F_SPACE_AFTER 0x00000040UL
21#define F_ALLOW_NONREF 0x00000100UL 31#define F_ALLOW_NONREF 0x00000100UL
22#define F_SHRINK 0x00000200UL 32#define F_SHRINK 0x00000200UL
33#define F_ALLOW_BLESSED 0x00000400UL
34#define F_CONV_BLESSED 0x00000800UL
35#define F_RELAXED 0x00001000UL
36
23#define F_MAXDEPTH 0xf8000000UL 37#define F_MAXDEPTH 0xf8000000UL
24#define S_MAXDEPTH 27 38#define S_MAXDEPTH 27
39#define F_MAXSIZE 0x01f00000UL
40#define S_MAXSIZE 20
41#define F_HOOK 0x00080000UL // some hooks exist, so slow-path processing
25 42
26#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH)) 43#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH))
27 44#define DEC_SIZE(flags) (1UL << ((flags & F_MAXSIZE ) >> S_MAXSIZE ))
28// F_SELFCONVERT? <=> to_json/toJson
29// F_BLESSED? <=> { $__class__$ => }
30 45
31#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER 46#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER
32#define F_DEFAULT (9UL << S_MAXDEPTH) 47#define F_DEFAULT (9UL << S_MAXDEPTH)
33 48
34#define INIT_SIZE 32 // initial scalar size to be allocated 49#define INIT_SIZE 32 // initial scalar size to be allocated
38 53
39#define SB do { 54#define SB do {
40#define SE } while (0) 55#define SE } while (0)
41 56
42#if __GNUC__ >= 3 57#if __GNUC__ >= 3
43# define expect(expr,value) __builtin_expect ((expr),(value)) 58# define expect(expr,value) __builtin_expect ((expr), (value))
44# define inline inline 59# define INLINE static inline
45#else 60#else
46# define expect(expr,value) (expr) 61# define expect(expr,value) (expr)
47# define inline static 62# define INLINE static
48#endif 63#endif
49 64
50#define expect_false(expr) expect ((expr) != 0, 0) 65#define expect_false(expr) expect ((expr) != 0, 0)
51#define expect_true(expr) expect ((expr) != 0, 1) 66#define expect_true(expr) expect ((expr) != 0, 1)
52 67
68#define IN_RANGE_INC(type,val,beg,end) \
69 ((unsigned type)((unsigned type)(val) - (unsigned type)(beg)) \
70 <= (unsigned type)((unsigned type)(end) - (unsigned type)(beg)))
71
72#ifdef USE_ITHREADS
73# define JSON_SLOW 1
74# define JSON_STASH (json_stash ? json_stash : gv_stashpv ("JSON::XS", 1))
75#else
76# define JSON_SLOW 0
77# define JSON_STASH json_stash
78#endif
79
53static HV *json_stash; // JSON::XS:: 80static HV *json_stash, *json_boolean_stash; // JSON::XS::
81static SV *json_true, *json_false;
82
83enum {
84 INCR_M_WS = 0, // initial whitespace skipping, must be 0
85 INCR_M_STR, // inside string
86 INCR_M_BS, // inside backslash
87 INCR_M_JSON // outside anything, count nesting
88};
89
90#define INCR_DONE(json) (!(json)->incr_nest && (json)->incr_mode == INCR_M_JSON)
91
92typedef struct {
93 U32 flags;
94 SV *cb_object;
95 HV *cb_sk_object;
96
97 // for the incremental parser
98 SV *incr_text; // the source text so far
99 STRLEN incr_pos; // the current offset into the text
100 int incr_nest; // {[]}-nesting level
101 int incr_mode;
102} JSON;
54 103
55///////////////////////////////////////////////////////////////////////////// 104/////////////////////////////////////////////////////////////////////////////
56// utility functions 105// utility functions
57 106
58static UV * 107INLINE void
59SvJSON (SV *sv)
60{
61 if (!(SvROK (sv) && SvOBJECT (SvRV (sv)) && SvSTASH (SvRV (sv)) == json_stash))
62 croak ("object is not of type JSON::XS");
63
64 return &SvUVX (SvRV (sv));
65}
66
67static void
68shrink (SV *sv) 108shrink (SV *sv)
69{ 109{
70 sv_utf8_downgrade (sv, 1); 110 sv_utf8_downgrade (sv, 1);
71 if (SvLEN (sv) > SvCUR (sv) + 1) 111 if (SvLEN (sv) > SvCUR (sv) + 1)
72 { 112 {
81// decode an utf-8 character and return it, or (UV)-1 in 121// decode an utf-8 character and return it, or (UV)-1 in
82// case of an error. 122// case of an error.
83// we special-case "safe" characters from U+80 .. U+7FF, 123// we special-case "safe" characters from U+80 .. U+7FF,
84// but use the very good perl function to parse anything else. 124// but use the very good perl function to parse anything else.
85// note that we never call this function for a ascii codepoints 125// note that we never call this function for a ascii codepoints
86inline UV 126INLINE UV
87decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen) 127decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
88{ 128{
89 if (expect_false (s[0] > 0xdf || s[0] < 0xc2)) 129 if (expect_true (len >= 2
90 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY); 130 && IN_RANGE_INC (char, s[0], 0xc2, 0xdf)
91 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf) 131 && IN_RANGE_INC (char, s[1], 0x80, 0xbf)))
92 { 132 {
93 *clen = 2; 133 *clen = 2;
94 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f); 134 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
95 } 135 }
96 else 136 else
97 { 137 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY);
98 *clen = (STRLEN)-1; 138}
99 return (UV)-1; 139
100 } 140// likewise for encoding, also never called for ascii codepoints
141// this function takes advantage of this fact, although current gccs
142// seem to optimise the check for >= 0x80 away anyways
143INLINE unsigned char *
144encode_utf8 (unsigned char *s, UV ch)
145{
146 if (expect_false (ch < 0x000080))
147 *s++ = ch;
148 else if (expect_true (ch < 0x000800))
149 *s++ = 0xc0 | ( ch >> 6),
150 *s++ = 0x80 | ( ch & 0x3f);
151 else if ( ch < 0x010000)
152 *s++ = 0xe0 | ( ch >> 12),
153 *s++ = 0x80 | ((ch >> 6) & 0x3f),
154 *s++ = 0x80 | ( ch & 0x3f);
155 else if ( ch < 0x110000)
156 *s++ = 0xf0 | ( ch >> 18),
157 *s++ = 0x80 | ((ch >> 12) & 0x3f),
158 *s++ = 0x80 | ((ch >> 6) & 0x3f),
159 *s++ = 0x80 | ( ch & 0x3f);
160
161 return s;
101} 162}
102 163
103///////////////////////////////////////////////////////////////////////////// 164/////////////////////////////////////////////////////////////////////////////
104// encoder 165// encoder
105 166
107typedef struct 168typedef struct
108{ 169{
109 char *cur; // SvPVX (sv) + current output position 170 char *cur; // SvPVX (sv) + current output position
110 char *end; // SvEND (sv) 171 char *end; // SvEND (sv)
111 SV *sv; // result scalar 172 SV *sv; // result scalar
112 U32 flags; // F_* 173 JSON json;
113 U32 indent; // indentation level 174 U32 indent; // indentation level
114 U32 maxdepth; // max. indentation/recursion level 175 U32 maxdepth; // max. indentation/recursion level
176 UV limit; // escape character values >= this value when encoding
115} enc_t; 177} enc_t;
116 178
117inline void 179INLINE void
118need (enc_t *enc, STRLEN len) 180need (enc_t *enc, STRLEN len)
119{ 181{
120 if (expect_false (enc->cur + len >= enc->end)) 182 if (expect_false (enc->cur + len >= enc->end))
121 { 183 {
122 STRLEN cur = enc->cur - SvPVX (enc->sv); 184 STRLEN cur = enc->cur - SvPVX (enc->sv);
124 enc->cur = SvPVX (enc->sv) + cur; 186 enc->cur = SvPVX (enc->sv) + cur;
125 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1; 187 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
126 } 188 }
127} 189}
128 190
129inline void 191INLINE void
130encode_ch (enc_t *enc, char ch) 192encode_ch (enc_t *enc, char ch)
131{ 193{
132 need (enc, 1); 194 need (enc, 1);
133 *enc->cur++ = ch; 195 *enc->cur++ = ch;
134} 196}
178 STRLEN clen; 240 STRLEN clen;
179 UV uch; 241 UV uch;
180 242
181 if (is_utf8) 243 if (is_utf8)
182 { 244 {
183 //uch = utf8n_to_uvuni (str, end - str, &clen, UTF8_CHECK_ONLY);
184 uch = decode_utf8 (str, end - str, &clen); 245 uch = decode_utf8 (str, end - str, &clen);
185 if (clen == (STRLEN)-1) 246 if (clen == (STRLEN)-1)
186 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str); 247 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str);
187 } 248 }
188 else 249 else
189 { 250 {
190 uch = ch; 251 uch = ch;
191 clen = 1; 252 clen = 1;
192 } 253 }
193 254
194 if (uch > 0x10FFFFUL) 255 if (uch < 0x80/*0x20*/ || uch >= enc->limit)
195 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
196
197 if (uch < 0x80 || enc->flags & F_ASCII || (enc->flags & F_LATIN1 && uch > 0xFF))
198 { 256 {
199 if (uch > 0xFFFFUL) 257 if (uch >= 0x10000UL)
200 { 258 {
259 if (uch >= 0x110000UL)
260 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
261
201 need (enc, len += 11); 262 need (enc, len += 11);
202 sprintf (enc->cur, "\\u%04x\\u%04x", 263 sprintf (enc->cur, "\\u%04x\\u%04x",
203 (int)((uch - 0x10000) / 0x400 + 0xD800), 264 (int)((uch - 0x10000) / 0x400 + 0xD800),
204 (int)((uch - 0x10000) % 0x400 + 0xDC00)); 265 (int)((uch - 0x10000) % 0x400 + 0xDC00));
205 enc->cur += 12; 266 enc->cur += 12;
216 *enc->cur++ = hexdigit [(uch >> 0) & 15]; 277 *enc->cur++ = hexdigit [(uch >> 0) & 15];
217 } 278 }
218 279
219 str += clen; 280 str += clen;
220 } 281 }
221 else if (enc->flags & F_LATIN1) 282 else if (enc->json.flags & F_LATIN1)
222 { 283 {
223 *enc->cur++ = uch; 284 *enc->cur++ = uch;
224 str += clen; 285 str += clen;
225 } 286 }
226 else if (is_utf8) 287 else if (is_utf8)
233 while (--clen); 294 while (--clen);
234 } 295 }
235 else 296 else
236 { 297 {
237 need (enc, len += UTF8_MAXBYTES - 1); // never more than 11 bytes needed 298 need (enc, len += UTF8_MAXBYTES - 1); // never more than 11 bytes needed
238 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); 299 enc->cur = encode_utf8 (enc->cur, uch);
239 ++str; 300 ++str;
240 } 301 }
241 } 302 }
242 } 303 }
243 } 304 }
244 305
245 --len; 306 --len;
246 } 307 }
247} 308}
248 309
249inline void 310INLINE void
250encode_indent (enc_t *enc) 311encode_indent (enc_t *enc)
251{ 312{
252 if (enc->flags & F_INDENT) 313 if (enc->json.flags & F_INDENT)
253 { 314 {
254 int spaces = enc->indent * INDENT_STEP; 315 int spaces = enc->indent * INDENT_STEP;
255 316
256 need (enc, spaces); 317 need (enc, spaces);
257 memset (enc->cur, ' ', spaces); 318 memset (enc->cur, ' ', spaces);
258 enc->cur += spaces; 319 enc->cur += spaces;
259 } 320 }
260} 321}
261 322
262inline void 323INLINE void
263encode_space (enc_t *enc) 324encode_space (enc_t *enc)
264{ 325{
265 need (enc, 1); 326 need (enc, 1);
266 encode_ch (enc, ' '); 327 encode_ch (enc, ' ');
267} 328}
268 329
269inline void 330INLINE void
270encode_nl (enc_t *enc) 331encode_nl (enc_t *enc)
271{ 332{
272 if (enc->flags & F_INDENT) 333 if (enc->json.flags & F_INDENT)
273 { 334 {
274 need (enc, 1); 335 need (enc, 1);
275 encode_ch (enc, '\n'); 336 encode_ch (enc, '\n');
276 } 337 }
277} 338}
278 339
279inline void 340INLINE void
280encode_comma (enc_t *enc) 341encode_comma (enc_t *enc)
281{ 342{
282 encode_ch (enc, ','); 343 encode_ch (enc, ',');
283 344
284 if (enc->flags & F_INDENT) 345 if (enc->json.flags & F_INDENT)
285 encode_nl (enc); 346 encode_nl (enc);
286 else if (enc->flags & F_SPACE_AFTER) 347 else if (enc->json.flags & F_SPACE_AFTER)
287 encode_space (enc); 348 encode_space (enc);
288} 349}
289 350
290static void encode_sv (enc_t *enc, SV *sv); 351static void encode_sv (enc_t *enc, SV *sv);
291 352
295 int i, len = av_len (av); 356 int i, len = av_len (av);
296 357
297 if (enc->indent >= enc->maxdepth) 358 if (enc->indent >= enc->maxdepth)
298 croak ("data structure too deep (hit recursion limit)"); 359 croak ("data structure too deep (hit recursion limit)");
299 360
300 encode_ch (enc, '['); encode_nl (enc); 361 encode_ch (enc, '[');
301 ++enc->indent; 362
363 if (len >= 0)
364 {
365 encode_nl (enc); ++enc->indent;
302 366
303 for (i = 0; i <= len; ++i) 367 for (i = 0; i <= len; ++i)
304 { 368 {
369 SV **svp = av_fetch (av, i, 0);
370
305 encode_indent (enc); 371 encode_indent (enc);
306 encode_sv (enc, *av_fetch (av, i, 0));
307 372
373 if (svp)
374 encode_sv (enc, *svp);
375 else
376 encode_str (enc, "null", 4, 0);
377
308 if (i < len) 378 if (i < len)
309 encode_comma (enc); 379 encode_comma (enc);
310 } 380 }
311 381
382 encode_nl (enc); --enc->indent; encode_indent (enc);
383 }
384
312 encode_nl (enc); 385 encode_ch (enc, ']');
313
314 --enc->indent;
315 encode_indent (enc); encode_ch (enc, ']');
316} 386}
317 387
318static void 388static void
319encode_he (enc_t *enc, HE *he) 389encode_hk (enc_t *enc, HE *he)
320{ 390{
321 encode_ch (enc, '"'); 391 encode_ch (enc, '"');
322 392
323 if (HeKLEN (he) == HEf_SVKEY) 393 if (HeKLEN (he) == HEf_SVKEY)
324 { 394 {
334 else 404 else
335 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he)); 405 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he));
336 406
337 encode_ch (enc, '"'); 407 encode_ch (enc, '"');
338 408
339 if (enc->flags & F_SPACE_BEFORE) encode_space (enc); 409 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc);
340 encode_ch (enc, ':'); 410 encode_ch (enc, ':');
341 if (enc->flags & F_SPACE_AFTER ) encode_space (enc); 411 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc);
342 encode_sv (enc, HeVAL (he));
343} 412}
344 413
345// compare hash entries, used when all keys are bytestrings 414// compare hash entries, used when all keys are bytestrings
346static int 415static int
347he_cmp_fast (const void *a_, const void *b_) 416he_cmp_fast (const void *a_, const void *b_)
352 HE *b = *(HE **)b_; 421 HE *b = *(HE **)b_;
353 422
354 STRLEN la = HeKLEN (a); 423 STRLEN la = HeKLEN (a);
355 STRLEN lb = HeKLEN (b); 424 STRLEN lb = HeKLEN (b);
356 425
357 if (!(cmp = memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb))) 426 if (!(cmp = memcmp (HeKEY (b), HeKEY (a), lb < la ? lb : la)))
358 cmp = la - lb; 427 cmp = lb - la;
359 428
360 return cmp; 429 return cmp;
361} 430}
362 431
363// compare hash entries, used when some keys are sv's or utf-x 432// compare hash entries, used when some keys are sv's or utf-x
364static int 433static int
365he_cmp_slow (const void *a, const void *b) 434he_cmp_slow (const void *a, const void *b)
366{ 435{
367 return sv_cmp (HeSVKEY_force (*(HE **)a), HeSVKEY_force (*(HE **)b)); 436 return sv_cmp (HeSVKEY_force (*(HE **)b), HeSVKEY_force (*(HE **)a));
368} 437}
369 438
370static void 439static void
371encode_hv (enc_t *enc, HV *hv) 440encode_hv (enc_t *enc, HV *hv)
372{ 441{
442 HE *he;
373 int count, i; 443 int count;
374 444
375 if (enc->indent >= enc->maxdepth) 445 if (enc->indent >= enc->maxdepth)
376 croak ("data structure too deep (hit recursion limit)"); 446 croak ("data structure too deep (hit recursion limit)");
377 447
378 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent; 448 encode_ch (enc, '{');
379 449
380 if ((count = hv_iterinit (hv)))
381 {
382 // for canonical output we have to sort by keys first 450 // for canonical output we have to sort by keys first
383 // actually, this is mostly due to the stupid so-called 451 // actually, this is mostly due to the stupid so-called
384 // security workaround added somewhere in 5.8.x. 452 // security workaround added somewhere in 5.8.x.
385 // that randomises hash orderings 453 // that randomises hash orderings
386 if (enc->flags & F_CANONICAL) 454 if (enc->json.flags & F_CANONICAL)
455 {
456 int count = hv_iterinit (hv);
457
458 if (SvMAGICAL (hv))
387 { 459 {
460 // need to count by iterating. could improve by dynamically building the vector below
461 // but I don't care for the speed of this special case.
462 // note also that we will run into undefined behaviour when the two iterations
463 // do not result in the same count, something I might care for in some later release.
464
465 count = 0;
466 while (hv_iternext (hv))
467 ++count;
468
469 hv_iterinit (hv);
470 }
471
472 if (count)
473 {
388 int fast = 1; 474 int i, fast = 1;
389 HE *he;
390#if defined(__BORLANDC__) || defined(_MSC_VER) 475#if defined(__BORLANDC__) || defined(_MSC_VER)
391 HE **hes = _alloca (count * sizeof (HE)); 476 HE **hes = _alloca (count * sizeof (HE));
392#else 477#else
393 HE *hes [count]; // if your compiler dies here, you need to enable C99 mode 478 HE *hes [count]; // if your compiler dies here, you need to enable C99 mode
394#endif 479#endif
421 506
422 FREETMPS; 507 FREETMPS;
423 LEAVE; 508 LEAVE;
424 } 509 }
425 510
426 for (i = 0; i < count; ++i) 511 encode_nl (enc); ++enc->indent;
512
513 while (count--)
427 { 514 {
428 encode_indent (enc); 515 encode_indent (enc);
516 he = hes [count];
429 encode_he (enc, hes [i]); 517 encode_hk (enc, he);
518 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
430 519
431 if (i < count - 1) 520 if (count)
432 encode_comma (enc); 521 encode_comma (enc);
433 } 522 }
434 523
524 encode_nl (enc); --enc->indent; encode_indent (enc);
525 }
526 }
527 else
528 {
529 if (hv_iterinit (hv) || SvMAGICAL (hv))
530 if ((he = hv_iternext (hv)))
531 {
532 encode_nl (enc); ++enc->indent;
533
534 for (;;)
535 {
435 encode_nl (enc); 536 encode_indent (enc);
537 encode_hk (enc, he);
538 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
539
540 if (!(he = hv_iternext (hv)))
541 break;
542
543 encode_comma (enc);
544 }
545
546 encode_nl (enc); --enc->indent; encode_indent (enc);
547 }
548 }
549
550 encode_ch (enc, '}');
551}
552
553// encode objects, arrays and special \0=false and \1=true values.
554static void
555encode_rv (enc_t *enc, SV *sv)
556{
557 svtype svt;
558
559 SvGETMAGIC (sv);
560 svt = SvTYPE (sv);
561
562 if (expect_false (SvOBJECT (sv)))
563 {
564 HV *stash = !JSON_SLOW || json_boolean_stash
565 ? json_boolean_stash
566 : gv_stashpv ("JSON::XS::Boolean", 1);
567
568 if (SvSTASH (sv) == stash)
569 {
570 if (SvIV (sv))
571 encode_str (enc, "true", 4, 0);
572 else
573 encode_str (enc, "false", 5, 0);
436 } 574 }
437 else 575 else
438 { 576 {
439 HE *he = hv_iternext (hv); 577#if 0
440 578 if (0 && sv_derived_from (rv, "JSON::Literal"))
441 for (;;)
442 { 579 {
443 encode_indent (enc); 580 // not yet
444 encode_he (enc, he);
445
446 if (!(he = hv_iternext (hv)))
447 break;
448
449 encode_comma (enc);
450 } 581 }
582#endif
583 if (enc->json.flags & F_CONV_BLESSED)
584 {
585 // we re-bless the reference to get overload and other niceties right
586 GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 0);
451 587
588 if (to_json)
589 {
590 dSP;
591
592 ENTER; SAVETMPS; PUSHMARK (SP);
593 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv)));
594
595 // calling with G_SCALAR ensures that we always get a 1 return value
596 PUTBACK;
597 call_sv ((SV *)GvCV (to_json), G_SCALAR);
598 SPAGAIN;
599
600 // catch this surprisingly common error
601 if (SvROK (TOPs) && SvRV (TOPs) == sv)
602 croak ("%s::TO_JSON method returned same object as was passed instead of a new one", HvNAME (SvSTASH (sv)));
603
604 sv = POPs;
605 PUTBACK;
606
452 encode_nl (enc); 607 encode_sv (enc, sv);
608
609 FREETMPS; LEAVE;
610 }
611 else if (enc->json.flags & F_ALLOW_BLESSED)
612 encode_str (enc, "null", 4, 0);
613 else
614 croak ("encountered object '%s', but neither allow_blessed enabled nor TO_JSON method available on it",
615 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
616 }
617 else if (enc->json.flags & F_ALLOW_BLESSED)
618 encode_str (enc, "null", 4, 0);
619 else
620 croak ("encountered object '%s', but neither allow_blessed nor convert_blessed settings are enabled",
621 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
453 } 622 }
454 } 623 }
455
456 --enc->indent; encode_indent (enc); encode_ch (enc, '}');
457}
458
459// encode objects, arrays and special \0=false and \1=true values.
460static void
461encode_rv (enc_t *enc, SV *sv)
462{
463 svtype svt;
464
465 SvGETMAGIC (sv);
466 svt = SvTYPE (sv);
467
468 if (svt == SVt_PVHV) 624 else if (svt == SVt_PVHV)
469 encode_hv (enc, (HV *)sv); 625 encode_hv (enc, (HV *)sv);
470 else if (svt == SVt_PVAV) 626 else if (svt == SVt_PVAV)
471 encode_av (enc, (AV *)sv); 627 encode_av (enc, (AV *)sv);
472 else if (svt < SVt_PVAV) 628 else if (svt < SVt_PVAV)
473 { 629 {
474 if (SvNIOK (sv) && SvIV (sv) == 0) 630 STRLEN len = 0;
631 char *pv = svt ? SvPV (sv, len) : 0;
632
633 if (len == 1 && *pv == '1')
634 encode_str (enc, "true", 4, 0);
635 else if (len == 1 && *pv == '0')
475 encode_str (enc, "false", 5, 0); 636 encode_str (enc, "false", 5, 0);
476 else if (SvNIOK (sv) && SvIV (sv) == 1)
477 encode_str (enc, "true", 4, 0);
478 else 637 else
479 croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1", 638 croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1",
480 SvPV_nolen (sv_2mortal (newRV_inc (sv)))); 639 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
481 } 640 }
482 else 641 else
504 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur); 663 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
505 enc->cur += strlen (enc->cur); 664 enc->cur += strlen (enc->cur);
506 } 665 }
507 else if (SvIOKp (sv)) 666 else if (SvIOKp (sv))
508 { 667 {
509 // we assume we can always read an IV as a UV 668 // we assume we can always read an IV as a UV and vice versa
510 if (SvUV (sv) & ~(UV)0x7fff) 669 // we assume two's complement
511 { 670 // we assume no aliasing issues in the union
512 // large integer, use the (rather slow) snprintf way. 671 if (SvIsUV (sv) ? SvUVX (sv) <= 59000
513 need (enc, sizeof (UV) * 3); 672 : SvIVX (sv) <= 59000 && SvIVX (sv) >= -59000)
514 enc->cur +=
515 SvIsUV(sv)
516 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv))
517 : snprintf (enc->cur, sizeof (UV) * 3, "%"IVdf, (IV)SvIVX (sv));
518 }
519 else
520 { 673 {
521 // optimise the "small number case" 674 // optimise the "small number case"
522 // code will likely be branchless and use only a single multiplication 675 // code will likely be branchless and use only a single multiplication
676 // works for numbers up to 59074
523 I32 i = SvIV (sv); 677 I32 i = SvIVX (sv);
524 U32 u; 678 U32 u;
525 char digit, nz = 0; 679 char digit, nz = 0;
526 680
527 need (enc, 6); 681 need (enc, 6);
528 682
534 688
535 // now output digit by digit, each time masking out the integer part 689 // now output digit by digit, each time masking out the integer part
536 // and multiplying by 5 while moving the decimal point one to the right, 690 // and multiplying by 5 while moving the decimal point one to the right,
537 // resulting in a net multiplication by 10. 691 // resulting in a net multiplication by 10.
538 // we always write the digit to memory but conditionally increment 692 // we always write the digit to memory but conditionally increment
539 // the pointer, to ease the usage of conditional move instructions. 693 // the pointer, to enable the use of conditional move instructions.
540 digit = u >> 28; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0xfffffff) * 5; 694 digit = u >> 28; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0xfffffffUL) * 5;
541 digit = u >> 27; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x7ffffff) * 5; 695 digit = u >> 27; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x7ffffffUL) * 5;
542 digit = u >> 26; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x3ffffff) * 5; 696 digit = u >> 26; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x3ffffffUL) * 5;
543 digit = u >> 25; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x1ffffff) * 5; 697 digit = u >> 25; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x1ffffffUL) * 5;
544 digit = u >> 24; *enc->cur = digit + '0'; enc->cur += 1; // correctly generate '0' 698 digit = u >> 24; *enc->cur = digit + '0'; enc->cur += 1; // correctly generate '0'
699 }
700 else
701 {
702 // large integer, use the (rather slow) snprintf way.
703 need (enc, IVUV_MAXCHARS);
704 enc->cur +=
705 SvIsUV(sv)
706 ? snprintf (enc->cur, IVUV_MAXCHARS, "%"UVuf, (UV)SvUVX (sv))
707 : snprintf (enc->cur, IVUV_MAXCHARS, "%"IVdf, (IV)SvIVX (sv));
545 } 708 }
546 } 709 }
547 else if (SvROK (sv)) 710 else if (SvROK (sv))
548 encode_rv (enc, SvRV (sv)); 711 encode_rv (enc, SvRV (sv));
549 else if (!SvOK (sv)) 712 else if (!SvOK (sv))
552 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this", 715 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this",
553 SvPV_nolen (sv), SvFLAGS (sv)); 716 SvPV_nolen (sv), SvFLAGS (sv));
554} 717}
555 718
556static SV * 719static SV *
557encode_json (SV *scalar, U32 flags) 720encode_json (SV *scalar, JSON *json)
558{ 721{
559 enc_t enc; 722 enc_t enc;
560 723
561 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar)) 724 if (!(json->flags & F_ALLOW_NONREF) && !SvROK (scalar))
562 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)"); 725 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)");
563 726
564 enc.flags = flags; 727 enc.json = *json;
565 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 728 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
566 enc.cur = SvPVX (enc.sv); 729 enc.cur = SvPVX (enc.sv);
567 enc.end = SvEND (enc.sv); 730 enc.end = SvEND (enc.sv);
568 enc.indent = 0; 731 enc.indent = 0;
569 enc.maxdepth = DEC_DEPTH (flags); 732 enc.maxdepth = DEC_DEPTH (enc.json.flags);
733 enc.limit = enc.json.flags & F_ASCII ? 0x000080UL
734 : enc.json.flags & F_LATIN1 ? 0x000100UL
735 : 0x110000UL;
570 736
571 SvPOK_only (enc.sv); 737 SvPOK_only (enc.sv);
572 encode_sv (&enc, scalar); 738 encode_sv (&enc, scalar);
573 739
574 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); 740 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
575 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings 741 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings
576 742
577 if (!(flags & (F_ASCII | F_LATIN1 | F_UTF8))) 743 if (!(enc.json.flags & (F_ASCII | F_LATIN1 | F_UTF8)))
578 SvUTF8_on (enc.sv); 744 SvUTF8_on (enc.sv);
579 745
580 if (enc.flags & F_SHRINK) 746 if (enc.json.flags & F_SHRINK)
581 shrink (enc.sv); 747 shrink (enc.sv);
582 748
583 return enc.sv; 749 return enc.sv;
584} 750}
585 751
590typedef struct 756typedef struct
591{ 757{
592 char *cur; // current parser pointer 758 char *cur; // current parser pointer
593 char *end; // end of input string 759 char *end; // end of input string
594 const char *err; // parse error, if != 0 760 const char *err; // parse error, if != 0
595 U32 flags; // F_* 761 JSON json;
596 U32 depth; // recursion depth 762 U32 depth; // recursion depth
597 U32 maxdepth; // recursion depth limit 763 U32 maxdepth; // recursion depth limit
598} dec_t; 764} dec_t;
599 765
600inline void 766INLINE void
767decode_comment (dec_t *dec)
768{
769 // only '#'-style comments allowed a.t.m.
770
771 while (*dec->cur && *dec->cur != 0x0a && *dec->cur != 0x0d)
772 ++dec->cur;
773}
774
775INLINE void
601decode_ws (dec_t *dec) 776decode_ws (dec_t *dec)
602{ 777{
603 for (;;) 778 for (;;)
604 { 779 {
605 char ch = *dec->cur; 780 char ch = *dec->cur;
606 781
607 if (ch > 0x20 782 if (ch > 0x20)
783 {
784 if (expect_false (ch == '#'))
785 {
786 if (dec->json.flags & F_RELAXED)
787 decode_comment (dec);
788 else
789 break;
790 }
791 else
792 break;
793 }
608 || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)) 794 else if (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)
609 break; 795 break; // parse error, but let higher level handle it, gives better error messages
610 796
611 ++dec->cur; 797 ++dec->cur;
612 } 798 }
613} 799}
614 800
631decode_4hex (dec_t *dec) 817decode_4hex (dec_t *dec)
632{ 818{
633 signed char d1, d2, d3, d4; 819 signed char d1, d2, d3, d4;
634 unsigned char *cur = (unsigned char *)dec->cur; 820 unsigned char *cur = (unsigned char *)dec->cur;
635 821
636 d1 = decode_hexdigit [cur [0]]; if (expect_false (d1 < 0)) ERR ("four hexadecimal digits expected"); 822 d1 = decode_hexdigit [cur [0]]; if (expect_false (d1 < 0)) ERR ("exactly four hexadecimal digits expected");
637 d2 = decode_hexdigit [cur [1]]; if (expect_false (d2 < 0)) ERR ("four hexadecimal digits expected"); 823 d2 = decode_hexdigit [cur [1]]; if (expect_false (d2 < 0)) ERR ("exactly four hexadecimal digits expected");
638 d3 = decode_hexdigit [cur [2]]; if (expect_false (d3 < 0)) ERR ("four hexadecimal digits expected"); 824 d3 = decode_hexdigit [cur [2]]; if (expect_false (d3 < 0)) ERR ("exactly four hexadecimal digits expected");
639 d4 = decode_hexdigit [cur [3]]; if (expect_false (d4 < 0)) ERR ("four hexadecimal digits expected"); 825 d4 = decode_hexdigit [cur [3]]; if (expect_false (d4 < 0)) ERR ("exactly four hexadecimal digits expected");
640 826
641 dec->cur += 4; 827 dec->cur += 4;
642 828
643 return ((UV)d1) << 12 829 return ((UV)d1) << 12
644 | ((UV)d2) << 8 830 | ((UV)d2) << 8
720 906
721 if (hi >= 0x80) 907 if (hi >= 0x80)
722 { 908 {
723 utf8 = 1; 909 utf8 = 1;
724 910
725 cur = (char *)uvuni_to_utf8_flags (cur, hi, 0); 911 cur = encode_utf8 (cur, hi);
726 } 912 }
727 else 913 else
728 *cur++ = hi; 914 *cur++ = hi;
729 } 915 }
730 break; 916 break;
732 default: 918 default:
733 --dec_cur; 919 --dec_cur;
734 ERR ("illegal backslash escape sequence in string"); 920 ERR ("illegal backslash escape sequence in string");
735 } 921 }
736 } 922 }
737 else if (expect_true (ch >= 0x20 && ch <= 0x7f)) 923 else if (expect_true (ch >= 0x20 && ch < 0x80))
738 *cur++ = ch; 924 *cur++ = ch;
739 else if (ch >= 0x80) 925 else if (ch >= 0x80)
740 { 926 {
741 STRLEN clen; 927 STRLEN clen;
742 UV uch; 928 UV uch;
863 is_nv = 1; 1049 is_nv = 1;
864 } 1050 }
865 1051
866 if (!is_nv) 1052 if (!is_nv)
867 { 1053 {
1054 int len = dec->cur - start;
1055
868 // special case the rather common 1..4-digit-int case, assumes 32 bit ints or so 1056 // special case the rather common 1..5-digit-int case
869 if (*start == '-') 1057 if (*start == '-')
870 switch (dec->cur - start) 1058 switch (len)
871 { 1059 {
872 case 2: return newSViv (-( start [1] - '0' )); 1060 case 2: return newSViv (-( start [1] - '0' * 1));
873 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11)); 1061 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11));
874 case 4: return newSViv (-( start [1] * 100 + start [2] * 10 + start [3] - '0' * 111)); 1062 case 4: return newSViv (-( start [1] * 100 + start [2] * 10 + start [3] - '0' * 111));
875 case 5: return newSViv (-(start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111)); 1063 case 5: return newSViv (-( start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111));
1064 case 6: return newSViv (-(start [1] * 10000 + start [2] * 1000 + start [3] * 100 + start [4] * 10 + start [5] - '0' * 11111));
876 } 1065 }
877 else 1066 else
878 switch (dec->cur - start) 1067 switch (len)
879 { 1068 {
880 case 1: return newSViv ( start [0] - '0' ); 1069 case 1: return newSViv ( start [0] - '0' * 1);
881 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11); 1070 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11);
882 case 3: return newSViv ( start [0] * 100 + start [1] * 10 + start [2] - '0' * 111); 1071 case 3: return newSViv ( start [0] * 100 + start [1] * 10 + start [2] - '0' * 111);
883 case 4: return newSViv ( start [0] * 1000 + start [1] * 100 + start [2] * 10 + start [3] - '0' * 1111); 1072 case 4: return newSViv ( start [0] * 1000 + start [1] * 100 + start [2] * 10 + start [3] - '0' * 1111);
1073 case 5: return newSViv ( start [0] * 10000 + start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 11111);
884 } 1074 }
885 1075
886 { 1076 {
887 UV uv; 1077 UV uv;
888 int numtype = grok_number (start, dec->cur - start, &uv); 1078 int numtype = grok_number (start, len, &uv);
889 if (numtype & IS_NUMBER_IN_UV) 1079 if (numtype & IS_NUMBER_IN_UV)
890 if (numtype & IS_NUMBER_NEG) 1080 if (numtype & IS_NUMBER_NEG)
891 { 1081 {
892 if (uv < (UV)IV_MIN) 1082 if (uv < (UV)IV_MIN)
893 return newSViv (-(IV)uv); 1083 return newSViv (-(IV)uv);
894 } 1084 }
895 else 1085 else
896 return newSVuv (uv); 1086 return newSVuv (uv);
897 } 1087 }
898 }
899 1088
1089 len -= *start == '-' ? 1 : 0;
1090
1091 // does not fit into IV or UV, try NV
1092 if ((sizeof (NV) == sizeof (double) && DBL_DIG >= len)
1093 #if defined (LDBL_DIG)
1094 || (sizeof (NV) == sizeof (long double) && LDBL_DIG >= len)
1095 #endif
1096 )
1097 // fits into NV without loss of precision
1098 return newSVnv (Atof (start));
1099
1100 // everything else fails, convert it to a string
1101 return newSVpvn (start, dec->cur - start);
1102 }
1103
1104 // loss of precision here
900 return newSVnv (Atof (start)); 1105 return newSVnv (Atof (start));
901 1106
902fail: 1107fail:
903 return 0; 1108 return 0;
904} 1109}
934 1139
935 if (*dec->cur != ',') 1140 if (*dec->cur != ',')
936 ERR (", or ] expected while parsing array"); 1141 ERR (", or ] expected while parsing array");
937 1142
938 ++dec->cur; 1143 ++dec->cur;
1144
1145 decode_ws (dec);
1146
1147 if (*dec->cur == ']' && dec->json.flags & F_RELAXED)
1148 {
1149 ++dec->cur;
1150 break;
1151 }
939 } 1152 }
940 1153
941 DEC_DEC_DEPTH; 1154 DEC_DEC_DEPTH;
942 return newRV_noinc ((SV *)av); 1155 return newRV_noinc ((SV *)av);
943 1156
948} 1161}
949 1162
950static SV * 1163static SV *
951decode_hv (dec_t *dec) 1164decode_hv (dec_t *dec)
952{ 1165{
1166 SV *sv;
953 HV *hv = newHV (); 1167 HV *hv = newHV ();
954 1168
955 DEC_INC_DEPTH; 1169 DEC_INC_DEPTH;
956 decode_ws (dec); 1170 decode_ws (dec);
957 1171
958 if (*dec->cur == '}') 1172 if (*dec->cur == '}')
959 ++dec->cur; 1173 ++dec->cur;
960 else 1174 else
961 for (;;) 1175 for (;;)
962 { 1176 {
1177 EXPECT_CH ('"');
1178
1179 // heuristic: assume that
1180 // a) decode_str + hv_store_ent are abysmally slow.
1181 // b) most hash keys are short, simple ascii text.
1182 // => try to "fast-match" such strings to avoid
1183 // the overhead of decode_str + hv_store_ent.
1184 {
963 SV *key, *value; 1185 SV *value;
1186 char *p = dec->cur;
1187 char *e = p + 24; // only try up to 24 bytes
964 1188
965 decode_ws (dec); EXPECT_CH ('"'); 1189 for (;;)
966
967 key = decode_str (dec);
968 if (!key)
969 goto fail;
970
971 decode_ws (dec); EXPECT_CH (':');
972
973 value = decode_sv (dec);
974 if (!value)
975 { 1190 {
1191 // the >= 0x80 is false on most architectures
1192 if (p == e || *p < 0x20 || *p >= 0x80 || *p == '\\')
1193 {
1194 // slow path, back up and use decode_str
1195 SV *key = decode_str (dec);
1196 if (!key)
1197 goto fail;
1198
1199 decode_ws (dec); EXPECT_CH (':');
1200
1201 decode_ws (dec);
1202 value = decode_sv (dec);
1203 if (!value)
1204 {
1205 SvREFCNT_dec (key);
1206 goto fail;
1207 }
1208
1209 hv_store_ent (hv, key, value, 0);
976 SvREFCNT_dec (key); 1210 SvREFCNT_dec (key);
1211
1212 break;
1213 }
1214 else if (*p == '"')
1215 {
1216 // fast path, got a simple key
1217 char *key = dec->cur;
1218 int len = p - key;
1219 dec->cur = p + 1;
1220
1221 decode_ws (dec); EXPECT_CH (':');
1222
1223 decode_ws (dec);
1224 value = decode_sv (dec);
1225 if (!value)
977 goto fail; 1226 goto fail;
1227
1228 hv_store (hv, key, len, value, 0);
1229
1230 break;
1231 }
1232
1233 ++p;
978 } 1234 }
979 1235 }
980 hv_store_ent (hv, key, value, 0);
981 SvREFCNT_dec (key);
982 1236
983 decode_ws (dec); 1237 decode_ws (dec);
984 1238
985 if (*dec->cur == '}') 1239 if (*dec->cur == '}')
986 { 1240 {
990 1244
991 if (*dec->cur != ',') 1245 if (*dec->cur != ',')
992 ERR (", or } expected while parsing object/hash"); 1246 ERR (", or } expected while parsing object/hash");
993 1247
994 ++dec->cur; 1248 ++dec->cur;
1249
1250 decode_ws (dec);
1251
1252 if (*dec->cur == '}' && dec->json.flags & F_RELAXED)
1253 {
1254 ++dec->cur;
1255 break;
1256 }
995 } 1257 }
996 1258
997 DEC_DEC_DEPTH; 1259 DEC_DEC_DEPTH;
998 return newRV_noinc ((SV *)hv); 1260 sv = newRV_noinc ((SV *)hv);
1261
1262 // check filter callbacks
1263 if (dec->json.flags & F_HOOK)
1264 {
1265 if (dec->json.cb_sk_object && HvKEYS (hv) == 1)
1266 {
1267 HE *cb, *he;
1268
1269 hv_iterinit (hv);
1270 he = hv_iternext (hv);
1271 hv_iterinit (hv);
1272
1273 // the next line creates a mortal sv each time its called.
1274 // might want to optimise this for common cases.
1275 cb = hv_fetch_ent (dec->json.cb_sk_object, hv_iterkeysv (he), 0, 0);
1276
1277 if (cb)
1278 {
1279 dSP;
1280 int count;
1281
1282 ENTER; SAVETMPS; PUSHMARK (SP);
1283 XPUSHs (HeVAL (he));
1284
1285 PUTBACK; count = call_sv (HeVAL (cb), G_ARRAY); SPAGAIN;
1286
1287 if (count == 1)
1288 {
1289 sv = newSVsv (POPs);
1290 FREETMPS; LEAVE;
1291 return sv;
1292 }
1293
1294 FREETMPS; LEAVE;
1295 }
1296 }
1297
1298 if (dec->json.cb_object)
1299 {
1300 dSP;
1301 int count;
1302
1303 ENTER; SAVETMPS; PUSHMARK (SP);
1304 XPUSHs (sv_2mortal (sv));
1305
1306 PUTBACK; count = call_sv (dec->json.cb_object, G_ARRAY); SPAGAIN;
1307
1308 if (count == 1)
1309 {
1310 sv = newSVsv (POPs);
1311 FREETMPS; LEAVE;
1312 return sv;
1313 }
1314
1315 SvREFCNT_inc (sv);
1316 FREETMPS; LEAVE;
1317 }
1318 }
1319
1320 return sv;
999 1321
1000fail: 1322fail:
1001 SvREFCNT_dec (hv); 1323 SvREFCNT_dec (hv);
1002 DEC_DEC_DEPTH; 1324 DEC_DEC_DEPTH;
1003 return 0; 1325 return 0;
1004} 1326}
1005 1327
1006static SV * 1328static SV *
1007decode_sv (dec_t *dec) 1329decode_sv (dec_t *dec)
1008{ 1330{
1009 decode_ws (dec); 1331 // the beauty of JSON: you need exactly one character lookahead
1332 // to parse everything.
1010 switch (*dec->cur) 1333 switch (*dec->cur)
1011 { 1334 {
1012 case '"': ++dec->cur; return decode_str (dec); 1335 case '"': ++dec->cur; return decode_str (dec);
1013 case '[': ++dec->cur; return decode_av (dec); 1336 case '[': ++dec->cur; return decode_av (dec);
1014 case '{': ++dec->cur; return decode_hv (dec); 1337 case '{': ++dec->cur; return decode_hv (dec);
1015 1338
1016 case '-': 1339 case '-':
1017 case '0': case '1': case '2': case '3': case '4': 1340 case '0': case '1': case '2': case '3': case '4':
1018 case '5': case '6': case '7': case '8': case '9': 1341 case '5': case '6': case '7': case '8': case '9':
1019 return decode_num (dec); 1342 return decode_num (dec);
1020 1343
1021 case 't': 1344 case 't':
1022 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1345 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
1023 { 1346 {
1024 dec->cur += 4; 1347 dec->cur += 4;
1025 return newSViv (1); 1348#if JSON_SLOW
1349 json_true = get_sv ("JSON::XS::true", 1); SvREADONLY_on (json_true);
1350#endif
1351 return SvREFCNT_inc (json_true);
1026 } 1352 }
1027 else 1353 else
1028 ERR ("'true' expected"); 1354 ERR ("'true' expected");
1029 1355
1030 break; 1356 break;
1031 1357
1032 case 'f': 1358 case 'f':
1033 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1359 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
1034 { 1360 {
1035 dec->cur += 5; 1361 dec->cur += 5;
1036 return newSViv (0); 1362#if JSON_SLOW
1363 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1364#endif
1365 return SvREFCNT_inc (json_false);
1037 } 1366 }
1038 else 1367 else
1039 ERR ("'false' expected"); 1368 ERR ("'false' expected");
1040 1369
1041 break; 1370 break;
1059fail: 1388fail:
1060 return 0; 1389 return 0;
1061} 1390}
1062 1391
1063static SV * 1392static SV *
1064decode_json (SV *string, U32 flags, UV *offset_return) 1393decode_json (SV *string, JSON *json, STRLEN *offset_return)
1065{ 1394{
1066 dec_t dec; 1395 dec_t dec;
1067 UV offset; 1396 STRLEN offset;
1068 SV *sv; 1397 SV *sv;
1069 1398
1070 SvGETMAGIC (string); 1399 SvGETMAGIC (string);
1071 SvUPGRADE (string, SVt_PV); 1400 SvUPGRADE (string, SVt_PV);
1072 1401
1402 if (json->flags & F_MAXSIZE && SvCUR (string) > DEC_SIZE (json->flags))
1403 croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu",
1404 (unsigned long)SvCUR (string), (unsigned long)DEC_SIZE (json->flags));
1405
1073 if (flags & F_UTF8) 1406 if (json->flags & F_UTF8)
1074 sv_utf8_downgrade (string, 0); 1407 sv_utf8_downgrade (string, 0);
1075 else 1408 else
1076 sv_utf8_upgrade (string); 1409 sv_utf8_upgrade (string);
1077 1410
1078 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP 1411 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
1079 1412
1080 dec.flags = flags; 1413 dec.json = *json;
1081 dec.cur = SvPVX (string); 1414 dec.cur = SvPVX (string);
1082 dec.end = SvEND (string); 1415 dec.end = SvEND (string);
1083 dec.err = 0; 1416 dec.err = 0;
1084 dec.depth = 0; 1417 dec.depth = 0;
1085 dec.maxdepth = DEC_DEPTH (dec.flags); 1418 dec.maxdepth = DEC_DEPTH (dec.json.flags);
1419
1420 if (dec.json.cb_object || dec.json.cb_sk_object)
1421 dec.json.flags |= F_HOOK;
1086 1422
1087 *dec.end = 0; // this should basically be a nop, too, but make sure it's there 1423 *dec.end = 0; // this should basically be a nop, too, but make sure it's there
1424
1425 decode_ws (&dec);
1088 sv = decode_sv (&dec); 1426 sv = decode_sv (&dec);
1089 1427
1090 if (!(offset_return || !sv)) 1428 if (!(offset_return || !sv))
1091 { 1429 {
1092 // check for trailing garbage 1430 // check for trailing garbage
1100 } 1438 }
1101 } 1439 }
1102 1440
1103 if (offset_return || !sv) 1441 if (offset_return || !sv)
1104 { 1442 {
1105 offset = dec.flags & F_UTF8 1443 offset = dec.json.flags & F_UTF8
1106 ? dec.cur - SvPVX (string) 1444 ? dec.cur - SvPVX (string)
1107 : utf8_distance (dec.cur, SvPVX (string)); 1445 : utf8_distance (dec.cur, SvPVX (string));
1108 1446
1109 if (offset_return) 1447 if (offset_return)
1110 *offset_return = offset; 1448 *offset_return = offset;
1129 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); 1467 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
1130 } 1468 }
1131 1469
1132 sv = sv_2mortal (sv); 1470 sv = sv_2mortal (sv);
1133 1471
1134 if (!(dec.flags & F_ALLOW_NONREF) && !SvROK (sv)) 1472 if (!(dec.json.flags & F_ALLOW_NONREF) && !SvROK (sv))
1135 croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)"); 1473 croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)");
1136 1474
1137 return sv; 1475 return sv;
1476}
1477
1478/////////////////////////////////////////////////////////////////////////////
1479// incremental parser
1480
1481static void
1482incr_parse (JSON *self)
1483{
1484 const char *p = SvPVX (self->incr_text) + self->incr_pos;
1485
1486 for (;;)
1487 {
1488 //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
1489 switch (self->incr_mode)
1490 {
1491 // only used for intiial whitespace skipping
1492 case INCR_M_WS:
1493 for (;;)
1494 {
1495 if (*p > 0x20)
1496 {
1497 self->incr_mode = INCR_M_JSON;
1498 goto incr_m_json;
1499 }
1500 else if (!*p)
1501 goto interrupt;
1502
1503 ++p;
1504 }
1505
1506 // skip a single char inside a string (for \\-processing)
1507 case INCR_M_BS:
1508 if (!*p)
1509 goto interrupt;
1510
1511 ++p;
1512 self->incr_mode = INCR_M_STR;
1513 goto incr_m_str;
1514
1515 // inside a string
1516 case INCR_M_STR:
1517 incr_m_str:
1518 for (;;)
1519 {
1520 if (*p == '"')
1521 {
1522 ++p;
1523 self->incr_mode = INCR_M_JSON;
1524
1525 if (!self->incr_nest)
1526 goto interrupt;
1527
1528 goto incr_m_json;
1529 }
1530 else if (*p == '\\')
1531 {
1532 ++p; // "virtually" consumes character after \
1533
1534 if (!*p) // if at end of string we have to switch modes
1535 {
1536 self->incr_mode = INCR_M_BS;
1537 goto interrupt;
1538 }
1539 }
1540 else if (!*p)
1541 goto interrupt;
1542
1543 ++p;
1544 }
1545
1546 // after initial ws, outside string
1547 case INCR_M_JSON:
1548 incr_m_json:
1549 for (;;)
1550 {
1551 switch (*p++)
1552 {
1553 case 0:
1554 --p;
1555 goto interrupt;
1556
1557 case 0x09:
1558 case 0x0a:
1559 case 0x0d:
1560 case 0x20:
1561 if (!self->incr_nest)
1562 {
1563 --p; // do not eat the whitespace, let the next round do it
1564 goto interrupt;
1565 }
1566 break;
1567
1568 case '"':
1569 self->incr_mode = INCR_M_STR;
1570 goto incr_m_str;
1571
1572 case '[':
1573 case '{':
1574 ++self->incr_nest;
1575 break;
1576
1577 case ']':
1578 case '}':
1579 if (!--self->incr_nest)
1580 goto interrupt;
1581 }
1582 }
1583 }
1584
1585 modechange:
1586 ;
1587 }
1588
1589interrupt:
1590 self->incr_pos = p - SvPVX (self->incr_text);
1591 //printf ("return pos %d mode %d nest %d\n", self->incr_pos, self->incr_mode, self->incr_nest);//D
1138} 1592}
1139 1593
1140///////////////////////////////////////////////////////////////////////////// 1594/////////////////////////////////////////////////////////////////////////////
1141// XS interface functions 1595// XS interface functions
1142 1596
1143MODULE = JSON::XS PACKAGE = JSON::XS 1597MODULE = JSON::XS PACKAGE = JSON::XS
1144 1598
1145BOOT: 1599BOOT:
1146{ 1600{
1147 int i; 1601 int i;
1148
1149 memset (decode_hexdigit, 0xff, 256);
1150 1602
1151 for (i = 0; i < 256; ++i) 1603 for (i = 0; i < 256; ++i)
1152 decode_hexdigit [i] = 1604 decode_hexdigit [i] =
1153 i >= '0' && i <= '9' ? i - '0' 1605 i >= '0' && i <= '9' ? i - '0'
1154 : i >= 'a' && i <= 'f' ? i - 'a' + 10 1606 : i >= 'a' && i <= 'f' ? i - 'a' + 10
1155 : i >= 'A' && i <= 'F' ? i - 'A' + 10 1607 : i >= 'A' && i <= 'F' ? i - 'A' + 10
1156 : -1; 1608 : -1;
1157 1609
1158 json_stash = gv_stashpv ("JSON::XS", 1); 1610 json_stash = gv_stashpv ("JSON::XS" , 1);
1611 json_boolean_stash = gv_stashpv ("JSON::XS::Boolean", 1);
1612
1613 json_true = get_sv ("JSON::XS::true" , 1); SvREADONLY_on (json_true );
1614 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1159} 1615}
1160 1616
1161PROTOTYPES: DISABLE 1617PROTOTYPES: DISABLE
1162 1618
1163SV *new (char *dummy) 1619void CLONE (...)
1164 CODE: 1620 CODE:
1165 RETVAL = sv_bless (newRV_noinc (newSVuv (F_DEFAULT)), json_stash); 1621 json_stash = 0;
1622 json_boolean_stash = 0;
1623
1624void new (char *klass)
1625 PPCODE:
1626{
1627 SV *pv = NEWSV (0, sizeof (JSON));
1628 SvPOK_only (pv);
1629 Zero (SvPVX (pv), 1, JSON);
1630 ((JSON *)SvPVX (pv))->flags = F_DEFAULT;
1631 XPUSHs (sv_2mortal (sv_bless (
1632 newRV_noinc (pv),
1633 strEQ (klass, "JSON::XS") ? JSON_STASH : gv_stashpv (klass, 1)
1634 )));
1635}
1636
1637void ascii (JSON *self, int enable = 1)
1638 ALIAS:
1639 ascii = F_ASCII
1640 latin1 = F_LATIN1
1641 utf8 = F_UTF8
1642 indent = F_INDENT
1643 canonical = F_CANONICAL
1644 space_before = F_SPACE_BEFORE
1645 space_after = F_SPACE_AFTER
1646 pretty = F_PRETTY
1647 allow_nonref = F_ALLOW_NONREF
1648 shrink = F_SHRINK
1649 allow_blessed = F_ALLOW_BLESSED
1650 convert_blessed = F_CONV_BLESSED
1651 relaxed = F_RELAXED
1652 PPCODE:
1653{
1654 if (enable)
1655 self->flags |= ix;
1656 else
1657 self->flags &= ~ix;
1658
1659 XPUSHs (ST (0));
1660}
1661
1662void get_ascii (JSON *self)
1663 ALIAS:
1664 get_ascii = F_ASCII
1665 get_latin1 = F_LATIN1
1666 get_utf8 = F_UTF8
1667 get_indent = F_INDENT
1668 get_canonical = F_CANONICAL
1669 get_space_before = F_SPACE_BEFORE
1670 get_space_after = F_SPACE_AFTER
1671 get_allow_nonref = F_ALLOW_NONREF
1672 get_shrink = F_SHRINK
1673 get_allow_blessed = F_ALLOW_BLESSED
1674 get_convert_blessed = F_CONV_BLESSED
1675 get_relaxed = F_RELAXED
1676 PPCODE:
1677 XPUSHs (boolSV (self->flags & ix));
1678
1679void max_depth (JSON *self, UV max_depth = 0x80000000UL)
1680 PPCODE:
1681{
1682 UV log2 = 0;
1683
1684 if (max_depth > 0x80000000UL) max_depth = 0x80000000UL;
1685
1686 while ((1UL << log2) < max_depth)
1687 ++log2;
1688
1689 self->flags = self->flags & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1690
1691 XPUSHs (ST (0));
1692}
1693
1694U32 get_max_depth (JSON *self)
1695 CODE:
1696 RETVAL = DEC_DEPTH (self->flags);
1166 OUTPUT: 1697 OUTPUT:
1167 RETVAL 1698 RETVAL
1168 1699
1169SV *ascii (SV *self, int enable = 1) 1700void max_size (JSON *self, UV max_size = 0)
1170 ALIAS: 1701 PPCODE:
1171 ascii = F_ASCII 1702{
1172 latin1 = F_LATIN1 1703 UV log2 = 0;
1173 utf8 = F_UTF8 1704
1174 indent = F_INDENT 1705 if (max_size > 0x80000000UL) max_size = 0x80000000UL;
1175 canonical = F_CANONICAL 1706 if (max_size == 1) max_size = 2;
1176 space_before = F_SPACE_BEFORE 1707
1177 space_after = F_SPACE_AFTER 1708 while ((1UL << log2) < max_size)
1178 pretty = F_PRETTY 1709 ++log2;
1179 allow_nonref = F_ALLOW_NONREF 1710
1180 shrink = F_SHRINK 1711 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE);
1712
1713 XPUSHs (ST (0));
1714}
1715
1716int get_max_size (JSON *self)
1181 CODE: 1717 CODE:
1182{ 1718 RETVAL = DEC_SIZE (self->flags);
1183 UV *uv = SvJSON (self);
1184 if (enable)
1185 *uv |= ix;
1186 else
1187 *uv &= ~ix;
1188
1189 RETVAL = newSVsv (self);
1190}
1191 OUTPUT: 1719 OUTPUT:
1192 RETVAL 1720 RETVAL
1193 1721
1194SV *max_depth (SV *self, UV max_depth = 0x80000000UL) 1722void filter_json_object (JSON *self, SV *cb = &PL_sv_undef)
1723 PPCODE:
1724{
1725 SvREFCNT_dec (self->cb_object);
1726 self->cb_object = SvOK (cb) ? newSVsv (cb) : 0;
1727
1728 XPUSHs (ST (0));
1729}
1730
1731void filter_json_single_key_object (JSON *self, SV *key, SV *cb = &PL_sv_undef)
1732 PPCODE:
1733{
1734 if (!self->cb_sk_object)
1735 self->cb_sk_object = newHV ();
1736
1737 if (SvOK (cb))
1738 hv_store_ent (self->cb_sk_object, key, newSVsv (cb), 0);
1739 else
1740 {
1741 hv_delete_ent (self->cb_sk_object, key, G_DISCARD, 0);
1742
1743 if (!HvKEYS (self->cb_sk_object))
1744 {
1745 SvREFCNT_dec (self->cb_sk_object);
1746 self->cb_sk_object = 0;
1747 }
1748 }
1749
1750 XPUSHs (ST (0));
1751}
1752
1753void encode (JSON *self, SV *scalar)
1754 PPCODE:
1755 XPUSHs (encode_json (scalar, self));
1756
1757void decode (JSON *self, SV *jsonstr)
1758 PPCODE:
1759 XPUSHs (decode_json (jsonstr, self, 0));
1760
1761void decode_prefix (JSON *self, SV *jsonstr)
1762 PPCODE:
1763{
1764 STRLEN offset;
1765 EXTEND (SP, 2);
1766 PUSHs (decode_json (jsonstr, self, &offset));
1767 PUSHs (sv_2mortal (newSVuv (offset)));
1768}
1769
1770void incr_parse (JSON *self, SV *jsonstr = 0)
1771 PPCODE:
1772{
1773 if (!self->incr_text)
1774 self->incr_text = newSVpvn ("", 0);
1775
1776 // append data, if any
1777 if (jsonstr)
1778 {
1779 if (SvUTF8 (jsonstr) && !SvUTF8 (self->incr_text))
1780 {
1781 /* utf-8-ness differs, need to upgrade */
1782 sv_utf8_upgrade (self->incr_text);
1783
1784 if (self->incr_pos)
1785 self->incr_pos = utf8_hop ((U8 *)SvPVX (self->incr_text), self->incr_pos)
1786 - (U8 *)SvPVX (self->incr_text);
1787 }
1788
1789 {
1790 STRLEN len;
1791 const char *str = SvPV (jsonstr, len);
1792 SvGROW (self->incr_text, SvCUR (self->incr_text) + len + 1);
1793 Move (str, SvEND (self->incr_text), len, char);
1794 SvCUR_set (self->incr_text, SvCUR (self->incr_text) + len);
1795 *SvEND (self->incr_text) = 0; // this should basically be a nop, too, but make sure it's there
1796 }
1797 }
1798
1799 if (GIMME_V != G_VOID)
1800 do
1801 {
1802 STRLEN offset;
1803
1804 incr_parse (self);
1805
1806 if (!INCR_DONE (self))
1807 break;
1808
1809 XPUSHs (decode_json (self->incr_text, self, &offset));
1810
1811 sv_chop (self->incr_text, SvPV_nolen (self->incr_text) + offset);
1812 self->incr_pos -= offset;
1813 self->incr_nest = 0;
1814 self->incr_mode = 0;
1815 }
1816 while (GIMME_V == G_ARRAY);
1817}
1818
1819SV *incr_text (JSON *self)
1820 ATTRS: lvalue
1195 CODE: 1821 CODE:
1196{ 1822{
1197 UV *uv = SvJSON (self); 1823 if (self->incr_pos)
1198 UV log2 = 0; 1824 croak ("incr_text can only be called after a successful incr_parse call in scalar context %d", self->incr_pos);//D
1199 1825
1200 if (max_depth > 0x80000000UL) max_depth = 0x80000000UL; 1826 RETVAL = self->incr_text ? SvREFCNT_inc (self->incr_text) : &PL_sv_undef;
1201
1202 while ((1UL << log2) < max_depth)
1203 ++log2;
1204
1205 *uv = *uv & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1206
1207 RETVAL = newSVsv (self);
1208} 1827}
1209 OUTPUT: 1828 OUTPUT:
1210 RETVAL 1829 RETVAL
1211 1830
1831void DESTROY (JSON *self)
1832 CODE:
1833 SvREFCNT_dec (self->cb_sk_object);
1834 SvREFCNT_dec (self->cb_object);
1835 SvREFCNT_dec (self->incr_text);
1836
1837PROTOTYPES: ENABLE
1838
1212void encode (SV *self, SV *scalar) 1839void encode_json (SV *scalar)
1840 ALIAS:
1841 to_json_ = 0
1842 encode_json = F_UTF8
1213 PPCODE: 1843 PPCODE:
1844{
1845 JSON json = { F_DEFAULT | ix };
1214 XPUSHs (encode_json (scalar, *SvJSON (self))); 1846 XPUSHs (encode_json (scalar, &json));
1847}
1215 1848
1216void decode (SV *self, SV *jsonstr) 1849void decode_json (SV *jsonstr)
1850 ALIAS:
1851 from_json_ = 0
1852 decode_json = F_UTF8
1217 PPCODE: 1853 PPCODE:
1854{
1855 JSON json = { F_DEFAULT | ix };
1218 XPUSHs (decode_json (jsonstr, *SvJSON (self), 0)); 1856 XPUSHs (decode_json (jsonstr, &json, 0));
1219
1220void decode_prefix (SV *self, SV *jsonstr)
1221 PPCODE:
1222{
1223 UV offset;
1224 EXTEND (SP, 2);
1225 PUSHs (decode_json (jsonstr, *SvJSON (self), &offset));
1226 PUSHs (sv_2mortal (newSVuv (offset)));
1227} 1857}
1228 1858
1229PROTOTYPES: ENABLE
1230 1859
1231void to_json (SV *scalar)
1232 ALIAS:
1233 objToJson = 0
1234 PPCODE:
1235 XPUSHs (encode_json (scalar, F_DEFAULT | F_UTF8));
1236
1237void from_json (SV *jsonstr)
1238 ALIAS:
1239 jsonToObj = 0
1240 PPCODE:
1241 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8, 0));
1242

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines