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.59 by root, Mon Aug 13 16:14:20 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)
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)))
62 71
63#ifdef USE_ITHREADS 72#ifdef USE_ITHREADS
64# define JSON_SLOW 1 73# define JSON_SLOW 1
65# define JSON_STASH (json_stash ? json_stash : gv_stashpv ("JSON::XS", 1)) 74# define JSON_STASH (json_stash ? json_stash : gv_stashpv ("JSON::XS", 1))
66#else 75#else
78} JSON; 87} JSON;
79 88
80///////////////////////////////////////////////////////////////////////////// 89/////////////////////////////////////////////////////////////////////////////
81// utility functions 90// utility functions
82 91
83inline void 92INLINE void
84shrink (SV *sv) 93shrink (SV *sv)
85{ 94{
86 sv_utf8_downgrade (sv, 1); 95 sv_utf8_downgrade (sv, 1);
87 if (SvLEN (sv) > SvCUR (sv) + 1) 96 if (SvLEN (sv) > SvCUR (sv) + 1)
88 { 97 {
97// 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
98// case of an error. 107// case of an error.
99// we special-case "safe" characters from U+80 .. U+7FF, 108// we special-case "safe" characters from U+80 .. U+7FF,
100// but use the very good perl function to parse anything else. 109// but use the very good perl function to parse anything else.
101// note that we never call this function for a ascii codepoints 110// note that we never call this function for a ascii codepoints
102inline UV 111INLINE UV
103decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen) 112decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
104{ 113{
105 if (expect_false (s[0] > 0xdf || s[0] < 0xc2)) 114 if (expect_true (len >= 2
106 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY); 115 && IN_RANGE_INC (char, s[0], 0xc2, 0xdf)
107 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf) 116 && IN_RANGE_INC (char, s[1], 0x80, 0xbf)))
108 { 117 {
109 *clen = 2; 118 *clen = 2;
110 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f); 119 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
111 } 120 }
112 else 121 else
113 { 122 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY);
114 *clen = (STRLEN)-1; 123}
115 return (UV)-1; 124
116 } 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;
117} 147}
118 148
119///////////////////////////////////////////////////////////////////////////// 149/////////////////////////////////////////////////////////////////////////////
120// encoder 150// encoder
121 151
126 char *end; // SvEND (sv) 156 char *end; // SvEND (sv)
127 SV *sv; // result scalar 157 SV *sv; // result scalar
128 JSON json; 158 JSON json;
129 U32 indent; // indentation level 159 U32 indent; // indentation level
130 U32 maxdepth; // max. indentation/recursion level 160 U32 maxdepth; // max. indentation/recursion level
161 UV limit; // escape character values >= this value when encoding
131} enc_t; 162} enc_t;
132 163
133inline void 164INLINE void
134need (enc_t *enc, STRLEN len) 165need (enc_t *enc, STRLEN len)
135{ 166{
136 if (expect_false (enc->cur + len >= enc->end)) 167 if (expect_false (enc->cur + len >= enc->end))
137 { 168 {
138 STRLEN cur = enc->cur - SvPVX (enc->sv); 169 STRLEN cur = enc->cur - SvPVX (enc->sv);
140 enc->cur = SvPVX (enc->sv) + cur; 171 enc->cur = SvPVX (enc->sv) + cur;
141 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1; 172 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
142 } 173 }
143} 174}
144 175
145inline void 176INLINE void
146encode_ch (enc_t *enc, char ch) 177encode_ch (enc_t *enc, char ch)
147{ 178{
148 need (enc, 1); 179 need (enc, 1);
149 *enc->cur++ = ch; 180 *enc->cur++ = ch;
150} 181}
204 { 235 {
205 uch = ch; 236 uch = ch;
206 clen = 1; 237 clen = 1;
207 } 238 }
208 239
209 if (uch > 0x10FFFFUL) 240 if (uch < 0x80/*0x20*/ || uch >= enc->limit)
210 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
211
212 if (uch < 0x80 || enc->json.flags & F_ASCII || (enc->json.flags & F_LATIN1 && uch > 0xFF))
213 { 241 {
214 if (uch > 0xFFFFUL) 242 if (uch >= 0x10000UL)
215 { 243 {
244 if (uch >= 0x110000UL)
245 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
246
216 need (enc, len += 11); 247 need (enc, len += 11);
217 sprintf (enc->cur, "\\u%04x\\u%04x", 248 sprintf (enc->cur, "\\u%04x\\u%04x",
218 (int)((uch - 0x10000) / 0x400 + 0xD800), 249 (int)((uch - 0x10000) / 0x400 + 0xD800),
219 (int)((uch - 0x10000) % 0x400 + 0xDC00)); 250 (int)((uch - 0x10000) % 0x400 + 0xDC00));
220 enc->cur += 12; 251 enc->cur += 12;
248 while (--clen); 279 while (--clen);
249 } 280 }
250 else 281 else
251 { 282 {
252 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
253 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); 284 enc->cur = encode_utf8 (enc->cur, uch);
254 ++str; 285 ++str;
255 } 286 }
256 } 287 }
257 } 288 }
258 } 289 }
259 290
260 --len; 291 --len;
261 } 292 }
262} 293}
263 294
264inline void 295INLINE void
265encode_indent (enc_t *enc) 296encode_indent (enc_t *enc)
266{ 297{
267 if (enc->json.flags & F_INDENT) 298 if (enc->json.flags & F_INDENT)
268 { 299 {
269 int spaces = enc->indent * INDENT_STEP; 300 int spaces = enc->indent * INDENT_STEP;
272 memset (enc->cur, ' ', spaces); 303 memset (enc->cur, ' ', spaces);
273 enc->cur += spaces; 304 enc->cur += spaces;
274 } 305 }
275} 306}
276 307
277inline void 308INLINE void
278encode_space (enc_t *enc) 309encode_space (enc_t *enc)
279{ 310{
280 need (enc, 1); 311 need (enc, 1);
281 encode_ch (enc, ' '); 312 encode_ch (enc, ' ');
282} 313}
283 314
284inline void 315INLINE void
285encode_nl (enc_t *enc) 316encode_nl (enc_t *enc)
286{ 317{
287 if (enc->json.flags & F_INDENT) 318 if (enc->json.flags & F_INDENT)
288 { 319 {
289 need (enc, 1); 320 need (enc, 1);
290 encode_ch (enc, '\n'); 321 encode_ch (enc, '\n');
291 } 322 }
292} 323}
293 324
294inline void 325INLINE void
295encode_comma (enc_t *enc) 326encode_comma (enc_t *enc)
296{ 327{
297 encode_ch (enc, ','); 328 encode_ch (enc, ',');
298 329
299 if (enc->json.flags & F_INDENT) 330 if (enc->json.flags & F_INDENT)
310 int i, len = av_len (av); 341 int i, len = av_len (av);
311 342
312 if (enc->indent >= enc->maxdepth) 343 if (enc->indent >= enc->maxdepth)
313 croak ("data structure too deep (hit recursion limit)"); 344 croak ("data structure too deep (hit recursion limit)");
314 345
315 encode_ch (enc, '['); encode_nl (enc); 346 encode_ch (enc, '[');
316 ++enc->indent; 347
348 if (len >= 0)
349 {
350 encode_nl (enc); ++enc->indent;
317 351
318 for (i = 0; i <= len; ++i) 352 for (i = 0; i <= len; ++i)
319 { 353 {
320 SV **svp = av_fetch (av, i, 0); 354 SV **svp = av_fetch (av, i, 0);
321 355
322 encode_indent (enc); 356 encode_indent (enc);
323 357
324 if (svp) 358 if (svp)
325 encode_sv (enc, *svp); 359 encode_sv (enc, *svp);
326 else 360 else
327 encode_str (enc, "null", 4, 0); 361 encode_str (enc, "null", 4, 0);
328 362
329 if (i < len) 363 if (i < len)
330 encode_comma (enc); 364 encode_comma (enc);
331 } 365 }
332 366
367 encode_nl (enc); --enc->indent; encode_indent (enc);
368 }
369
333 encode_nl (enc); 370 encode_ch (enc, ']');
334
335 --enc->indent;
336 encode_indent (enc); encode_ch (enc, ']');
337} 371}
338 372
339static void 373static void
340encode_he (enc_t *enc, HE *he) 374encode_hk (enc_t *enc, HE *he)
341{ 375{
342 encode_ch (enc, '"'); 376 encode_ch (enc, '"');
343 377
344 if (HeKLEN (he) == HEf_SVKEY) 378 if (HeKLEN (he) == HEf_SVKEY)
345 { 379 {
358 encode_ch (enc, '"'); 392 encode_ch (enc, '"');
359 393
360 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc); 394 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc);
361 encode_ch (enc, ':'); 395 encode_ch (enc, ':');
362 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc); 396 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc);
363 encode_sv (enc, HeVAL (he));
364} 397}
365 398
366// compare hash entries, used when all keys are bytestrings 399// compare hash entries, used when all keys are bytestrings
367static int 400static int
368he_cmp_fast (const void *a_, const void *b_) 401he_cmp_fast (const void *a_, const void *b_)
373 HE *b = *(HE **)b_; 406 HE *b = *(HE **)b_;
374 407
375 STRLEN la = HeKLEN (a); 408 STRLEN la = HeKLEN (a);
376 STRLEN lb = HeKLEN (b); 409 STRLEN lb = HeKLEN (b);
377 410
378 if (!(cmp = memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb))) 411 if (!(cmp = memcmp (HeKEY (b), HeKEY (a), lb < la ? lb : la)))
379 cmp = la - lb; 412 cmp = lb - la;
380 413
381 return cmp; 414 return cmp;
382} 415}
383 416
384// 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
385static int 418static int
386he_cmp_slow (const void *a, const void *b) 419he_cmp_slow (const void *a, const void *b)
387{ 420{
388 return sv_cmp (HeSVKEY_force (*(HE **)a), HeSVKEY_force (*(HE **)b)); 421 return sv_cmp (HeSVKEY_force (*(HE **)b), HeSVKEY_force (*(HE **)a));
389} 422}
390 423
391static void 424static void
392encode_hv (enc_t *enc, HV *hv) 425encode_hv (enc_t *enc, HV *hv)
393{ 426{
427 HE *he;
394 int count, i; 428 int count;
395 429
396 if (enc->indent >= enc->maxdepth) 430 if (enc->indent >= enc->maxdepth)
397 croak ("data structure too deep (hit recursion limit)"); 431 croak ("data structure too deep (hit recursion limit)");
398 432
399 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent; 433 encode_ch (enc, '{');
400 434
401 if ((count = hv_iterinit (hv)))
402 {
403 // for canonical output we have to sort by keys first 435 // for canonical output we have to sort by keys first
404 // actually, this is mostly due to the stupid so-called 436 // actually, this is mostly due to the stupid so-called
405 // security workaround added somewhere in 5.8.x. 437 // security workaround added somewhere in 5.8.x.
406 // that randomises hash orderings 438 // that randomises hash orderings
407 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))
408 { 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 {
409 int fast = 1; 459 int i, fast = 1;
410 HE *he;
411#if defined(__BORLANDC__) || defined(_MSC_VER) 460#if defined(__BORLANDC__) || defined(_MSC_VER)
412 HE **hes = _alloca (count * sizeof (HE)); 461 HE **hes = _alloca (count * sizeof (HE));
413#else 462#else
414 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
415#endif 464#endif
442 491
443 FREETMPS; 492 FREETMPS;
444 LEAVE; 493 LEAVE;
445 } 494 }
446 495
447 for (i = 0; i < count; ++i) 496 encode_nl (enc); ++enc->indent;
497
498 while (count--)
448 { 499 {
449 encode_indent (enc); 500 encode_indent (enc);
501 he = hes [count];
450 encode_he (enc, hes [i]); 502 encode_hk (enc, he);
503 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
451 504
452 if (i < count - 1) 505 if (count)
453 encode_comma (enc); 506 encode_comma (enc);
454 } 507 }
455 508
456 encode_nl (enc); 509 encode_nl (enc); --enc->indent; encode_indent (enc);
457 } 510 }
511 }
458 else 512 else
513 {
514 if (hv_iterinit (hv) || SvMAGICAL (hv))
515 if ((he = hv_iternext (hv)))
459 { 516 {
460 HE *he = hv_iternext (hv); 517 encode_nl (enc); ++enc->indent;
461 518
462 for (;;) 519 for (;;)
463 { 520 {
464 encode_indent (enc); 521 encode_indent (enc);
465 encode_he (enc, he); 522 encode_hk (enc, he);
523 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
466 524
467 if (!(he = hv_iternext (hv))) 525 if (!(he = hv_iternext (hv)))
468 break; 526 break;
469 527
470 encode_comma (enc); 528 encode_comma (enc);
471 } 529 }
472 530
473 encode_nl (enc); 531 encode_nl (enc); --enc->indent; encode_indent (enc);
474 } 532 }
475 } 533 }
476 534
477 --enc->indent; encode_indent (enc); encode_ch (enc, '}'); 535 encode_ch (enc, '}');
478} 536}
479 537
480// encode objects, arrays and special \0=false and \1=true values. 538// encode objects, arrays and special \0=false and \1=true values.
481static void 539static void
482encode_rv (enc_t *enc, SV *sv) 540encode_rv (enc_t *enc, SV *sv)
590 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur); 648 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
591 enc->cur += strlen (enc->cur); 649 enc->cur += strlen (enc->cur);
592 } 650 }
593 else if (SvIOKp (sv)) 651 else if (SvIOKp (sv))
594 { 652 {
595 // 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
596 if (SvUV (sv) & ~(UV)0x7fff) 654 // we assume two's complement
597 { 655 // we assume no aliasing issues in the union
598 // large integer, use the (rather slow) snprintf way. 656 if (SvIsUV (sv) ? SvUVX (sv) <= 59000
599 need (enc, sizeof (UV) * 3); 657 : SvIVX (sv) <= 59000 && SvIVX (sv) >= -59000)
600 enc->cur +=
601 SvIsUV(sv)
602 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv))
603 : snprintf (enc->cur, sizeof (UV) * 3, "%"IVdf, (IV)SvIVX (sv));
604 }
605 else
606 { 658 {
607 // optimise the "small number case" 659 // optimise the "small number case"
608 // 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
609 I32 i = SvIV (sv); 662 I32 i = SvIVX (sv);
610 U32 u; 663 U32 u;
611 char digit, nz = 0; 664 char digit, nz = 0;
612 665
613 need (enc, 6); 666 need (enc, 6);
614 667
620 673
621 // 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
622 // 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,
623 // resulting in a net multiplication by 10. 676 // resulting in a net multiplication by 10.
624 // we always write the digit to memory but conditionally increment 677 // we always write the digit to memory but conditionally increment
625 // the pointer, to ease the usage of conditional move instructions. 678 // the pointer, to enable the use of conditional move instructions.
626 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;
627 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;
628 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;
629 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;
630 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));
631 } 693 }
632 } 694 }
633 else if (SvROK (sv)) 695 else if (SvROK (sv))
634 encode_rv (enc, SvRV (sv)); 696 encode_rv (enc, SvRV (sv));
635 else if (!SvOK (sv)) 697 else if (!SvOK (sv))
651 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 713 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
652 enc.cur = SvPVX (enc.sv); 714 enc.cur = SvPVX (enc.sv);
653 enc.end = SvEND (enc.sv); 715 enc.end = SvEND (enc.sv);
654 enc.indent = 0; 716 enc.indent = 0;
655 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;
656 721
657 SvPOK_only (enc.sv); 722 SvPOK_only (enc.sv);
658 encode_sv (&enc, scalar); 723 encode_sv (&enc, scalar);
659 724
660 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); 725 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
681 JSON json; 746 JSON json;
682 U32 depth; // recursion depth 747 U32 depth; // recursion depth
683 U32 maxdepth; // recursion depth limit 748 U32 maxdepth; // recursion depth limit
684} dec_t; 749} dec_t;
685 750
686inline 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
687decode_ws (dec_t *dec) 761decode_ws (dec_t *dec)
688{ 762{
689 for (;;) 763 for (;;)
690 { 764 {
691 char ch = *dec->cur; 765 char ch = *dec->cur;
692 766
693 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 }
694 || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)) 779 else if (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)
695 break; 780 break; // parse error, but let higher level handle it, gives better error messages
696 781
697 ++dec->cur; 782 ++dec->cur;
698 } 783 }
699} 784}
700 785
806 891
807 if (hi >= 0x80) 892 if (hi >= 0x80)
808 { 893 {
809 utf8 = 1; 894 utf8 = 1;
810 895
811 cur = (char *)uvuni_to_utf8_flags (cur, hi, 0); 896 cur = encode_utf8 (cur, hi);
812 } 897 }
813 else 898 else
814 *cur++ = hi; 899 *cur++ = hi;
815 } 900 }
816 break; 901 break;
818 default: 903 default:
819 --dec_cur; 904 --dec_cur;
820 ERR ("illegal backslash escape sequence in string"); 905 ERR ("illegal backslash escape sequence in string");
821 } 906 }
822 } 907 }
823 else if (expect_true (ch >= 0x20 && ch <= 0x7f)) 908 else if (expect_true (ch >= 0x20 && ch < 0x80))
824 *cur++ = ch; 909 *cur++ = ch;
825 else if (ch >= 0x80) 910 else if (ch >= 0x80)
826 { 911 {
827 STRLEN clen; 912 STRLEN clen;
828 UV uch; 913 UV uch;
951 1036
952 if (!is_nv) 1037 if (!is_nv)
953 { 1038 {
954 int len = dec->cur - start; 1039 int len = dec->cur - start;
955 1040
956 // 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
957 if (*start == '-') 1042 if (*start == '-')
958 switch (len) 1043 switch (len)
959 { 1044 {
960 case 2: return newSViv (-( start [1] - '0' * 1)); 1045 case 2: return newSViv (-( start [1] - '0' * 1));
961 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11)); 1046 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11));
962 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));
963 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));
964 } 1050 }
965 else 1051 else
966 switch (len) 1052 switch (len)
967 { 1053 {
968 case 1: return newSViv ( start [0] - '0' * 1); 1054 case 1: return newSViv ( start [0] - '0' * 1);
969 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11); 1055 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11);
970 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);
971 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);
972 } 1059 }
973 1060
974 { 1061 {
975 UV uv; 1062 UV uv;
976 int numtype = grok_number (start, len, &uv); 1063 int numtype = grok_number (start, len, &uv);
1037 1124
1038 if (*dec->cur != ',') 1125 if (*dec->cur != ',')
1039 ERR (", or ] expected while parsing array"); 1126 ERR (", or ] expected while parsing array");
1040 1127
1041 ++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 }
1042 } 1137 }
1043 1138
1044 DEC_DEC_DEPTH; 1139 DEC_DEC_DEPTH;
1045 return newRV_noinc ((SV *)av); 1140 return newRV_noinc ((SV *)av);
1046 1141
1062 if (*dec->cur == '}') 1157 if (*dec->cur == '}')
1063 ++dec->cur; 1158 ++dec->cur;
1064 else 1159 else
1065 for (;;) 1160 for (;;)
1066 { 1161 {
1067 decode_ws (dec); EXPECT_CH ('"'); 1162 EXPECT_CH ('"');
1068 1163
1069 // heuristic: assume that 1164 // heuristic: assume that
1070 // a) decode_str + hv_store_ent are abysmally slow. 1165 // a) decode_str + hv_store_ent are abysmally slow.
1071 // b) most hash keys are short, simple ascii text. 1166 // b) most hash keys are short, simple ascii text.
1072 // => try to "fast-match" such strings to avoid 1167 // => try to "fast-match" such strings to avoid
1086 if (!key) 1181 if (!key)
1087 goto fail; 1182 goto fail;
1088 1183
1089 decode_ws (dec); EXPECT_CH (':'); 1184 decode_ws (dec); EXPECT_CH (':');
1090 1185
1186 decode_ws (dec);
1091 value = decode_sv (dec); 1187 value = decode_sv (dec);
1092 if (!value) 1188 if (!value)
1093 { 1189 {
1094 SvREFCNT_dec (key); 1190 SvREFCNT_dec (key);
1095 goto fail; 1191 goto fail;
1107 int len = p - key; 1203 int len = p - key;
1108 dec->cur = p + 1; 1204 dec->cur = p + 1;
1109 1205
1110 decode_ws (dec); EXPECT_CH (':'); 1206 decode_ws (dec); EXPECT_CH (':');
1111 1207
1208 decode_ws (dec);
1112 value = decode_sv (dec); 1209 value = decode_sv (dec);
1113 if (!value) 1210 if (!value)
1114 goto fail; 1211 goto fail;
1115 1212
1116 hv_store (hv, key, len, value, 0); 1213 hv_store (hv, key, len, value, 0);
1132 1229
1133 if (*dec->cur != ',') 1230 if (*dec->cur != ',')
1134 ERR (", or } expected while parsing object/hash"); 1231 ERR (", or } expected while parsing object/hash");
1135 1232
1136 ++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 }
1137 } 1242 }
1138 1243
1139 DEC_DEC_DEPTH; 1244 DEC_DEC_DEPTH;
1140 sv = newRV_noinc ((SV *)hv); 1245 sv = newRV_noinc ((SV *)hv);
1141 1246
1206} 1311}
1207 1312
1208static SV * 1313static SV *
1209decode_sv (dec_t *dec) 1314decode_sv (dec_t *dec)
1210{ 1315{
1211 decode_ws (dec);
1212
1213 // the beauty of JSON: you need exactly one character lookahead 1316 // the beauty of JSON: you need exactly one character lookahead
1214 // to parse anything. 1317 // to parse everything.
1215 switch (*dec->cur) 1318 switch (*dec->cur)
1216 { 1319 {
1217 case '"': ++dec->cur; return decode_str (dec); 1320 case '"': ++dec->cur; return decode_str (dec);
1218 case '[': ++dec->cur; return decode_av (dec); 1321 case '[': ++dec->cur; return decode_av (dec);
1219 case '{': ++dec->cur; return decode_hv (dec); 1322 case '{': ++dec->cur; return decode_hv (dec);
1220 1323
1221 case '-': 1324 case '-':
1222 case '0': case '1': case '2': case '3': case '4': 1325 case '0': case '1': case '2': case '3': case '4':
1223 case '5': case '6': case '7': case '8': case '9': 1326 case '5': case '6': case '7': case '8': case '9':
1224 return decode_num (dec); 1327 return decode_num (dec);
1225 1328
1226 case 't': 1329 case 't':
1227 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1330 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
1228 { 1331 {
1229 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
1230 return SvREFCNT_inc (json_true); 1336 return SvREFCNT_inc (json_true);
1231 } 1337 }
1232 else 1338 else
1233 ERR ("'true' expected"); 1339 ERR ("'true' expected");
1234 1340
1236 1342
1237 case 'f': 1343 case 'f':
1238 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1344 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
1239 { 1345 {
1240 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
1241 return SvREFCNT_inc (json_false); 1350 return SvREFCNT_inc (json_false);
1242 } 1351 }
1243 else 1352 else
1244 ERR ("'false' expected"); 1353 ERR ("'false' expected");
1245 1354
1295 1404
1296 if (dec.json.cb_object || dec.json.cb_sk_object) 1405 if (dec.json.cb_object || dec.json.cb_sk_object)
1297 dec.json.flags |= F_HOOK; 1406 dec.json.flags |= F_HOOK;
1298 1407
1299 *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);
1300 sv = decode_sv (&dec); 1411 sv = decode_sv (&dec);
1301 1412
1302 if (!(offset_return || !sv)) 1413 if (!(offset_return || !sv))
1303 { 1414 {
1304 // check for trailing garbage 1415 // check for trailing garbage
1384{ 1495{
1385 SV *pv = NEWSV (0, sizeof (JSON)); 1496 SV *pv = NEWSV (0, sizeof (JSON));
1386 SvPOK_only (pv); 1497 SvPOK_only (pv);
1387 Zero (SvPVX (pv), 1, JSON); 1498 Zero (SvPVX (pv), 1, JSON);
1388 ((JSON *)SvPVX (pv))->flags = F_DEFAULT; 1499 ((JSON *)SvPVX (pv))->flags = F_DEFAULT;
1389 XPUSHs (sv_2mortal (sv_bless (newRV_noinc (pv), JSON_STASH))); 1500 XPUSHs (sv_2mortal (sv_bless (
1501 newRV_noinc (pv),
1502 strEQ (klass, "JSON::XS") ? JSON_STASH : gv_stashpv (klass, 1)
1503 )));
1390} 1504}
1391 1505
1392void ascii (JSON *self, int enable = 1) 1506void ascii (JSON *self, int enable = 1)
1393 ALIAS: 1507 ALIAS:
1394 ascii = F_ASCII 1508 ascii = F_ASCII
1401 pretty = F_PRETTY 1515 pretty = F_PRETTY
1402 allow_nonref = F_ALLOW_NONREF 1516 allow_nonref = F_ALLOW_NONREF
1403 shrink = F_SHRINK 1517 shrink = F_SHRINK
1404 allow_blessed = F_ALLOW_BLESSED 1518 allow_blessed = F_ALLOW_BLESSED
1405 convert_blessed = F_CONV_BLESSED 1519 convert_blessed = F_CONV_BLESSED
1520 relaxed = F_RELAXED
1406 PPCODE: 1521 PPCODE:
1407{ 1522{
1408 if (enable) 1523 if (enable)
1409 self->flags |= ix; 1524 self->flags |= ix;
1410 else 1525 else
1411 self->flags &= ~ix; 1526 self->flags &= ~ix;
1412 1527
1413 XPUSHs (ST (0)); 1528 XPUSHs (ST (0));
1414} 1529}
1415 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
1416void max_depth (JSON *self, UV max_depth = 0x80000000UL) 1548void max_depth (JSON *self, UV max_depth = 0x80000000UL)
1417 PPCODE: 1549 PPCODE:
1418{ 1550{
1419 UV log2 = 0; 1551 UV log2 = 0;
1420 1552
1426 self->flags = self->flags & ~F_MAXDEPTH | (log2 << S_MAXDEPTH); 1558 self->flags = self->flags & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1427 1559
1428 XPUSHs (ST (0)); 1560 XPUSHs (ST (0));
1429} 1561}
1430 1562
1563U32 get_max_depth (JSON *self)
1564 CODE:
1565 RETVAL = DEC_DEPTH (self->flags);
1566 OUTPUT:
1567 RETVAL
1568
1431void max_size (JSON *self, UV max_size = 0) 1569void max_size (JSON *self, UV max_size = 0)
1432 PPCODE: 1570 PPCODE:
1433{ 1571{
1434 UV log2 = 0; 1572 UV log2 = 0;
1435 1573
1441 1579
1442 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE); 1580 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE);
1443 1581
1444 XPUSHs (ST (0)); 1582 XPUSHs (ST (0));
1445} 1583}
1584
1585int get_max_size (JSON *self)
1586 CODE:
1587 RETVAL = DEC_SIZE (self->flags);
1588 OUTPUT:
1589 RETVAL
1446 1590
1447void filter_json_object (JSON *self, SV *cb = &PL_sv_undef) 1591void filter_json_object (JSON *self, SV *cb = &PL_sv_undef)
1448 PPCODE: 1592 PPCODE:
1449{ 1593{
1450 SvREFCNT_dec (self->cb_object); 1594 SvREFCNT_dec (self->cb_object);
1497 SvREFCNT_dec (self->cb_sk_object); 1641 SvREFCNT_dec (self->cb_sk_object);
1498 SvREFCNT_dec (self->cb_object); 1642 SvREFCNT_dec (self->cb_object);
1499 1643
1500PROTOTYPES: ENABLE 1644PROTOTYPES: ENABLE
1501 1645
1502void to_json (SV *scalar) 1646void encode_json (SV *scalar)
1503 PPCODE: 1647 PPCODE:
1504{ 1648{
1505 JSON json = { F_DEFAULT | F_UTF8 }; 1649 JSON json = { F_DEFAULT | F_UTF8 };
1506 XPUSHs (encode_json (scalar, &json)); 1650 XPUSHs (encode_json (scalar, &json));
1507} 1651}
1508 1652
1509void from_json (SV *jsonstr) 1653void decode_json (SV *jsonstr)
1510 PPCODE: 1654 PPCODE:
1511{ 1655{
1512 JSON json = { F_DEFAULT | F_UTF8 }; 1656 JSON json = { F_DEFAULT | F_UTF8 };
1513 XPUSHs (decode_json (jsonstr, &json, 0)); 1657 XPUSHs (decode_json (jsonstr, &json, 0));
1514} 1658}

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines