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.52 by root, Mon Jul 2 02:57:11 2007 UTC vs.
Revision 1.73 by root, Wed Mar 19 13:44: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 <float.h>
9 10
10#if defined(__BORLANDC__) || defined(_MSC_VER) 11#if defined(__BORLANDC__) || defined(_MSC_VER)
11# define snprintf _snprintf // C compilers have this in stdio.h 12# define snprintf _snprintf // C compilers have this in stdio.h
12#endif 13#endif
13 14
26#define F_SPACE_AFTER 0x00000040UL 27#define F_SPACE_AFTER 0x00000040UL
27#define F_ALLOW_NONREF 0x00000100UL 28#define F_ALLOW_NONREF 0x00000100UL
28#define F_SHRINK 0x00000200UL 29#define F_SHRINK 0x00000200UL
29#define F_ALLOW_BLESSED 0x00000400UL 30#define F_ALLOW_BLESSED 0x00000400UL
30#define F_CONV_BLESSED 0x00000800UL 31#define F_CONV_BLESSED 0x00000800UL
32#define F_RELAXED 0x00001000UL
33
31#define F_MAXDEPTH 0xf8000000UL 34#define F_MAXDEPTH 0xf8000000UL
32#define S_MAXDEPTH 27 35#define S_MAXDEPTH 27
33#define F_MAXSIZE 0x01f00000UL 36#define F_MAXSIZE 0x01f00000UL
34#define S_MAXSIZE 20 37#define S_MAXSIZE 20
35#define F_HOOK 0x00080000UL // some hooks exist, so slow-path processing 38#define F_HOOK 0x00080000UL // some hooks exist, so slow-path processing
47 50
48#define SB do { 51#define SB do {
49#define SE } while (0) 52#define SE } while (0)
50 53
51#if __GNUC__ >= 3 54#if __GNUC__ >= 3
52# define expect(expr,value) __builtin_expect ((expr),(value)) 55# define expect(expr,value) __builtin_expect ((expr), (value))
53# define inline inline 56# define INLINE static inline
54#else 57#else
55# define expect(expr,value) (expr) 58# define expect(expr,value) (expr)
56# define inline static 59# define INLINE static
57#endif 60#endif
58 61
59#define expect_false(expr) expect ((expr) != 0, 0) 62#define expect_false(expr) expect ((expr) != 0, 0)
60#define expect_true(expr) expect ((expr) != 0, 1) 63#define expect_true(expr) expect ((expr) != 0, 1)
64
65#define IN_RANGE_INC(type,val,beg,end) \
66 ((unsigned type)((unsigned type)(val) - (unsigned type)(beg)) \
67 <= (unsigned type)((unsigned type)(end) - (unsigned type)(beg)))
68
69#ifdef USE_ITHREADS
70# define JSON_SLOW 1
71# define JSON_STASH (json_stash ? json_stash : gv_stashpv ("JSON::XS", 1))
72#else
73# define JSON_SLOW 0
74# define JSON_STASH json_stash
75#endif
61 76
62static HV *json_stash, *json_boolean_stash; // JSON::XS:: 77static HV *json_stash, *json_boolean_stash; // JSON::XS::
63static SV *json_true, *json_false; 78static SV *json_true, *json_false;
64 79
65typedef struct { 80typedef struct {
69} JSON; 84} JSON;
70 85
71///////////////////////////////////////////////////////////////////////////// 86/////////////////////////////////////////////////////////////////////////////
72// utility functions 87// utility functions
73 88
74inline void 89INLINE void
75shrink (SV *sv) 90shrink (SV *sv)
76{ 91{
77 sv_utf8_downgrade (sv, 1); 92 sv_utf8_downgrade (sv, 1);
78 if (SvLEN (sv) > SvCUR (sv) + 1) 93 if (SvLEN (sv) > SvCUR (sv) + 1)
79 { 94 {
88// decode an utf-8 character and return it, or (UV)-1 in 103// decode an utf-8 character and return it, or (UV)-1 in
89// case of an error. 104// case of an error.
90// we special-case "safe" characters from U+80 .. U+7FF, 105// we special-case "safe" characters from U+80 .. U+7FF,
91// but use the very good perl function to parse anything else. 106// but use the very good perl function to parse anything else.
92// note that we never call this function for a ascii codepoints 107// note that we never call this function for a ascii codepoints
93inline UV 108INLINE UV
94decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen) 109decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
95{ 110{
96 if (expect_false (s[0] > 0xdf || s[0] < 0xc2)) 111 if (expect_true (len >= 2
97 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY); 112 && IN_RANGE_INC (char, s[0], 0xc2, 0xdf)
98 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf) 113 && IN_RANGE_INC (char, s[1], 0x80, 0xbf)))
99 { 114 {
100 *clen = 2; 115 *clen = 2;
101 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f); 116 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
102 } 117 }
103 else 118 else
104 { 119 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY);
105 *clen = (STRLEN)-1; 120}
106 return (UV)-1; 121
122// likewise for encoding, also never called for ascii codepoints
123// this function takes advantage of this fact, although current gccs
124// seem to optimise the check for >= 0x80 away anyways
125INLINE unsigned char *
126encode_utf8 (unsigned char *s, UV ch)
127{
128 if (ch <= 0x7FF)
107 } 129 {
130 *s++ = (ch >> 6) | 0xc0;
131 *s++ = (ch & 0x3f) | 0x80;
132 }
133 else
134 s = uvuni_to_utf8_flags (s, ch, 0);
135
136 return s;
108} 137}
109 138
110///////////////////////////////////////////////////////////////////////////// 139/////////////////////////////////////////////////////////////////////////////
111// encoder 140// encoder
112 141
117 char *end; // SvEND (sv) 146 char *end; // SvEND (sv)
118 SV *sv; // result scalar 147 SV *sv; // result scalar
119 JSON json; 148 JSON json;
120 U32 indent; // indentation level 149 U32 indent; // indentation level
121 U32 maxdepth; // max. indentation/recursion level 150 U32 maxdepth; // max. indentation/recursion level
151 UV limit; // escape character values >= this value when encoding
122} enc_t; 152} enc_t;
123 153
124inline void 154INLINE void
125need (enc_t *enc, STRLEN len) 155need (enc_t *enc, STRLEN len)
126{ 156{
127 if (expect_false (enc->cur + len >= enc->end)) 157 if (expect_false (enc->cur + len >= enc->end))
128 { 158 {
129 STRLEN cur = enc->cur - SvPVX (enc->sv); 159 STRLEN cur = enc->cur - SvPVX (enc->sv);
131 enc->cur = SvPVX (enc->sv) + cur; 161 enc->cur = SvPVX (enc->sv) + cur;
132 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1; 162 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
133 } 163 }
134} 164}
135 165
136inline void 166INLINE void
137encode_ch (enc_t *enc, char ch) 167encode_ch (enc_t *enc, char ch)
138{ 168{
139 need (enc, 1); 169 need (enc, 1);
140 *enc->cur++ = ch; 170 *enc->cur++ = ch;
141} 171}
195 { 225 {
196 uch = ch; 226 uch = ch;
197 clen = 1; 227 clen = 1;
198 } 228 }
199 229
200 if (uch > 0x10FFFFUL) 230 if (uch < 0x80/*0x20*/ || uch >= enc->limit)
201 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
202
203 if (uch < 0x80 || enc->json.flags & F_ASCII || (enc->json.flags & F_LATIN1 && uch > 0xFF))
204 { 231 {
205 if (uch > 0xFFFFUL) 232 if (uch > 0xFFFFUL)
206 { 233 {
234 if (uch > 0x10FFFFUL)
235 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
236
207 need (enc, len += 11); 237 need (enc, len += 11);
208 sprintf (enc->cur, "\\u%04x\\u%04x", 238 sprintf (enc->cur, "\\u%04x\\u%04x",
209 (int)((uch - 0x10000) / 0x400 + 0xD800), 239 (int)((uch - 0x10000) / 0x400 + 0xD800),
210 (int)((uch - 0x10000) % 0x400 + 0xDC00)); 240 (int)((uch - 0x10000) % 0x400 + 0xDC00));
211 enc->cur += 12; 241 enc->cur += 12;
239 while (--clen); 269 while (--clen);
240 } 270 }
241 else 271 else
242 { 272 {
243 need (enc, len += UTF8_MAXBYTES - 1); // never more than 11 bytes needed 273 need (enc, len += UTF8_MAXBYTES - 1); // never more than 11 bytes needed
244 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); 274 enc->cur = encode_utf8 (enc->cur, uch);
245 ++str; 275 ++str;
246 } 276 }
247 } 277 }
248 } 278 }
249 } 279 }
250 280
251 --len; 281 --len;
252 } 282 }
253} 283}
254 284
255inline void 285INLINE void
256encode_indent (enc_t *enc) 286encode_indent (enc_t *enc)
257{ 287{
258 if (enc->json.flags & F_INDENT) 288 if (enc->json.flags & F_INDENT)
259 { 289 {
260 int spaces = enc->indent * INDENT_STEP; 290 int spaces = enc->indent * INDENT_STEP;
263 memset (enc->cur, ' ', spaces); 293 memset (enc->cur, ' ', spaces);
264 enc->cur += spaces; 294 enc->cur += spaces;
265 } 295 }
266} 296}
267 297
268inline void 298INLINE void
269encode_space (enc_t *enc) 299encode_space (enc_t *enc)
270{ 300{
271 need (enc, 1); 301 need (enc, 1);
272 encode_ch (enc, ' '); 302 encode_ch (enc, ' ');
273} 303}
274 304
275inline void 305INLINE void
276encode_nl (enc_t *enc) 306encode_nl (enc_t *enc)
277{ 307{
278 if (enc->json.flags & F_INDENT) 308 if (enc->json.flags & F_INDENT)
279 { 309 {
280 need (enc, 1); 310 need (enc, 1);
281 encode_ch (enc, '\n'); 311 encode_ch (enc, '\n');
282 } 312 }
283} 313}
284 314
285inline void 315INLINE void
286encode_comma (enc_t *enc) 316encode_comma (enc_t *enc)
287{ 317{
288 encode_ch (enc, ','); 318 encode_ch (enc, ',');
289 319
290 if (enc->json.flags & F_INDENT) 320 if (enc->json.flags & F_INDENT)
301 int i, len = av_len (av); 331 int i, len = av_len (av);
302 332
303 if (enc->indent >= enc->maxdepth) 333 if (enc->indent >= enc->maxdepth)
304 croak ("data structure too deep (hit recursion limit)"); 334 croak ("data structure too deep (hit recursion limit)");
305 335
306 encode_ch (enc, '['); encode_nl (enc); 336 encode_ch (enc, '[');
307 ++enc->indent; 337
338 if (len >= 0)
339 {
340 encode_nl (enc); ++enc->indent;
308 341
309 for (i = 0; i <= len; ++i) 342 for (i = 0; i <= len; ++i)
310 { 343 {
344 SV **svp = av_fetch (av, i, 0);
345
311 encode_indent (enc); 346 encode_indent (enc);
312 encode_sv (enc, *av_fetch (av, i, 0));
313 347
348 if (svp)
349 encode_sv (enc, *svp);
350 else
351 encode_str (enc, "null", 4, 0);
352
314 if (i < len) 353 if (i < len)
315 encode_comma (enc); 354 encode_comma (enc);
316 } 355 }
317 356
357 encode_nl (enc); --enc->indent; encode_indent (enc);
358 }
359
318 encode_nl (enc); 360 encode_ch (enc, ']');
319
320 --enc->indent;
321 encode_indent (enc); encode_ch (enc, ']');
322} 361}
323 362
324static void 363static void
325encode_he (enc_t *enc, HE *he) 364encode_hk (enc_t *enc, HE *he)
326{ 365{
327 encode_ch (enc, '"'); 366 encode_ch (enc, '"');
328 367
329 if (HeKLEN (he) == HEf_SVKEY) 368 if (HeKLEN (he) == HEf_SVKEY)
330 { 369 {
343 encode_ch (enc, '"'); 382 encode_ch (enc, '"');
344 383
345 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc); 384 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc);
346 encode_ch (enc, ':'); 385 encode_ch (enc, ':');
347 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc); 386 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc);
348 encode_sv (enc, HeVAL (he));
349} 387}
350 388
351// compare hash entries, used when all keys are bytestrings 389// compare hash entries, used when all keys are bytestrings
352static int 390static int
353he_cmp_fast (const void *a_, const void *b_) 391he_cmp_fast (const void *a_, const void *b_)
358 HE *b = *(HE **)b_; 396 HE *b = *(HE **)b_;
359 397
360 STRLEN la = HeKLEN (a); 398 STRLEN la = HeKLEN (a);
361 STRLEN lb = HeKLEN (b); 399 STRLEN lb = HeKLEN (b);
362 400
363 if (!(cmp = memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb))) 401 if (!(cmp = memcmp (HeKEY (b), HeKEY (a), lb < la ? lb : la)))
364 cmp = la - lb; 402 cmp = lb - la;
365 403
366 return cmp; 404 return cmp;
367} 405}
368 406
369// compare hash entries, used when some keys are sv's or utf-x 407// compare hash entries, used when some keys are sv's or utf-x
370static int 408static int
371he_cmp_slow (const void *a, const void *b) 409he_cmp_slow (const void *a, const void *b)
372{ 410{
373 return sv_cmp (HeSVKEY_force (*(HE **)a), HeSVKEY_force (*(HE **)b)); 411 return sv_cmp (HeSVKEY_force (*(HE **)b), HeSVKEY_force (*(HE **)a));
374} 412}
375 413
376static void 414static void
377encode_hv (enc_t *enc, HV *hv) 415encode_hv (enc_t *enc, HV *hv)
378{ 416{
417 HE *he;
379 int count, i; 418 int count;
380 419
381 if (enc->indent >= enc->maxdepth) 420 if (enc->indent >= enc->maxdepth)
382 croak ("data structure too deep (hit recursion limit)"); 421 croak ("data structure too deep (hit recursion limit)");
383 422
384 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent; 423 encode_ch (enc, '{');
385 424
386 if ((count = hv_iterinit (hv)))
387 {
388 // for canonical output we have to sort by keys first 425 // for canonical output we have to sort by keys first
389 // actually, this is mostly due to the stupid so-called 426 // actually, this is mostly due to the stupid so-called
390 // security workaround added somewhere in 5.8.x. 427 // security workaround added somewhere in 5.8.x.
391 // that randomises hash orderings 428 // that randomises hash orderings
392 if (enc->json.flags & F_CANONICAL) 429 if (enc->json.flags & F_CANONICAL)
430 {
431 int count = hv_iterinit (hv);
432
433 if (SvMAGICAL (hv))
393 { 434 {
435 // need to count by iterating. could improve by dynamically building the vector below
436 // but I don't care for the speed of this special case.
437 // note also that we will run into undefined behaviour when the two iterations
438 // do not result in the same count, something I might care for in some later release.
439
440 count = 0;
441 while (hv_iternext (hv))
442 ++count;
443
444 hv_iterinit (hv);
445 }
446
447 if (count)
448 {
394 int fast = 1; 449 int i, fast = 1;
395 HE *he;
396#if defined(__BORLANDC__) || defined(_MSC_VER) 450#if defined(__BORLANDC__) || defined(_MSC_VER)
397 HE **hes = _alloca (count * sizeof (HE)); 451 HE **hes = _alloca (count * sizeof (HE));
398#else 452#else
399 HE *hes [count]; // if your compiler dies here, you need to enable C99 mode 453 HE *hes [count]; // if your compiler dies here, you need to enable C99 mode
400#endif 454#endif
427 481
428 FREETMPS; 482 FREETMPS;
429 LEAVE; 483 LEAVE;
430 } 484 }
431 485
432 for (i = 0; i < count; ++i) 486 encode_nl (enc); ++enc->indent;
487
488 while (count--)
433 { 489 {
434 encode_indent (enc); 490 encode_indent (enc);
491 he = hes [count];
435 encode_he (enc, hes [i]); 492 encode_hk (enc, he);
493 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
436 494
437 if (i < count - 1) 495 if (count)
438 encode_comma (enc); 496 encode_comma (enc);
439 } 497 }
440 498
441 encode_nl (enc); 499 encode_nl (enc); --enc->indent; encode_indent (enc);
442 } 500 }
501 }
443 else 502 else
503 {
504 if (hv_iterinit (hv) || SvMAGICAL (hv))
505 if ((he = hv_iternext (hv)))
444 { 506 {
445 HE *he = hv_iternext (hv); 507 encode_nl (enc); ++enc->indent;
446 508
447 for (;;) 509 for (;;)
448 { 510 {
449 encode_indent (enc); 511 encode_indent (enc);
450 encode_he (enc, he); 512 encode_hk (enc, he);
513 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
451 514
452 if (!(he = hv_iternext (hv))) 515 if (!(he = hv_iternext (hv)))
453 break; 516 break;
454 517
455 encode_comma (enc); 518 encode_comma (enc);
456 } 519 }
457 520
458 encode_nl (enc); 521 encode_nl (enc); --enc->indent; encode_indent (enc);
459 } 522 }
460 } 523 }
461 524
462 --enc->indent; encode_indent (enc); encode_ch (enc, '}'); 525 encode_ch (enc, '}');
463} 526}
464 527
465// encode objects, arrays and special \0=false and \1=true values. 528// encode objects, arrays and special \0=false and \1=true values.
466static void 529static void
467encode_rv (enc_t *enc, SV *sv) 530encode_rv (enc_t *enc, SV *sv)
471 SvGETMAGIC (sv); 534 SvGETMAGIC (sv);
472 svt = SvTYPE (sv); 535 svt = SvTYPE (sv);
473 536
474 if (expect_false (SvOBJECT (sv))) 537 if (expect_false (SvOBJECT (sv)))
475 { 538 {
539 HV *stash = !JSON_SLOW || json_boolean_stash
540 ? json_boolean_stash
541 : gv_stashpv ("JSON::XS::Boolean", 1);
542
476 if (SvSTASH (sv) == json_boolean_stash) 543 if (SvSTASH (sv) == stash)
477 { 544 {
478 if (SvIV (sv)) 545 if (SvIV (sv))
479 encode_str (enc, "true", 4, 0); 546 encode_str (enc, "true", 4, 0);
480 else 547 else
481 encode_str (enc, "false", 5, 0); 548 encode_str (enc, "false", 5, 0);
489 } 556 }
490#endif 557#endif
491 if (enc->json.flags & F_CONV_BLESSED) 558 if (enc->json.flags & F_CONV_BLESSED)
492 { 559 {
493 // we re-bless the reference to get overload and other niceties right 560 // we re-bless the reference to get overload and other niceties right
494 GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 1); 561 GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 0);
495 562
496 if (to_json) 563 if (to_json)
497 { 564 {
565 dSP;
566
498 dSP; ENTER; SAVETMPS; PUSHMARK (SP); 567 ENTER; SAVETMPS; PUSHMARK (SP);
499 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv))); 568 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv)));
500 569
501 // calling with G_SCALAR ensures that we always get a 1 reutrn value 570 // calling with G_SCALAR ensures that we always get a 1 return value
502 // check anyways.
503 PUTBACK; 571 PUTBACK;
504 assert (1 == call_sv ((SV *)GvCV (to_json), G_SCALAR)); 572 call_sv ((SV *)GvCV (to_json), G_SCALAR);
505 SPAGAIN; 573 SPAGAIN;
506 574
575 // catch this surprisingly common error
576 if (SvROK (TOPs) && SvRV (TOPs) == sv)
577 croak ("%s::TO_JSON method returned same object as was passed instead of a new one", HvNAME (SvSTASH (sv)));
578
579 sv = POPs;
580 PUTBACK;
581
507 encode_sv (enc, POPs); 582 encode_sv (enc, sv);
508 583
509 FREETMPS; LEAVE; 584 FREETMPS; LEAVE;
510 } 585 }
511 else if (enc->json.flags & F_ALLOW_BLESSED) 586 else if (enc->json.flags & F_ALLOW_BLESSED)
512 encode_str (enc, "null", 4, 0); 587 encode_str (enc, "null", 4, 0);
624 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 699 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
625 enc.cur = SvPVX (enc.sv); 700 enc.cur = SvPVX (enc.sv);
626 enc.end = SvEND (enc.sv); 701 enc.end = SvEND (enc.sv);
627 enc.indent = 0; 702 enc.indent = 0;
628 enc.maxdepth = DEC_DEPTH (enc.json.flags); 703 enc.maxdepth = DEC_DEPTH (enc.json.flags);
704 enc.limit = enc.json.flags & F_ASCII ? 0x000080UL
705 : enc.json.flags & F_LATIN1 ? 0x000100UL
706 : 0x10FFFFUL;
629 707
630 SvPOK_only (enc.sv); 708 SvPOK_only (enc.sv);
631 encode_sv (&enc, scalar); 709 encode_sv (&enc, scalar);
632 710
633 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); 711 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
654 JSON json; 732 JSON json;
655 U32 depth; // recursion depth 733 U32 depth; // recursion depth
656 U32 maxdepth; // recursion depth limit 734 U32 maxdepth; // recursion depth limit
657} dec_t; 735} dec_t;
658 736
659inline void 737INLINE void
738decode_comment (dec_t *dec)
739{
740 // only '#'-style comments allowed a.t.m.
741
742 while (*dec->cur && *dec->cur != 0x0a && *dec->cur != 0x0d)
743 ++dec->cur;
744}
745
746INLINE void
660decode_ws (dec_t *dec) 747decode_ws (dec_t *dec)
661{ 748{
662 for (;;) 749 for (;;)
663 { 750 {
664 char ch = *dec->cur; 751 char ch = *dec->cur;
665 752
666 if (ch > 0x20 753 if (ch > 0x20)
754 {
755 if (expect_false (ch == '#'))
756 {
757 if (dec->json.flags & F_RELAXED)
758 decode_comment (dec);
759 else
760 break;
761 }
762 else
763 break;
764 }
667 || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)) 765 else if (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)
668 break; 766 break; // parse error, but let higher level handle it, gives better error messages
669 767
670 ++dec->cur; 768 ++dec->cur;
671 } 769 }
672} 770}
673 771
779 877
780 if (hi >= 0x80) 878 if (hi >= 0x80)
781 { 879 {
782 utf8 = 1; 880 utf8 = 1;
783 881
784 cur = (char *)uvuni_to_utf8_flags (cur, hi, 0); 882 cur = encode_utf8 (cur, hi);
785 } 883 }
786 else 884 else
787 *cur++ = hi; 885 *cur++ = hi;
788 } 886 }
789 break; 887 break;
922 is_nv = 1; 1020 is_nv = 1;
923 } 1021 }
924 1022
925 if (!is_nv) 1023 if (!is_nv)
926 { 1024 {
1025 int len = dec->cur - start;
1026
927 // special case the rather common 1..4-digit-int case, assumes 32 bit ints or so 1027 // special case the rather common 1..5-digit-int case
928 if (*start == '-') 1028 if (*start == '-')
929 switch (dec->cur - start) 1029 switch (len)
930 { 1030 {
931 case 2: return newSViv (-( start [1] - '0' * 1)); 1031 case 2: return newSViv (-( start [1] - '0' * 1));
932 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11)); 1032 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11));
933 case 4: return newSViv (-( start [1] * 100 + start [2] * 10 + start [3] - '0' * 111)); 1033 case 4: return newSViv (-( start [1] * 100 + start [2] * 10 + start [3] - '0' * 111));
934 case 5: return newSViv (-(start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111)); 1034 case 5: return newSViv (-( start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111));
1035 case 6: return newSViv (-(start [1] * 10000 + start [2] * 1000 + start [3] * 100 + start [4] * 10 + start [5] - '0' * 11111));
935 } 1036 }
936 else 1037 else
937 switch (dec->cur - start) 1038 switch (len)
938 { 1039 {
939 case 1: return newSViv ( start [0] - '0' * 1); 1040 case 1: return newSViv ( start [0] - '0' * 1);
940 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11); 1041 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11);
941 case 3: return newSViv ( start [0] * 100 + start [1] * 10 + start [2] - '0' * 111); 1042 case 3: return newSViv ( start [0] * 100 + start [1] * 10 + start [2] - '0' * 111);
942 case 4: return newSViv ( start [0] * 1000 + start [1] * 100 + start [2] * 10 + start [3] - '0' * 1111); 1043 case 4: return newSViv ( start [0] * 1000 + start [1] * 100 + start [2] * 10 + start [3] - '0' * 1111);
1044 case 5: return newSViv ( start [0] * 10000 + start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 11111);
943 } 1045 }
944 1046
945 { 1047 {
946 UV uv; 1048 UV uv;
947 int numtype = grok_number (start, dec->cur - start, &uv); 1049 int numtype = grok_number (start, len, &uv);
948 if (numtype & IS_NUMBER_IN_UV) 1050 if (numtype & IS_NUMBER_IN_UV)
949 if (numtype & IS_NUMBER_NEG) 1051 if (numtype & IS_NUMBER_NEG)
950 { 1052 {
951 if (uv < (UV)IV_MIN) 1053 if (uv < (UV)IV_MIN)
952 return newSViv (-(IV)uv); 1054 return newSViv (-(IV)uv);
953 } 1055 }
954 else 1056 else
955 return newSVuv (uv); 1057 return newSVuv (uv);
956
957 // here would likely be the place for bigint support
958 } 1058 }
959 }
960 1059
961 // if we ever support bigint or bigfloat, this is the place for bigfloat 1060 len -= *start == '-' ? 1 : 0;
1061
1062 // does not fit into IV or UV, try NV
1063 if ((sizeof (NV) == sizeof (double) && DBL_DIG >= len)
1064 #if defined (LDBL_DIG)
1065 || (sizeof (NV) == sizeof (long double) && LDBL_DIG >= len)
1066 #endif
1067 )
1068 // fits into NV without loss of precision
1069 return newSVnv (Atof (start));
1070
1071 // everything else fails, convert it to a string
1072 return newSVpvn (start, dec->cur - start);
1073 }
1074
1075 // loss of precision here
962 return newSVnv (Atof (start)); 1076 return newSVnv (Atof (start));
963 1077
964fail: 1078fail:
965 return 0; 1079 return 0;
966} 1080}
996 1110
997 if (*dec->cur != ',') 1111 if (*dec->cur != ',')
998 ERR (", or ] expected while parsing array"); 1112 ERR (", or ] expected while parsing array");
999 1113
1000 ++dec->cur; 1114 ++dec->cur;
1115
1116 decode_ws (dec);
1117
1118 if (*dec->cur == ']' && dec->json.flags & F_RELAXED)
1119 {
1120 ++dec->cur;
1121 break;
1122 }
1001 } 1123 }
1002 1124
1003 DEC_DEC_DEPTH; 1125 DEC_DEC_DEPTH;
1004 return newRV_noinc ((SV *)av); 1126 return newRV_noinc ((SV *)av);
1005 1127
1021 if (*dec->cur == '}') 1143 if (*dec->cur == '}')
1022 ++dec->cur; 1144 ++dec->cur;
1023 else 1145 else
1024 for (;;) 1146 for (;;)
1025 { 1147 {
1026 decode_ws (dec); EXPECT_CH ('"'); 1148 EXPECT_CH ('"');
1027 1149
1028 // heuristic: assume that 1150 // heuristic: assume that
1029 // a) decode_str + hv_store_ent are abysmally slow. 1151 // a) decode_str + hv_store_ent are abysmally slow.
1030 // b) most hash keys are short, simple ascii text. 1152 // b) most hash keys are short, simple ascii text.
1031 // => try to "fast-match" such strings to avoid 1153 // => try to "fast-match" such strings to avoid
1045 if (!key) 1167 if (!key)
1046 goto fail; 1168 goto fail;
1047 1169
1048 decode_ws (dec); EXPECT_CH (':'); 1170 decode_ws (dec); EXPECT_CH (':');
1049 1171
1172 decode_ws (dec);
1050 value = decode_sv (dec); 1173 value = decode_sv (dec);
1051 if (!value) 1174 if (!value)
1052 { 1175 {
1053 SvREFCNT_dec (key); 1176 SvREFCNT_dec (key);
1054 goto fail; 1177 goto fail;
1066 int len = p - key; 1189 int len = p - key;
1067 dec->cur = p + 1; 1190 dec->cur = p + 1;
1068 1191
1069 decode_ws (dec); EXPECT_CH (':'); 1192 decode_ws (dec); EXPECT_CH (':');
1070 1193
1194 decode_ws (dec);
1071 value = decode_sv (dec); 1195 value = decode_sv (dec);
1072 if (!value) 1196 if (!value)
1073 goto fail; 1197 goto fail;
1074 1198
1075 hv_store (hv, key, len, value, 0); 1199 hv_store (hv, key, len, value, 0);
1091 1215
1092 if (*dec->cur != ',') 1216 if (*dec->cur != ',')
1093 ERR (", or } expected while parsing object/hash"); 1217 ERR (", or } expected while parsing object/hash");
1094 1218
1095 ++dec->cur; 1219 ++dec->cur;
1220
1221 decode_ws (dec);
1222
1223 if (*dec->cur == '}' && dec->json.flags & F_RELAXED)
1224 {
1225 ++dec->cur;
1226 break;
1227 }
1096 } 1228 }
1097 1229
1098 DEC_DEC_DEPTH; 1230 DEC_DEC_DEPTH;
1099 sv = newRV_noinc ((SV *)hv); 1231 sv = newRV_noinc ((SV *)hv);
1100 1232
1113 // might want to optimise this for common cases. 1245 // might want to optimise this for common cases.
1114 cb = hv_fetch_ent (dec->json.cb_sk_object, hv_iterkeysv (he), 0, 0); 1246 cb = hv_fetch_ent (dec->json.cb_sk_object, hv_iterkeysv (he), 0, 0);
1115 1247
1116 if (cb) 1248 if (cb)
1117 { 1249 {
1250 dSP;
1118 int count; 1251 int count;
1119 ENTER; SAVETMPS;
1120 1252
1121 dSP; PUSHMARK (SP); 1253 ENTER; SAVETMPS; PUSHMARK (SP);
1122 XPUSHs (HeVAL (he)); 1254 XPUSHs (HeVAL (he));
1123 1255
1124 PUTBACK; count = call_sv (HeVAL (cb), G_ARRAY); SPAGAIN; 1256 PUTBACK; count = call_sv (HeVAL (cb), G_ARRAY); SPAGAIN;
1125 1257
1126 if (count == 1) 1258 if (count == 1)
1134 } 1266 }
1135 } 1267 }
1136 1268
1137 if (dec->json.cb_object) 1269 if (dec->json.cb_object)
1138 { 1270 {
1271 dSP;
1139 int count; 1272 int count;
1140 ENTER; SAVETMPS;
1141 1273
1142 dSP; ENTER; SAVETMPS; PUSHMARK (SP); 1274 ENTER; SAVETMPS; PUSHMARK (SP);
1143 XPUSHs (sv_2mortal (sv)); 1275 XPUSHs (sv_2mortal (sv));
1144 1276
1145 PUTBACK; count = call_sv (dec->json.cb_object, G_ARRAY); SPAGAIN; 1277 PUTBACK; count = call_sv (dec->json.cb_object, G_ARRAY); SPAGAIN;
1146 1278
1147 if (count == 1) 1279 if (count == 1)
1165} 1297}
1166 1298
1167static SV * 1299static SV *
1168decode_sv (dec_t *dec) 1300decode_sv (dec_t *dec)
1169{ 1301{
1170 decode_ws (dec);
1171
1172 // the beauty of JSON: you need exactly one character lookahead 1302 // the beauty of JSON: you need exactly one character lookahead
1173 // to parse anything. 1303 // to parse everything.
1174 switch (*dec->cur) 1304 switch (*dec->cur)
1175 { 1305 {
1176 case '"': ++dec->cur; return decode_str (dec); 1306 case '"': ++dec->cur; return decode_str (dec);
1177 case '[': ++dec->cur; return decode_av (dec); 1307 case '[': ++dec->cur; return decode_av (dec);
1178 case '{': ++dec->cur; return decode_hv (dec); 1308 case '{': ++dec->cur; return decode_hv (dec);
1179 1309
1180 case '-': 1310 case '-':
1181 case '0': case '1': case '2': case '3': case '4': 1311 case '0': case '1': case '2': case '3': case '4':
1182 case '5': case '6': case '7': case '8': case '9': 1312 case '5': case '6': case '7': case '8': case '9':
1183 return decode_num (dec); 1313 return decode_num (dec);
1184 1314
1185 case 't': 1315 case 't':
1186 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1316 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
1187 { 1317 {
1188 dec->cur += 4; 1318 dec->cur += 4;
1319#if JSON_SLOW
1320 json_true = get_sv ("JSON::XS::true", 1); SvREADONLY_on (json_true);
1321#endif
1189 return SvREFCNT_inc (json_true); 1322 return SvREFCNT_inc (json_true);
1190 } 1323 }
1191 else 1324 else
1192 ERR ("'true' expected"); 1325 ERR ("'true' expected");
1193 1326
1195 1328
1196 case 'f': 1329 case 'f':
1197 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1330 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
1198 { 1331 {
1199 dec->cur += 5; 1332 dec->cur += 5;
1333#if JSON_SLOW
1334 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1335#endif
1200 return SvREFCNT_inc (json_false); 1336 return SvREFCNT_inc (json_false);
1201 } 1337 }
1202 else 1338 else
1203 ERR ("'false' expected"); 1339 ERR ("'false' expected");
1204 1340
1254 1390
1255 if (dec.json.cb_object || dec.json.cb_sk_object) 1391 if (dec.json.cb_object || dec.json.cb_sk_object)
1256 dec.json.flags |= F_HOOK; 1392 dec.json.flags |= F_HOOK;
1257 1393
1258 *dec.end = 0; // this should basically be a nop, too, but make sure it's there 1394 *dec.end = 0; // this should basically be a nop, too, but make sure it's there
1395
1396 decode_ws (&dec);
1259 sv = decode_sv (&dec); 1397 sv = decode_sv (&dec);
1260 1398
1261 if (!(offset_return || !sv)) 1399 if (!(offset_return || !sv))
1262 { 1400 {
1263 // check for trailing garbage 1401 // check for trailing garbage
1331 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false); 1469 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1332} 1470}
1333 1471
1334PROTOTYPES: DISABLE 1472PROTOTYPES: DISABLE
1335 1473
1474void CLONE (...)
1475 CODE:
1476 json_stash = 0;
1477 json_boolean_stash = 0;
1478
1336void new (char *klass) 1479void new (char *klass)
1337 PPCODE: 1480 PPCODE:
1338{ 1481{
1339 SV *pv = NEWSV (0, sizeof (JSON)); 1482 SV *pv = NEWSV (0, sizeof (JSON));
1340 SvPOK_only (pv); 1483 SvPOK_only (pv);
1341 Zero (SvPVX (pv), 1, JSON); 1484 Zero (SvPVX (pv), 1, JSON);
1342 ((JSON *)SvPVX (pv))->flags = F_DEFAULT; 1485 ((JSON *)SvPVX (pv))->flags = F_DEFAULT;
1343 XPUSHs (sv_2mortal (sv_bless (newRV_noinc (pv), json_stash))); 1486 XPUSHs (sv_2mortal (sv_bless (
1487 newRV_noinc (pv),
1488 strEQ (klass, "JSON::XS") ? JSON_STASH : gv_stashpv (klass, 1)
1489 )));
1344} 1490}
1345 1491
1346void ascii (JSON *self, int enable = 1) 1492void ascii (JSON *self, int enable = 1)
1347 ALIAS: 1493 ALIAS:
1348 ascii = F_ASCII 1494 ascii = F_ASCII
1355 pretty = F_PRETTY 1501 pretty = F_PRETTY
1356 allow_nonref = F_ALLOW_NONREF 1502 allow_nonref = F_ALLOW_NONREF
1357 shrink = F_SHRINK 1503 shrink = F_SHRINK
1358 allow_blessed = F_ALLOW_BLESSED 1504 allow_blessed = F_ALLOW_BLESSED
1359 convert_blessed = F_CONV_BLESSED 1505 convert_blessed = F_CONV_BLESSED
1506 relaxed = F_RELAXED
1360 PPCODE: 1507 PPCODE:
1361{ 1508{
1362 if (enable) 1509 if (enable)
1363 self->flags |= ix; 1510 self->flags |= ix;
1364 else 1511 else
1365 self->flags &= ~ix; 1512 self->flags &= ~ix;
1366 1513
1367 XPUSHs (ST (0)); 1514 XPUSHs (ST (0));
1368} 1515}
1369 1516
1517void get_ascii (JSON *self)
1518 ALIAS:
1519 get_ascii = F_ASCII
1520 get_latin1 = F_LATIN1
1521 get_utf8 = F_UTF8
1522 get_indent = F_INDENT
1523 get_canonical = F_CANONICAL
1524 get_space_before = F_SPACE_BEFORE
1525 get_space_after = F_SPACE_AFTER
1526 get_allow_nonref = F_ALLOW_NONREF
1527 get_shrink = F_SHRINK
1528 get_allow_blessed = F_ALLOW_BLESSED
1529 get_convert_blessed = F_CONV_BLESSED
1530 get_relaxed = F_RELAXED
1531 PPCODE:
1532 XPUSHs (boolSV (self->flags & ix));
1533
1370void max_depth (JSON *self, UV max_depth = 0x80000000UL) 1534void max_depth (JSON *self, UV max_depth = 0x80000000UL)
1371 PPCODE: 1535 PPCODE:
1372{ 1536{
1373 UV log2 = 0; 1537 UV log2 = 0;
1374 1538
1380 self->flags = self->flags & ~F_MAXDEPTH | (log2 << S_MAXDEPTH); 1544 self->flags = self->flags & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1381 1545
1382 XPUSHs (ST (0)); 1546 XPUSHs (ST (0));
1383} 1547}
1384 1548
1549U32 get_max_depth (JSON *self)
1550 CODE:
1551 RETVAL = DEC_DEPTH (self->flags);
1552 OUTPUT:
1553 RETVAL
1554
1385void max_size (JSON *self, UV max_size = 0) 1555void max_size (JSON *self, UV max_size = 0)
1386 PPCODE: 1556 PPCODE:
1387{ 1557{
1388 UV log2 = 0; 1558 UV log2 = 0;
1389 1559
1395 1565
1396 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE); 1566 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE);
1397 1567
1398 XPUSHs (ST (0)); 1568 XPUSHs (ST (0));
1399} 1569}
1570
1571int get_max_size (JSON *self)
1572 CODE:
1573 RETVAL = DEC_SIZE (self->flags);
1574 OUTPUT:
1575 RETVAL
1400 1576
1401void filter_json_object (JSON *self, SV *cb = &PL_sv_undef) 1577void filter_json_object (JSON *self, SV *cb = &PL_sv_undef)
1402 PPCODE: 1578 PPCODE:
1403{ 1579{
1404 SvREFCNT_dec (self->cb_object); 1580 SvREFCNT_dec (self->cb_object);
1451 SvREFCNT_dec (self->cb_sk_object); 1627 SvREFCNT_dec (self->cb_sk_object);
1452 SvREFCNT_dec (self->cb_object); 1628 SvREFCNT_dec (self->cb_object);
1453 1629
1454PROTOTYPES: ENABLE 1630PROTOTYPES: ENABLE
1455 1631
1456void to_json (SV *scalar) 1632void encode_json (SV *scalar)
1457 PPCODE: 1633 PPCODE:
1458{ 1634{
1459 JSON json = { F_DEFAULT | F_UTF8 }; 1635 JSON json = { F_DEFAULT | F_UTF8 };
1460 XPUSHs (encode_json (scalar, &json)); 1636 XPUSHs (encode_json (scalar, &json));
1461} 1637}
1462 1638
1463void from_json (SV *jsonstr) 1639void decode_json (SV *jsonstr)
1464 PPCODE: 1640 PPCODE:
1465{ 1641{
1466 JSON json = { F_DEFAULT | F_UTF8 }; 1642 JSON json = { F_DEFAULT | F_UTF8 };
1467 XPUSHs (decode_json (jsonstr, &json, 0)); 1643 XPUSHs (decode_json (jsonstr, &json, 0));
1468} 1644}

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines