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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines