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.57 by root, Mon Aug 13 16:05:42 2007 UTC vs.
Revision 1.75 by root, Wed Mar 19 15:37:54 2008 UTC

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>
9#include <float.h> 10#include <float.h>
10 11
11#if defined(__BORLANDC__) || defined(_MSC_VER) 12#if defined(__BORLANDC__) || defined(_MSC_VER)
12# define snprintf _snprintf // C compilers have this in stdio.h 13# define snprintf _snprintf // C compilers have this in stdio.h
13#endif 14#endif
15// 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
16// guarentees, though. if it breaks, you get to keep the pieces. 17// guarentees, though. if it breaks, you get to keep the pieces.
17#ifndef UTF8_MAXBYTES 18#ifndef UTF8_MAXBYTES
18# define UTF8_MAXBYTES 13 19# define UTF8_MAXBYTES 13
19#endif 20#endif
21
22#define IVUV_MAXCHARS (sizeof (UV) * CHAR_BIT * 28 / 93 + 2)
20 23
21#define F_ASCII 0x00000001UL 24#define F_ASCII 0x00000001UL
22#define F_LATIN1 0x00000002UL 25#define F_LATIN1 0x00000002UL
23#define F_UTF8 0x00000004UL 26#define F_UTF8 0x00000004UL
24#define F_INDENT 0x00000008UL 27#define F_INDENT 0x00000008UL
27#define F_SPACE_AFTER 0x00000040UL 30#define F_SPACE_AFTER 0x00000040UL
28#define F_ALLOW_NONREF 0x00000100UL 31#define F_ALLOW_NONREF 0x00000100UL
29#define F_SHRINK 0x00000200UL 32#define F_SHRINK 0x00000200UL
30#define F_ALLOW_BLESSED 0x00000400UL 33#define F_ALLOW_BLESSED 0x00000400UL
31#define F_CONV_BLESSED 0x00000800UL 34#define F_CONV_BLESSED 0x00000800UL
35#define F_RELAXED 0x00001000UL
36
32#define F_MAXDEPTH 0xf8000000UL 37#define F_MAXDEPTH 0xf8000000UL
33#define S_MAXDEPTH 27 38#define S_MAXDEPTH 27
34#define F_MAXSIZE 0x01f00000UL 39#define F_MAXSIZE 0x01f00000UL
35#define S_MAXSIZE 20 40#define S_MAXSIZE 20
36#define F_HOOK 0x00080000UL // some hooks exist, so slow-path processing 41#define F_HOOK 0x00080000UL // some hooks exist, so slow-path processing
48 53
49#define SB do { 54#define SB do {
50#define SE } while (0) 55#define SE } while (0)
51 56
52#if __GNUC__ >= 3 57#if __GNUC__ >= 3
53# define expect(expr,value) __builtin_expect ((expr),(value)) 58# define expect(expr,value) __builtin_expect ((expr), (value))
54# define inline inline 59# define INLINE static inline
55#else 60#else
56# define expect(expr,value) (expr) 61# define expect(expr,value) (expr)
57# define inline static 62# define INLINE static
58#endif 63#endif
59 64
60#define expect_false(expr) expect ((expr) != 0, 0) 65#define expect_false(expr) expect ((expr) != 0, 0)
61#define expect_true(expr) expect ((expr) != 0, 1) 66#define expect_true(expr) expect ((expr) != 0, 1)
62 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
63#ifdef USE_ITHREADS 72#ifdef USE_ITHREADS
64# define JSON_SLOW 1 73# define JSON_SLOW 1
74# define JSON_STASH (json_stash ? json_stash : gv_stashpv ("JSON::XS", 1))
65#else 75#else
66# define JSON_SLOW 1 76# define JSON_SLOW 0
77# define JSON_STASH json_stash
67#endif 78#endif
68 79
69static HV *json_stash, *json_boolean_stash; // JSON::XS:: 80static HV *json_stash, *json_boolean_stash; // JSON::XS::
70static SV *json_true, *json_false; 81static SV *json_true, *json_false;
71 82
76} JSON; 87} JSON;
77 88
78///////////////////////////////////////////////////////////////////////////// 89/////////////////////////////////////////////////////////////////////////////
79// utility functions 90// utility functions
80 91
81inline void 92INLINE void
82shrink (SV *sv) 93shrink (SV *sv)
83{ 94{
84 sv_utf8_downgrade (sv, 1); 95 sv_utf8_downgrade (sv, 1);
85 if (SvLEN (sv) > SvCUR (sv) + 1) 96 if (SvLEN (sv) > SvCUR (sv) + 1)
86 { 97 {
95// decode an utf-8 character and return it, or (UV)-1 in 106// decode an utf-8 character and return it, or (UV)-1 in
96// case of an error. 107// case of an error.
97// we special-case "safe" characters from U+80 .. U+7FF, 108// we special-case "safe" characters from U+80 .. U+7FF,
98// but use the very good perl function to parse anything else. 109// but use the very good perl function to parse anything else.
99// note that we never call this function for a ascii codepoints 110// note that we never call this function for a ascii codepoints
100inline UV 111INLINE UV
101decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen) 112decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
102{ 113{
103 if (expect_false (s[0] > 0xdf || s[0] < 0xc2)) 114 if (expect_true (len >= 2
104 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY); 115 && IN_RANGE_INC (char, s[0], 0xc2, 0xdf)
105 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf) 116 && IN_RANGE_INC (char, s[1], 0x80, 0xbf)))
106 { 117 {
107 *clen = 2; 118 *clen = 2;
108 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f); 119 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
109 } 120 }
110 else 121 else
111 { 122 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY);
112 *clen = (STRLEN)-1; 123}
113 return (UV)-1; 124
114 } 125// likewise for encoding, also never called for ascii codepoints
126// this function takes advantage of this fact, although current gccs
127// seem to optimise the check for >= 0x80 away anyways
128INLINE unsigned char *
129encode_utf8 (unsigned char *s, UV ch)
130{
131 if (expect_false (ch < 0x000080))
132 *s++ = ch;
133 else if (expect_true (ch < 0x000800))
134 *s++ = 0xc0 | ( ch >> 6),
135 *s++ = 0x80 | ( ch & 0x3f);
136 else if ( ch < 0x010000)
137 *s++ = 0xe0 | ( ch >> 12),
138 *s++ = 0x80 | ((ch >> 6) & 0x3f),
139 *s++ = 0x80 | ( ch & 0x3f);
140 else if ( ch < 0x110000)
141 *s++ = 0xf0 | ( ch >> 18),
142 *s++ = 0x80 | ((ch >> 12) & 0x3f),
143 *s++ = 0x80 | ((ch >> 6) & 0x3f),
144 *s++ = 0x80 | ( ch & 0x3f);
145
146 return s;
115} 147}
116 148
117///////////////////////////////////////////////////////////////////////////// 149/////////////////////////////////////////////////////////////////////////////
118// encoder 150// encoder
119 151
124 char *end; // SvEND (sv) 156 char *end; // SvEND (sv)
125 SV *sv; // result scalar 157 SV *sv; // result scalar
126 JSON json; 158 JSON json;
127 U32 indent; // indentation level 159 U32 indent; // indentation level
128 U32 maxdepth; // max. indentation/recursion level 160 U32 maxdepth; // max. indentation/recursion level
161 UV limit; // escape character values >= this value when encoding
129} enc_t; 162} enc_t;
130 163
131inline void 164INLINE void
132need (enc_t *enc, STRLEN len) 165need (enc_t *enc, STRLEN len)
133{ 166{
134 if (expect_false (enc->cur + len >= enc->end)) 167 if (expect_false (enc->cur + len >= enc->end))
135 { 168 {
136 STRLEN cur = enc->cur - SvPVX (enc->sv); 169 STRLEN cur = enc->cur - SvPVX (enc->sv);
138 enc->cur = SvPVX (enc->sv) + cur; 171 enc->cur = SvPVX (enc->sv) + cur;
139 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1; 172 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
140 } 173 }
141} 174}
142 175
143inline void 176INLINE void
144encode_ch (enc_t *enc, char ch) 177encode_ch (enc_t *enc, char ch)
145{ 178{
146 need (enc, 1); 179 need (enc, 1);
147 *enc->cur++ = ch; 180 *enc->cur++ = ch;
148} 181}
202 { 235 {
203 uch = ch; 236 uch = ch;
204 clen = 1; 237 clen = 1;
205 } 238 }
206 239
207 if (uch > 0x10FFFFUL) 240 if (uch < 0x80/*0x20*/ || uch >= enc->limit)
208 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
209
210 if (uch < 0x80 || enc->json.flags & F_ASCII || (enc->json.flags & F_LATIN1 && uch > 0xFF))
211 { 241 {
212 if (uch > 0xFFFFUL) 242 if (uch >= 0x10000UL)
213 { 243 {
244 if (uch >= 0x110000UL)
245 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
246
214 need (enc, len += 11); 247 need (enc, len += 11);
215 sprintf (enc->cur, "\\u%04x\\u%04x", 248 sprintf (enc->cur, "\\u%04x\\u%04x",
216 (int)((uch - 0x10000) / 0x400 + 0xD800), 249 (int)((uch - 0x10000) / 0x400 + 0xD800),
217 (int)((uch - 0x10000) % 0x400 + 0xDC00)); 250 (int)((uch - 0x10000) % 0x400 + 0xDC00));
218 enc->cur += 12; 251 enc->cur += 12;
246 while (--clen); 279 while (--clen);
247 } 280 }
248 else 281 else
249 { 282 {
250 need (enc, len += UTF8_MAXBYTES - 1); // never more than 11 bytes needed 283 need (enc, len += UTF8_MAXBYTES - 1); // never more than 11 bytes needed
251 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); 284 enc->cur = encode_utf8 (enc->cur, uch);
252 ++str; 285 ++str;
253 } 286 }
254 } 287 }
255 } 288 }
256 } 289 }
257 290
258 --len; 291 --len;
259 } 292 }
260} 293}
261 294
262inline void 295INLINE void
263encode_indent (enc_t *enc) 296encode_indent (enc_t *enc)
264{ 297{
265 if (enc->json.flags & F_INDENT) 298 if (enc->json.flags & F_INDENT)
266 { 299 {
267 int spaces = enc->indent * INDENT_STEP; 300 int spaces = enc->indent * INDENT_STEP;
270 memset (enc->cur, ' ', spaces); 303 memset (enc->cur, ' ', spaces);
271 enc->cur += spaces; 304 enc->cur += spaces;
272 } 305 }
273} 306}
274 307
275inline void 308INLINE void
276encode_space (enc_t *enc) 309encode_space (enc_t *enc)
277{ 310{
278 need (enc, 1); 311 need (enc, 1);
279 encode_ch (enc, ' '); 312 encode_ch (enc, ' ');
280} 313}
281 314
282inline void 315INLINE void
283encode_nl (enc_t *enc) 316encode_nl (enc_t *enc)
284{ 317{
285 if (enc->json.flags & F_INDENT) 318 if (enc->json.flags & F_INDENT)
286 { 319 {
287 need (enc, 1); 320 need (enc, 1);
288 encode_ch (enc, '\n'); 321 encode_ch (enc, '\n');
289 } 322 }
290} 323}
291 324
292inline void 325INLINE void
293encode_comma (enc_t *enc) 326encode_comma (enc_t *enc)
294{ 327{
295 encode_ch (enc, ','); 328 encode_ch (enc, ',');
296 329
297 if (enc->json.flags & F_INDENT) 330 if (enc->json.flags & F_INDENT)
308 int i, len = av_len (av); 341 int i, len = av_len (av);
309 342
310 if (enc->indent >= enc->maxdepth) 343 if (enc->indent >= enc->maxdepth)
311 croak ("data structure too deep (hit recursion limit)"); 344 croak ("data structure too deep (hit recursion limit)");
312 345
313 encode_ch (enc, '['); encode_nl (enc); 346 encode_ch (enc, '[');
314 ++enc->indent; 347
348 if (len >= 0)
349 {
350 encode_nl (enc); ++enc->indent;
315 351
316 for (i = 0; i <= len; ++i) 352 for (i = 0; i <= len; ++i)
317 { 353 {
318 SV **svp = av_fetch (av, i, 0); 354 SV **svp = av_fetch (av, i, 0);
319 355
320 encode_indent (enc); 356 encode_indent (enc);
321 357
322 if (svp) 358 if (svp)
323 encode_sv (enc, *svp); 359 encode_sv (enc, *svp);
324 else 360 else
325 encode_str (enc, "null", 4, 0); 361 encode_str (enc, "null", 4, 0);
326 362
327 if (i < len) 363 if (i < len)
328 encode_comma (enc); 364 encode_comma (enc);
329 } 365 }
330 366
367 encode_nl (enc); --enc->indent; encode_indent (enc);
368 }
369
331 encode_nl (enc); 370 encode_ch (enc, ']');
332
333 --enc->indent;
334 encode_indent (enc); encode_ch (enc, ']');
335} 371}
336 372
337static void 373static void
338encode_he (enc_t *enc, HE *he) 374encode_hk (enc_t *enc, HE *he)
339{ 375{
340 encode_ch (enc, '"'); 376 encode_ch (enc, '"');
341 377
342 if (HeKLEN (he) == HEf_SVKEY) 378 if (HeKLEN (he) == HEf_SVKEY)
343 { 379 {
356 encode_ch (enc, '"'); 392 encode_ch (enc, '"');
357 393
358 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc); 394 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc);
359 encode_ch (enc, ':'); 395 encode_ch (enc, ':');
360 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc); 396 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc);
361 encode_sv (enc, HeVAL (he));
362} 397}
363 398
364// compare hash entries, used when all keys are bytestrings 399// compare hash entries, used when all keys are bytestrings
365static int 400static int
366he_cmp_fast (const void *a_, const void *b_) 401he_cmp_fast (const void *a_, const void *b_)
371 HE *b = *(HE **)b_; 406 HE *b = *(HE **)b_;
372 407
373 STRLEN la = HeKLEN (a); 408 STRLEN la = HeKLEN (a);
374 STRLEN lb = HeKLEN (b); 409 STRLEN lb = HeKLEN (b);
375 410
376 if (!(cmp = memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb))) 411 if (!(cmp = memcmp (HeKEY (b), HeKEY (a), lb < la ? lb : la)))
377 cmp = la - lb; 412 cmp = lb - la;
378 413
379 return cmp; 414 return cmp;
380} 415}
381 416
382// compare hash entries, used when some keys are sv's or utf-x 417// compare hash entries, used when some keys are sv's or utf-x
383static int 418static int
384he_cmp_slow (const void *a, const void *b) 419he_cmp_slow (const void *a, const void *b)
385{ 420{
386 return sv_cmp (HeSVKEY_force (*(HE **)a), HeSVKEY_force (*(HE **)b)); 421 return sv_cmp (HeSVKEY_force (*(HE **)b), HeSVKEY_force (*(HE **)a));
387} 422}
388 423
389static void 424static void
390encode_hv (enc_t *enc, HV *hv) 425encode_hv (enc_t *enc, HV *hv)
391{ 426{
427 HE *he;
392 int count, i; 428 int count;
393 429
394 if (enc->indent >= enc->maxdepth) 430 if (enc->indent >= enc->maxdepth)
395 croak ("data structure too deep (hit recursion limit)"); 431 croak ("data structure too deep (hit recursion limit)");
396 432
397 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent; 433 encode_ch (enc, '{');
398 434
399 if ((count = hv_iterinit (hv)))
400 {
401 // for canonical output we have to sort by keys first 435 // for canonical output we have to sort by keys first
402 // actually, this is mostly due to the stupid so-called 436 // actually, this is mostly due to the stupid so-called
403 // security workaround added somewhere in 5.8.x. 437 // security workaround added somewhere in 5.8.x.
404 // that randomises hash orderings 438 // that randomises hash orderings
405 if (enc->json.flags & F_CANONICAL) 439 if (enc->json.flags & F_CANONICAL)
440 {
441 int count = hv_iterinit (hv);
442
443 if (SvMAGICAL (hv))
406 { 444 {
445 // need to count by iterating. could improve by dynamically building the vector below
446 // but I don't care for the speed of this special case.
447 // note also that we will run into undefined behaviour when the two iterations
448 // do not result in the same count, something I might care for in some later release.
449
450 count = 0;
451 while (hv_iternext (hv))
452 ++count;
453
454 hv_iterinit (hv);
455 }
456
457 if (count)
458 {
407 int fast = 1; 459 int i, fast = 1;
408 HE *he;
409#if defined(__BORLANDC__) || defined(_MSC_VER) 460#if defined(__BORLANDC__) || defined(_MSC_VER)
410 HE **hes = _alloca (count * sizeof (HE)); 461 HE **hes = _alloca (count * sizeof (HE));
411#else 462#else
412 HE *hes [count]; // if your compiler dies here, you need to enable C99 mode 463 HE *hes [count]; // if your compiler dies here, you need to enable C99 mode
413#endif 464#endif
440 491
441 FREETMPS; 492 FREETMPS;
442 LEAVE; 493 LEAVE;
443 } 494 }
444 495
445 for (i = 0; i < count; ++i) 496 encode_nl (enc); ++enc->indent;
497
498 while (count--)
446 { 499 {
447 encode_indent (enc); 500 encode_indent (enc);
501 he = hes [count];
448 encode_he (enc, hes [i]); 502 encode_hk (enc, he);
503 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
449 504
450 if (i < count - 1) 505 if (count)
451 encode_comma (enc); 506 encode_comma (enc);
452 } 507 }
453 508
454 encode_nl (enc); 509 encode_nl (enc); --enc->indent; encode_indent (enc);
455 } 510 }
511 }
456 else 512 else
513 {
514 if (hv_iterinit (hv) || SvMAGICAL (hv))
515 if ((he = hv_iternext (hv)))
457 { 516 {
458 HE *he = hv_iternext (hv); 517 encode_nl (enc); ++enc->indent;
459 518
460 for (;;) 519 for (;;)
461 { 520 {
462 encode_indent (enc); 521 encode_indent (enc);
463 encode_he (enc, he); 522 encode_hk (enc, he);
523 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
464 524
465 if (!(he = hv_iternext (hv))) 525 if (!(he = hv_iternext (hv)))
466 break; 526 break;
467 527
468 encode_comma (enc); 528 encode_comma (enc);
469 } 529 }
470 530
471 encode_nl (enc); 531 encode_nl (enc); --enc->indent; encode_indent (enc);
472 } 532 }
473 } 533 }
474 534
475 --enc->indent; encode_indent (enc); encode_ch (enc, '}'); 535 encode_ch (enc, '}');
476} 536}
477 537
478// encode objects, arrays and special \0=false and \1=true values. 538// encode objects, arrays and special \0=false and \1=true values.
479static void 539static void
480encode_rv (enc_t *enc, SV *sv) 540encode_rv (enc_t *enc, SV *sv)
510 // we re-bless the reference to get overload and other niceties right 570 // we re-bless the reference to get overload and other niceties right
511 GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 0); 571 GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 0);
512 572
513 if (to_json) 573 if (to_json)
514 { 574 {
515 int count;
516 dSP; 575 dSP;
517 576
518 ENTER; SAVETMPS; PUSHMARK (SP); 577 ENTER; SAVETMPS; PUSHMARK (SP);
519 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv))); 578 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv)));
520 579
589 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur); 648 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
590 enc->cur += strlen (enc->cur); 649 enc->cur += strlen (enc->cur);
591 } 650 }
592 else if (SvIOKp (sv)) 651 else if (SvIOKp (sv))
593 { 652 {
594 // we assume we can always read an IV as a UV 653 // we assume we can always read an IV as a UV and vice versa
595 if (SvUV (sv) & ~(UV)0x7fff) 654 // we assume two's complement
596 { 655 // we assume no aliasing issues in the union
597 // large integer, use the (rather slow) snprintf way. 656 if (SvIsUV (sv) ? SvUVX (sv) <= 59000
598 need (enc, sizeof (UV) * 3); 657 : SvIVX (sv) <= 59000 && SvIVX (sv) >= -59000)
599 enc->cur +=
600 SvIsUV(sv)
601 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv))
602 : snprintf (enc->cur, sizeof (UV) * 3, "%"IVdf, (IV)SvIVX (sv));
603 }
604 else
605 { 658 {
606 // optimise the "small number case" 659 // optimise the "small number case"
607 // code will likely be branchless and use only a single multiplication 660 // code will likely be branchless and use only a single multiplication
661 // works for numbers up to 59074
608 I32 i = SvIV (sv); 662 I32 i = SvIVX (sv);
609 U32 u; 663 U32 u;
610 char digit, nz = 0; 664 char digit, nz = 0;
611 665
612 need (enc, 6); 666 need (enc, 6);
613 667
619 673
620 // now output digit by digit, each time masking out the integer part 674 // now output digit by digit, each time masking out the integer part
621 // and multiplying by 5 while moving the decimal point one to the right, 675 // and multiplying by 5 while moving the decimal point one to the right,
622 // resulting in a net multiplication by 10. 676 // resulting in a net multiplication by 10.
623 // we always write the digit to memory but conditionally increment 677 // we always write the digit to memory but conditionally increment
624 // the pointer, to ease the usage of conditional move instructions. 678 // the pointer, to enable the use of conditional move instructions.
625 digit = u >> 28; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0xfffffff) * 5; 679 digit = u >> 28; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0xfffffffUL) * 5;
626 digit = u >> 27; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x7ffffff) * 5; 680 digit = u >> 27; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x7ffffffUL) * 5;
627 digit = u >> 26; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x3ffffff) * 5; 681 digit = u >> 26; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x3ffffffUL) * 5;
628 digit = u >> 25; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x1ffffff) * 5; 682 digit = u >> 25; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x1ffffffUL) * 5;
629 digit = u >> 24; *enc->cur = digit + '0'; enc->cur += 1; // correctly generate '0' 683 digit = u >> 24; *enc->cur = digit + '0'; enc->cur += 1; // correctly generate '0'
684 }
685 else
686 {
687 // large integer, use the (rather slow) snprintf way.
688 need (enc, IVUV_MAXCHARS);
689 enc->cur +=
690 SvIsUV(sv)
691 ? snprintf (enc->cur, IVUV_MAXCHARS, "%"UVuf, (UV)SvUVX (sv))
692 : snprintf (enc->cur, IVUV_MAXCHARS, "%"IVdf, (IV)SvIVX (sv));
630 } 693 }
631 } 694 }
632 else if (SvROK (sv)) 695 else if (SvROK (sv))
633 encode_rv (enc, SvRV (sv)); 696 encode_rv (enc, SvRV (sv));
634 else if (!SvOK (sv)) 697 else if (!SvOK (sv))
650 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 713 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
651 enc.cur = SvPVX (enc.sv); 714 enc.cur = SvPVX (enc.sv);
652 enc.end = SvEND (enc.sv); 715 enc.end = SvEND (enc.sv);
653 enc.indent = 0; 716 enc.indent = 0;
654 enc.maxdepth = DEC_DEPTH (enc.json.flags); 717 enc.maxdepth = DEC_DEPTH (enc.json.flags);
718 enc.limit = enc.json.flags & F_ASCII ? 0x000080UL
719 : enc.json.flags & F_LATIN1 ? 0x000100UL
720 : 0x110000UL;
655 721
656 SvPOK_only (enc.sv); 722 SvPOK_only (enc.sv);
657 encode_sv (&enc, scalar); 723 encode_sv (&enc, scalar);
658 724
659 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); 725 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
680 JSON json; 746 JSON json;
681 U32 depth; // recursion depth 747 U32 depth; // recursion depth
682 U32 maxdepth; // recursion depth limit 748 U32 maxdepth; // recursion depth limit
683} dec_t; 749} dec_t;
684 750
685inline void 751INLINE void
752decode_comment (dec_t *dec)
753{
754 // only '#'-style comments allowed a.t.m.
755
756 while (*dec->cur && *dec->cur != 0x0a && *dec->cur != 0x0d)
757 ++dec->cur;
758}
759
760INLINE void
686decode_ws (dec_t *dec) 761decode_ws (dec_t *dec)
687{ 762{
688 for (;;) 763 for (;;)
689 { 764 {
690 char ch = *dec->cur; 765 char ch = *dec->cur;
691 766
692 if (ch > 0x20 767 if (ch > 0x20)
768 {
769 if (expect_false (ch == '#'))
770 {
771 if (dec->json.flags & F_RELAXED)
772 decode_comment (dec);
773 else
774 break;
775 }
776 else
777 break;
778 }
693 || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)) 779 else if (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)
694 break; 780 break; // parse error, but let higher level handle it, gives better error messages
695 781
696 ++dec->cur; 782 ++dec->cur;
697 } 783 }
698} 784}
699 785
805 891
806 if (hi >= 0x80) 892 if (hi >= 0x80)
807 { 893 {
808 utf8 = 1; 894 utf8 = 1;
809 895
810 cur = (char *)uvuni_to_utf8_flags (cur, hi, 0); 896 cur = encode_utf8 (cur, hi);
811 } 897 }
812 else 898 else
813 *cur++ = hi; 899 *cur++ = hi;
814 } 900 }
815 break; 901 break;
817 default: 903 default:
818 --dec_cur; 904 --dec_cur;
819 ERR ("illegal backslash escape sequence in string"); 905 ERR ("illegal backslash escape sequence in string");
820 } 906 }
821 } 907 }
822 else if (expect_true (ch >= 0x20 && ch <= 0x7f)) 908 else if (expect_true (ch >= 0x20 && ch < 0x80))
823 *cur++ = ch; 909 *cur++ = ch;
824 else if (ch >= 0x80) 910 else if (ch >= 0x80)
825 { 911 {
826 STRLEN clen; 912 STRLEN clen;
827 UV uch; 913 UV uch;
950 1036
951 if (!is_nv) 1037 if (!is_nv)
952 { 1038 {
953 int len = dec->cur - start; 1039 int len = dec->cur - start;
954 1040
955 // special case the rather common 1..4-digit-int case, assumes 32 bit ints or so 1041 // special case the rather common 1..5-digit-int case
956 if (*start == '-') 1042 if (*start == '-')
957 switch (len) 1043 switch (len)
958 { 1044 {
959 case 2: return newSViv (-( start [1] - '0' * 1)); 1045 case 2: return newSViv (-( start [1] - '0' * 1));
960 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11)); 1046 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11));
961 case 4: return newSViv (-( start [1] * 100 + start [2] * 10 + start [3] - '0' * 111)); 1047 case 4: return newSViv (-( start [1] * 100 + start [2] * 10 + start [3] - '0' * 111));
962 case 5: return newSViv (-(start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111)); 1048 case 5: return newSViv (-( start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111));
1049 case 6: return newSViv (-(start [1] * 10000 + start [2] * 1000 + start [3] * 100 + start [4] * 10 + start [5] - '0' * 11111));
963 } 1050 }
964 else 1051 else
965 switch (len) 1052 switch (len)
966 { 1053 {
967 case 1: return newSViv ( start [0] - '0' * 1); 1054 case 1: return newSViv ( start [0] - '0' * 1);
968 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11); 1055 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11);
969 case 3: return newSViv ( start [0] * 100 + start [1] * 10 + start [2] - '0' * 111); 1056 case 3: return newSViv ( start [0] * 100 + start [1] * 10 + start [2] - '0' * 111);
970 case 4: return newSViv ( start [0] * 1000 + start [1] * 100 + start [2] * 10 + start [3] - '0' * 1111); 1057 case 4: return newSViv ( start [0] * 1000 + start [1] * 100 + start [2] * 10 + start [3] - '0' * 1111);
1058 case 5: return newSViv ( start [0] * 10000 + start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 11111);
971 } 1059 }
972 1060
973 { 1061 {
974 UV uv; 1062 UV uv;
975 int numtype = grok_number (start, len, &uv); 1063 int numtype = grok_number (start, len, &uv);
1036 1124
1037 if (*dec->cur != ',') 1125 if (*dec->cur != ',')
1038 ERR (", or ] expected while parsing array"); 1126 ERR (", or ] expected while parsing array");
1039 1127
1040 ++dec->cur; 1128 ++dec->cur;
1129
1130 decode_ws (dec);
1131
1132 if (*dec->cur == ']' && dec->json.flags & F_RELAXED)
1133 {
1134 ++dec->cur;
1135 break;
1136 }
1041 } 1137 }
1042 1138
1043 DEC_DEC_DEPTH; 1139 DEC_DEC_DEPTH;
1044 return newRV_noinc ((SV *)av); 1140 return newRV_noinc ((SV *)av);
1045 1141
1061 if (*dec->cur == '}') 1157 if (*dec->cur == '}')
1062 ++dec->cur; 1158 ++dec->cur;
1063 else 1159 else
1064 for (;;) 1160 for (;;)
1065 { 1161 {
1066 decode_ws (dec); EXPECT_CH ('"'); 1162 EXPECT_CH ('"');
1067 1163
1068 // heuristic: assume that 1164 // heuristic: assume that
1069 // a) decode_str + hv_store_ent are abysmally slow. 1165 // a) decode_str + hv_store_ent are abysmally slow.
1070 // b) most hash keys are short, simple ascii text. 1166 // b) most hash keys are short, simple ascii text.
1071 // => try to "fast-match" such strings to avoid 1167 // => try to "fast-match" such strings to avoid
1085 if (!key) 1181 if (!key)
1086 goto fail; 1182 goto fail;
1087 1183
1088 decode_ws (dec); EXPECT_CH (':'); 1184 decode_ws (dec); EXPECT_CH (':');
1089 1185
1186 decode_ws (dec);
1090 value = decode_sv (dec); 1187 value = decode_sv (dec);
1091 if (!value) 1188 if (!value)
1092 { 1189 {
1093 SvREFCNT_dec (key); 1190 SvREFCNT_dec (key);
1094 goto fail; 1191 goto fail;
1106 int len = p - key; 1203 int len = p - key;
1107 dec->cur = p + 1; 1204 dec->cur = p + 1;
1108 1205
1109 decode_ws (dec); EXPECT_CH (':'); 1206 decode_ws (dec); EXPECT_CH (':');
1110 1207
1208 decode_ws (dec);
1111 value = decode_sv (dec); 1209 value = decode_sv (dec);
1112 if (!value) 1210 if (!value)
1113 goto fail; 1211 goto fail;
1114 1212
1115 hv_store (hv, key, len, value, 0); 1213 hv_store (hv, key, len, value, 0);
1131 1229
1132 if (*dec->cur != ',') 1230 if (*dec->cur != ',')
1133 ERR (", or } expected while parsing object/hash"); 1231 ERR (", or } expected while parsing object/hash");
1134 1232
1135 ++dec->cur; 1233 ++dec->cur;
1234
1235 decode_ws (dec);
1236
1237 if (*dec->cur == '}' && dec->json.flags & F_RELAXED)
1238 {
1239 ++dec->cur;
1240 break;
1241 }
1136 } 1242 }
1137 1243
1138 DEC_DEC_DEPTH; 1244 DEC_DEC_DEPTH;
1139 sv = newRV_noinc ((SV *)hv); 1245 sv = newRV_noinc ((SV *)hv);
1140 1246
1205} 1311}
1206 1312
1207static SV * 1313static SV *
1208decode_sv (dec_t *dec) 1314decode_sv (dec_t *dec)
1209{ 1315{
1210 decode_ws (dec);
1211
1212 // the beauty of JSON: you need exactly one character lookahead 1316 // the beauty of JSON: you need exactly one character lookahead
1213 // to parse anything. 1317 // to parse everything.
1214 switch (*dec->cur) 1318 switch (*dec->cur)
1215 { 1319 {
1216 case '"': ++dec->cur; return decode_str (dec); 1320 case '"': ++dec->cur; return decode_str (dec);
1217 case '[': ++dec->cur; return decode_av (dec); 1321 case '[': ++dec->cur; return decode_av (dec);
1218 case '{': ++dec->cur; return decode_hv (dec); 1322 case '{': ++dec->cur; return decode_hv (dec);
1219 1323
1220 case '-': 1324 case '-':
1221 case '0': case '1': case '2': case '3': case '4': 1325 case '0': case '1': case '2': case '3': case '4':
1222 case '5': case '6': case '7': case '8': case '9': 1326 case '5': case '6': case '7': case '8': case '9':
1223 return decode_num (dec); 1327 return decode_num (dec);
1224 1328
1225 case 't': 1329 case 't':
1226 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1330 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
1227 { 1331 {
1228 dec->cur += 4; 1332 dec->cur += 4;
1333#if JSON_SLOW
1334 json_true = get_sv ("JSON::XS::true", 1); SvREADONLY_on (json_true);
1335#endif
1229 return SvREFCNT_inc (json_true); 1336 return SvREFCNT_inc (json_true);
1230 } 1337 }
1231 else 1338 else
1232 ERR ("'true' expected"); 1339 ERR ("'true' expected");
1233 1340
1235 1342
1236 case 'f': 1343 case 'f':
1237 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1344 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
1238 { 1345 {
1239 dec->cur += 5; 1346 dec->cur += 5;
1347#if JSON_SLOW
1348 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1349#endif
1240 return SvREFCNT_inc (json_false); 1350 return SvREFCNT_inc (json_false);
1241 } 1351 }
1242 else 1352 else
1243 ERR ("'false' expected"); 1353 ERR ("'false' expected");
1244 1354
1294 1404
1295 if (dec.json.cb_object || dec.json.cb_sk_object) 1405 if (dec.json.cb_object || dec.json.cb_sk_object)
1296 dec.json.flags |= F_HOOK; 1406 dec.json.flags |= F_HOOK;
1297 1407
1298 *dec.end = 0; // this should basically be a nop, too, but make sure it's there 1408 *dec.end = 0; // this should basically be a nop, too, but make sure it's there
1409
1410 decode_ws (&dec);
1299 sv = decode_sv (&dec); 1411 sv = decode_sv (&dec);
1300 1412
1301 if (!(offset_return || !sv)) 1413 if (!(offset_return || !sv))
1302 { 1414 {
1303 // check for trailing garbage 1415 // check for trailing garbage
1379 json_boolean_stash = 0; 1491 json_boolean_stash = 0;
1380 1492
1381void new (char *klass) 1493void new (char *klass)
1382 PPCODE: 1494 PPCODE:
1383{ 1495{
1384 HV *stash = !JSON_SLOW || json_stash
1385 ? json_stash
1386 : gv_stashpv ("JSON::XS", 1);
1387 SV *pv = NEWSV (0, sizeof (JSON)); 1496 SV *pv = NEWSV (0, sizeof (JSON));
1388 SvPOK_only (pv); 1497 SvPOK_only (pv);
1389 Zero (SvPVX (pv), 1, JSON); 1498 Zero (SvPVX (pv), 1, JSON);
1390 ((JSON *)SvPVX (pv))->flags = F_DEFAULT; 1499 ((JSON *)SvPVX (pv))->flags = F_DEFAULT;
1391 XPUSHs (sv_2mortal (sv_bless (newRV_noinc (pv), stash))); 1500 XPUSHs (sv_2mortal (sv_bless (
1501 newRV_noinc (pv),
1502 strEQ (klass, "JSON::XS") ? JSON_STASH : gv_stashpv (klass, 1)
1503 )));
1392} 1504}
1393 1505
1394void ascii (JSON *self, int enable = 1) 1506void ascii (JSON *self, int enable = 1)
1395 ALIAS: 1507 ALIAS:
1396 ascii = F_ASCII 1508 ascii = F_ASCII
1403 pretty = F_PRETTY 1515 pretty = F_PRETTY
1404 allow_nonref = F_ALLOW_NONREF 1516 allow_nonref = F_ALLOW_NONREF
1405 shrink = F_SHRINK 1517 shrink = F_SHRINK
1406 allow_blessed = F_ALLOW_BLESSED 1518 allow_blessed = F_ALLOW_BLESSED
1407 convert_blessed = F_CONV_BLESSED 1519 convert_blessed = F_CONV_BLESSED
1520 relaxed = F_RELAXED
1408 PPCODE: 1521 PPCODE:
1409{ 1522{
1410 if (enable) 1523 if (enable)
1411 self->flags |= ix; 1524 self->flags |= ix;
1412 else 1525 else
1413 self->flags &= ~ix; 1526 self->flags &= ~ix;
1414 1527
1415 XPUSHs (ST (0)); 1528 XPUSHs (ST (0));
1416} 1529}
1417 1530
1531void get_ascii (JSON *self)
1532 ALIAS:
1533 get_ascii = F_ASCII
1534 get_latin1 = F_LATIN1
1535 get_utf8 = F_UTF8
1536 get_indent = F_INDENT
1537 get_canonical = F_CANONICAL
1538 get_space_before = F_SPACE_BEFORE
1539 get_space_after = F_SPACE_AFTER
1540 get_allow_nonref = F_ALLOW_NONREF
1541 get_shrink = F_SHRINK
1542 get_allow_blessed = F_ALLOW_BLESSED
1543 get_convert_blessed = F_CONV_BLESSED
1544 get_relaxed = F_RELAXED
1545 PPCODE:
1546 XPUSHs (boolSV (self->flags & ix));
1547
1418void max_depth (JSON *self, UV max_depth = 0x80000000UL) 1548void max_depth (JSON *self, UV max_depth = 0x80000000UL)
1419 PPCODE: 1549 PPCODE:
1420{ 1550{
1421 UV log2 = 0; 1551 UV log2 = 0;
1422 1552
1428 self->flags = self->flags & ~F_MAXDEPTH | (log2 << S_MAXDEPTH); 1558 self->flags = self->flags & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1429 1559
1430 XPUSHs (ST (0)); 1560 XPUSHs (ST (0));
1431} 1561}
1432 1562
1563U32 get_max_depth (JSON *self)
1564 CODE:
1565 RETVAL = DEC_DEPTH (self->flags);
1566 OUTPUT:
1567 RETVAL
1568
1433void max_size (JSON *self, UV max_size = 0) 1569void max_size (JSON *self, UV max_size = 0)
1434 PPCODE: 1570 PPCODE:
1435{ 1571{
1436 UV log2 = 0; 1572 UV log2 = 0;
1437 1573
1443 1579
1444 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE); 1580 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE);
1445 1581
1446 XPUSHs (ST (0)); 1582 XPUSHs (ST (0));
1447} 1583}
1584
1585int get_max_size (JSON *self)
1586 CODE:
1587 RETVAL = DEC_SIZE (self->flags);
1588 OUTPUT:
1589 RETVAL
1448 1590
1449void filter_json_object (JSON *self, SV *cb = &PL_sv_undef) 1591void filter_json_object (JSON *self, SV *cb = &PL_sv_undef)
1450 PPCODE: 1592 PPCODE:
1451{ 1593{
1452 SvREFCNT_dec (self->cb_object); 1594 SvREFCNT_dec (self->cb_object);
1499 SvREFCNT_dec (self->cb_sk_object); 1641 SvREFCNT_dec (self->cb_sk_object);
1500 SvREFCNT_dec (self->cb_object); 1642 SvREFCNT_dec (self->cb_object);
1501 1643
1502PROTOTYPES: ENABLE 1644PROTOTYPES: ENABLE
1503 1645
1504void to_json (SV *scalar) 1646void encode_json (SV *scalar)
1505 PPCODE: 1647 PPCODE:
1506{ 1648{
1507 JSON json = { F_DEFAULT | F_UTF8 }; 1649 JSON json = { F_DEFAULT | F_UTF8 };
1508 XPUSHs (encode_json (scalar, &json)); 1650 XPUSHs (encode_json (scalar, &json));
1509} 1651}
1510 1652
1511void from_json (SV *jsonstr) 1653void decode_json (SV *jsonstr)
1512 PPCODE: 1654 PPCODE:
1513{ 1655{
1514 JSON json = { F_DEFAULT | F_UTF8 }; 1656 JSON json = { F_DEFAULT | F_UTF8 };
1515 XPUSHs (decode_json (jsonstr, &json, 0)); 1657 XPUSHs (decode_json (jsonstr, &json, 0));
1516} 1658}

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines