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