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.58 by root, Mon Aug 13 16:06:25 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 0 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)
588 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur); 648 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
589 enc->cur += strlen (enc->cur); 649 enc->cur += strlen (enc->cur);
590 } 650 }
591 else if (SvIOKp (sv)) 651 else if (SvIOKp (sv))
592 { 652 {
593 // 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
594 if (SvUV (sv) & ~(UV)0x7fff) 654 // we assume two's complement
595 { 655 // we assume no aliasing issues in the union
596 // large integer, use the (rather slow) snprintf way. 656 if (SvIsUV (sv) ? SvUVX (sv) <= 59000
597 need (enc, sizeof (UV) * 3); 657 : SvIVX (sv) <= 59000 && SvIVX (sv) >= -59000)
598 enc->cur +=
599 SvIsUV(sv)
600 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv))
601 : snprintf (enc->cur, sizeof (UV) * 3, "%"IVdf, (IV)SvIVX (sv));
602 }
603 else
604 { 658 {
605 // optimise the "small number case" 659 // optimise the "small number case"
606 // 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
607 I32 i = SvIV (sv); 662 I32 i = SvIVX (sv);
608 U32 u; 663 U32 u;
609 char digit, nz = 0; 664 char digit, nz = 0;
610 665
611 need (enc, 6); 666 need (enc, 6);
612 667
618 673
619 // 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
620 // 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,
621 // resulting in a net multiplication by 10. 676 // resulting in a net multiplication by 10.
622 // we always write the digit to memory but conditionally increment 677 // we always write the digit to memory but conditionally increment
623 // the pointer, to ease the usage of conditional move instructions. 678 // the pointer, to enable the use of conditional move instructions.
624 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;
625 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;
626 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;
627 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;
628 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));
629 } 693 }
630 } 694 }
631 else if (SvROK (sv)) 695 else if (SvROK (sv))
632 encode_rv (enc, SvRV (sv)); 696 encode_rv (enc, SvRV (sv));
633 else if (!SvOK (sv)) 697 else if (!SvOK (sv))
649 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 713 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
650 enc.cur = SvPVX (enc.sv); 714 enc.cur = SvPVX (enc.sv);
651 enc.end = SvEND (enc.sv); 715 enc.end = SvEND (enc.sv);
652 enc.indent = 0; 716 enc.indent = 0;
653 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;
654 721
655 SvPOK_only (enc.sv); 722 SvPOK_only (enc.sv);
656 encode_sv (&enc, scalar); 723 encode_sv (&enc, scalar);
657 724
658 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); 725 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
679 JSON json; 746 JSON json;
680 U32 depth; // recursion depth 747 U32 depth; // recursion depth
681 U32 maxdepth; // recursion depth limit 748 U32 maxdepth; // recursion depth limit
682} dec_t; 749} dec_t;
683 750
684inline 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
685decode_ws (dec_t *dec) 761decode_ws (dec_t *dec)
686{ 762{
687 for (;;) 763 for (;;)
688 { 764 {
689 char ch = *dec->cur; 765 char ch = *dec->cur;
690 766
691 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 }
692 || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)) 779 else if (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)
693 break; 780 break; // parse error, but let higher level handle it, gives better error messages
694 781
695 ++dec->cur; 782 ++dec->cur;
696 } 783 }
697} 784}
698 785
804 891
805 if (hi >= 0x80) 892 if (hi >= 0x80)
806 { 893 {
807 utf8 = 1; 894 utf8 = 1;
808 895
809 cur = (char *)uvuni_to_utf8_flags (cur, hi, 0); 896 cur = encode_utf8 (cur, hi);
810 } 897 }
811 else 898 else
812 *cur++ = hi; 899 *cur++ = hi;
813 } 900 }
814 break; 901 break;
816 default: 903 default:
817 --dec_cur; 904 --dec_cur;
818 ERR ("illegal backslash escape sequence in string"); 905 ERR ("illegal backslash escape sequence in string");
819 } 906 }
820 } 907 }
821 else if (expect_true (ch >= 0x20 && ch <= 0x7f)) 908 else if (expect_true (ch >= 0x20 && ch < 0x80))
822 *cur++ = ch; 909 *cur++ = ch;
823 else if (ch >= 0x80) 910 else if (ch >= 0x80)
824 { 911 {
825 STRLEN clen; 912 STRLEN clen;
826 UV uch; 913 UV uch;
949 1036
950 if (!is_nv) 1037 if (!is_nv)
951 { 1038 {
952 int len = dec->cur - start; 1039 int len = dec->cur - start;
953 1040
954 // 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
955 if (*start == '-') 1042 if (*start == '-')
956 switch (len) 1043 switch (len)
957 { 1044 {
958 case 2: return newSViv (-( start [1] - '0' * 1)); 1045 case 2: return newSViv (-( start [1] - '0' * 1));
959 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11)); 1046 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11));
960 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));
961 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));
962 } 1050 }
963 else 1051 else
964 switch (len) 1052 switch (len)
965 { 1053 {
966 case 1: return newSViv ( start [0] - '0' * 1); 1054 case 1: return newSViv ( start [0] - '0' * 1);
967 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11); 1055 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11);
968 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);
969 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);
970 } 1059 }
971 1060
972 { 1061 {
973 UV uv; 1062 UV uv;
974 int numtype = grok_number (start, len, &uv); 1063 int numtype = grok_number (start, len, &uv);
1035 1124
1036 if (*dec->cur != ',') 1125 if (*dec->cur != ',')
1037 ERR (", or ] expected while parsing array"); 1126 ERR (", or ] expected while parsing array");
1038 1127
1039 ++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 }
1040 } 1137 }
1041 1138
1042 DEC_DEC_DEPTH; 1139 DEC_DEC_DEPTH;
1043 return newRV_noinc ((SV *)av); 1140 return newRV_noinc ((SV *)av);
1044 1141
1060 if (*dec->cur == '}') 1157 if (*dec->cur == '}')
1061 ++dec->cur; 1158 ++dec->cur;
1062 else 1159 else
1063 for (;;) 1160 for (;;)
1064 { 1161 {
1065 decode_ws (dec); EXPECT_CH ('"'); 1162 EXPECT_CH ('"');
1066 1163
1067 // heuristic: assume that 1164 // heuristic: assume that
1068 // a) decode_str + hv_store_ent are abysmally slow. 1165 // a) decode_str + hv_store_ent are abysmally slow.
1069 // b) most hash keys are short, simple ascii text. 1166 // b) most hash keys are short, simple ascii text.
1070 // => try to "fast-match" such strings to avoid 1167 // => try to "fast-match" such strings to avoid
1084 if (!key) 1181 if (!key)
1085 goto fail; 1182 goto fail;
1086 1183
1087 decode_ws (dec); EXPECT_CH (':'); 1184 decode_ws (dec); EXPECT_CH (':');
1088 1185
1186 decode_ws (dec);
1089 value = decode_sv (dec); 1187 value = decode_sv (dec);
1090 if (!value) 1188 if (!value)
1091 { 1189 {
1092 SvREFCNT_dec (key); 1190 SvREFCNT_dec (key);
1093 goto fail; 1191 goto fail;
1105 int len = p - key; 1203 int len = p - key;
1106 dec->cur = p + 1; 1204 dec->cur = p + 1;
1107 1205
1108 decode_ws (dec); EXPECT_CH (':'); 1206 decode_ws (dec); EXPECT_CH (':');
1109 1207
1208 decode_ws (dec);
1110 value = decode_sv (dec); 1209 value = decode_sv (dec);
1111 if (!value) 1210 if (!value)
1112 goto fail; 1211 goto fail;
1113 1212
1114 hv_store (hv, key, len, value, 0); 1213 hv_store (hv, key, len, value, 0);
1130 1229
1131 if (*dec->cur != ',') 1230 if (*dec->cur != ',')
1132 ERR (", or } expected while parsing object/hash"); 1231 ERR (", or } expected while parsing object/hash");
1133 1232
1134 ++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 }
1135 } 1242 }
1136 1243
1137 DEC_DEC_DEPTH; 1244 DEC_DEC_DEPTH;
1138 sv = newRV_noinc ((SV *)hv); 1245 sv = newRV_noinc ((SV *)hv);
1139 1246
1204} 1311}
1205 1312
1206static SV * 1313static SV *
1207decode_sv (dec_t *dec) 1314decode_sv (dec_t *dec)
1208{ 1315{
1209 decode_ws (dec);
1210
1211 // the beauty of JSON: you need exactly one character lookahead 1316 // the beauty of JSON: you need exactly one character lookahead
1212 // to parse anything. 1317 // to parse everything.
1213 switch (*dec->cur) 1318 switch (*dec->cur)
1214 { 1319 {
1215 case '"': ++dec->cur; return decode_str (dec); 1320 case '"': ++dec->cur; return decode_str (dec);
1216 case '[': ++dec->cur; return decode_av (dec); 1321 case '[': ++dec->cur; return decode_av (dec);
1217 case '{': ++dec->cur; return decode_hv (dec); 1322 case '{': ++dec->cur; return decode_hv (dec);
1218 1323
1219 case '-': 1324 case '-':
1220 case '0': case '1': case '2': case '3': case '4': 1325 case '0': case '1': case '2': case '3': case '4':
1221 case '5': case '6': case '7': case '8': case '9': 1326 case '5': case '6': case '7': case '8': case '9':
1222 return decode_num (dec); 1327 return decode_num (dec);
1223 1328
1224 case 't': 1329 case 't':
1225 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1330 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
1226 { 1331 {
1227 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
1228 return SvREFCNT_inc (json_true); 1336 return SvREFCNT_inc (json_true);
1229 } 1337 }
1230 else 1338 else
1231 ERR ("'true' expected"); 1339 ERR ("'true' expected");
1232 1340
1234 1342
1235 case 'f': 1343 case 'f':
1236 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1344 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
1237 { 1345 {
1238 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
1239 return SvREFCNT_inc (json_false); 1350 return SvREFCNT_inc (json_false);
1240 } 1351 }
1241 else 1352 else
1242 ERR ("'false' expected"); 1353 ERR ("'false' expected");
1243 1354
1293 1404
1294 if (dec.json.cb_object || dec.json.cb_sk_object) 1405 if (dec.json.cb_object || dec.json.cb_sk_object)
1295 dec.json.flags |= F_HOOK; 1406 dec.json.flags |= F_HOOK;
1296 1407
1297 *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);
1298 sv = decode_sv (&dec); 1411 sv = decode_sv (&dec);
1299 1412
1300 if (!(offset_return || !sv)) 1413 if (!(offset_return || !sv))
1301 { 1414 {
1302 // check for trailing garbage 1415 // check for trailing garbage
1378 json_boolean_stash = 0; 1491 json_boolean_stash = 0;
1379 1492
1380void new (char *klass) 1493void new (char *klass)
1381 PPCODE: 1494 PPCODE:
1382{ 1495{
1383 HV *stash = !JSON_SLOW || json_stash
1384 ? json_stash
1385 : gv_stashpv ("JSON::XS", 1);
1386 SV *pv = NEWSV (0, sizeof (JSON)); 1496 SV *pv = NEWSV (0, sizeof (JSON));
1387 SvPOK_only (pv); 1497 SvPOK_only (pv);
1388 Zero (SvPVX (pv), 1, JSON); 1498 Zero (SvPVX (pv), 1, JSON);
1389 ((JSON *)SvPVX (pv))->flags = F_DEFAULT; 1499 ((JSON *)SvPVX (pv))->flags = F_DEFAULT;
1390 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 )));
1391} 1504}
1392 1505
1393void ascii (JSON *self, int enable = 1) 1506void ascii (JSON *self, int enable = 1)
1394 ALIAS: 1507 ALIAS:
1395 ascii = F_ASCII 1508 ascii = F_ASCII
1402 pretty = F_PRETTY 1515 pretty = F_PRETTY
1403 allow_nonref = F_ALLOW_NONREF 1516 allow_nonref = F_ALLOW_NONREF
1404 shrink = F_SHRINK 1517 shrink = F_SHRINK
1405 allow_blessed = F_ALLOW_BLESSED 1518 allow_blessed = F_ALLOW_BLESSED
1406 convert_blessed = F_CONV_BLESSED 1519 convert_blessed = F_CONV_BLESSED
1520 relaxed = F_RELAXED
1407 PPCODE: 1521 PPCODE:
1408{ 1522{
1409 if (enable) 1523 if (enable)
1410 self->flags |= ix; 1524 self->flags |= ix;
1411 else 1525 else
1412 self->flags &= ~ix; 1526 self->flags &= ~ix;
1413 1527
1414 XPUSHs (ST (0)); 1528 XPUSHs (ST (0));
1415} 1529}
1416 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
1417void max_depth (JSON *self, UV max_depth = 0x80000000UL) 1548void max_depth (JSON *self, UV max_depth = 0x80000000UL)
1418 PPCODE: 1549 PPCODE:
1419{ 1550{
1420 UV log2 = 0; 1551 UV log2 = 0;
1421 1552
1427 self->flags = self->flags & ~F_MAXDEPTH | (log2 << S_MAXDEPTH); 1558 self->flags = self->flags & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1428 1559
1429 XPUSHs (ST (0)); 1560 XPUSHs (ST (0));
1430} 1561}
1431 1562
1563U32 get_max_depth (JSON *self)
1564 CODE:
1565 RETVAL = DEC_DEPTH (self->flags);
1566 OUTPUT:
1567 RETVAL
1568
1432void max_size (JSON *self, UV max_size = 0) 1569void max_size (JSON *self, UV max_size = 0)
1433 PPCODE: 1570 PPCODE:
1434{ 1571{
1435 UV log2 = 0; 1572 UV log2 = 0;
1436 1573
1442 1579
1443 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE); 1580 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE);
1444 1581
1445 XPUSHs (ST (0)); 1582 XPUSHs (ST (0));
1446} 1583}
1584
1585int get_max_size (JSON *self)
1586 CODE:
1587 RETVAL = DEC_SIZE (self->flags);
1588 OUTPUT:
1589 RETVAL
1447 1590
1448void filter_json_object (JSON *self, SV *cb = &PL_sv_undef) 1591void filter_json_object (JSON *self, SV *cb = &PL_sv_undef)
1449 PPCODE: 1592 PPCODE:
1450{ 1593{
1451 SvREFCNT_dec (self->cb_object); 1594 SvREFCNT_dec (self->cb_object);
1498 SvREFCNT_dec (self->cb_sk_object); 1641 SvREFCNT_dec (self->cb_sk_object);
1499 SvREFCNT_dec (self->cb_object); 1642 SvREFCNT_dec (self->cb_object);
1500 1643
1501PROTOTYPES: ENABLE 1644PROTOTYPES: ENABLE
1502 1645
1503void to_json (SV *scalar) 1646void encode_json (SV *scalar)
1504 PPCODE: 1647 PPCODE:
1505{ 1648{
1506 JSON json = { F_DEFAULT | F_UTF8 }; 1649 JSON json = { F_DEFAULT | F_UTF8 };
1507 XPUSHs (encode_json (scalar, &json)); 1650 XPUSHs (encode_json (scalar, &json));
1508} 1651}
1509 1652
1510void from_json (SV *jsonstr) 1653void decode_json (SV *jsonstr)
1511 PPCODE: 1654 PPCODE:
1512{ 1655{
1513 JSON json = { F_DEFAULT | F_UTF8 }; 1656 JSON json = { F_DEFAULT | F_UTF8 };
1514 XPUSHs (decode_json (jsonstr, &json, 0)); 1657 XPUSHs (decode_json (jsonstr, &json, 0));
1515} 1658}

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines