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.55 by root, Mon Jul 23 22:57:40 2007 UTC vs.
Revision 1.74 by root, Wed Mar 19 15:17:53 2008 UTC

1#include "EXTERN.h" 1#include "EXTERN.h"
2#include "perl.h" 2#include "perl.h"
3#include "XSUB.h" 3#include "XSUB.h"
4 4
5#include "assert.h" 5#include <assert.h>
6#include "string.h" 6#include <string.h>
7#include "stdlib.h" 7#include <stdlib.h>
8#include "stdio.h" 8#include <stdio.h>
9#include <float.h>
9 10
10#if defined(__BORLANDC__) || defined(_MSC_VER) 11#if defined(__BORLANDC__) || defined(_MSC_VER)
11# define snprintf _snprintf // C compilers have this in stdio.h 12# define snprintf _snprintf // C compilers have this in stdio.h
12#endif 13#endif
13 14
26#define F_SPACE_AFTER 0x00000040UL 27#define F_SPACE_AFTER 0x00000040UL
27#define F_ALLOW_NONREF 0x00000100UL 28#define F_ALLOW_NONREF 0x00000100UL
28#define F_SHRINK 0x00000200UL 29#define F_SHRINK 0x00000200UL
29#define F_ALLOW_BLESSED 0x00000400UL 30#define F_ALLOW_BLESSED 0x00000400UL
30#define F_CONV_BLESSED 0x00000800UL 31#define F_CONV_BLESSED 0x00000800UL
32#define F_RELAXED 0x00001000UL
33
31#define F_MAXDEPTH 0xf8000000UL 34#define F_MAXDEPTH 0xf8000000UL
32#define S_MAXDEPTH 27 35#define S_MAXDEPTH 27
33#define F_MAXSIZE 0x01f00000UL 36#define F_MAXSIZE 0x01f00000UL
34#define S_MAXSIZE 20 37#define S_MAXSIZE 20
35#define F_HOOK 0x00080000UL // some hooks exist, so slow-path processing 38#define F_HOOK 0x00080000UL // some hooks exist, so slow-path processing
47 50
48#define SB do { 51#define SB do {
49#define SE } while (0) 52#define SE } while (0)
50 53
51#if __GNUC__ >= 3 54#if __GNUC__ >= 3
52# define expect(expr,value) __builtin_expect ((expr),(value)) 55# define expect(expr,value) __builtin_expect ((expr), (value))
53# define inline inline 56# define INLINE static inline
54#else 57#else
55# define expect(expr,value) (expr) 58# define expect(expr,value) (expr)
56# define inline static 59# define INLINE static
57#endif 60#endif
58 61
59#define expect_false(expr) expect ((expr) != 0, 0) 62#define expect_false(expr) expect ((expr) != 0, 0)
60#define expect_true(expr) expect ((expr) != 0, 1) 63#define expect_true(expr) expect ((expr) != 0, 1)
64
65#define IN_RANGE_INC(type,val,beg,end) \
66 ((unsigned type)((unsigned type)(val) - (unsigned type)(beg)) \
67 <= (unsigned type)((unsigned type)(end) - (unsigned type)(beg)))
68
69#ifdef USE_ITHREADS
70# define JSON_SLOW 1
71# define JSON_STASH (json_stash ? json_stash : gv_stashpv ("JSON::XS", 1))
72#else
73# define JSON_SLOW 0
74# define JSON_STASH json_stash
75#endif
61 76
62static HV *json_stash, *json_boolean_stash; // JSON::XS:: 77static HV *json_stash, *json_boolean_stash; // JSON::XS::
63static SV *json_true, *json_false; 78static SV *json_true, *json_false;
64 79
65typedef struct { 80typedef struct {
69} JSON; 84} JSON;
70 85
71///////////////////////////////////////////////////////////////////////////// 86/////////////////////////////////////////////////////////////////////////////
72// utility functions 87// utility functions
73 88
74inline void 89INLINE void
75shrink (SV *sv) 90shrink (SV *sv)
76{ 91{
77 sv_utf8_downgrade (sv, 1); 92 sv_utf8_downgrade (sv, 1);
78 if (SvLEN (sv) > SvCUR (sv) + 1) 93 if (SvLEN (sv) > SvCUR (sv) + 1)
79 { 94 {
88// decode an utf-8 character and return it, or (UV)-1 in 103// decode an utf-8 character and return it, or (UV)-1 in
89// case of an error. 104// case of an error.
90// we special-case "safe" characters from U+80 .. U+7FF, 105// we special-case "safe" characters from U+80 .. U+7FF,
91// but use the very good perl function to parse anything else. 106// but use the very good perl function to parse anything else.
92// note that we never call this function for a ascii codepoints 107// note that we never call this function for a ascii codepoints
93inline UV 108INLINE UV
94decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen) 109decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
95{ 110{
96 if (expect_false (s[0] > 0xdf || s[0] < 0xc2)) 111 if (expect_true (len >= 2
97 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY); 112 && IN_RANGE_INC (char, s[0], 0xc2, 0xdf)
98 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf) 113 && IN_RANGE_INC (char, s[1], 0x80, 0xbf)))
99 { 114 {
100 *clen = 2; 115 *clen = 2;
101 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f); 116 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
102 } 117 }
103 else 118 else
104 { 119 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY);
105 *clen = (STRLEN)-1; 120}
106 return (UV)-1; 121
107 } 122// likewise for encoding, also never called for ascii codepoints
123// this function takes advantage of this fact, although current gccs
124// seem to optimise the check for >= 0x80 away anyways
125INLINE unsigned char *
126encode_utf8 (unsigned char *s, UV ch)
127{
128 if (expect_false (ch < 0x000080))
129 *s++ = ch;
130 else if (expect_true (ch < 0x000800))
131 *s++ = 0xc0 | ( ch >> 6),
132 *s++ = 0x80 | ( ch & 0x3f);
133 else if ( ch < 0x010000)
134 *s++ = 0xe0 | ( ch >> 12),
135 *s++ = 0x80 | ((ch >> 6) & 0x3f),
136 *s++ = 0x80 | ( ch & 0x3f);
137 else if ( ch < 0x110000)
138 *s++ = 0xf0 | ( ch >> 18),
139 *s++ = 0x80 | ((ch >> 12) & 0x3f),
140 *s++ = 0x80 | ((ch >> 6) & 0x3f),
141 *s++ = 0x80 | ( ch & 0x3f);
142
143 return s;
108} 144}
109 145
110///////////////////////////////////////////////////////////////////////////// 146/////////////////////////////////////////////////////////////////////////////
111// encoder 147// encoder
112 148
117 char *end; // SvEND (sv) 153 char *end; // SvEND (sv)
118 SV *sv; // result scalar 154 SV *sv; // result scalar
119 JSON json; 155 JSON json;
120 U32 indent; // indentation level 156 U32 indent; // indentation level
121 U32 maxdepth; // max. indentation/recursion level 157 U32 maxdepth; // max. indentation/recursion level
158 UV limit; // escape character values >= this value when encoding
122} enc_t; 159} enc_t;
123 160
124inline void 161INLINE void
125need (enc_t *enc, STRLEN len) 162need (enc_t *enc, STRLEN len)
126{ 163{
127 if (expect_false (enc->cur + len >= enc->end)) 164 if (expect_false (enc->cur + len >= enc->end))
128 { 165 {
129 STRLEN cur = enc->cur - SvPVX (enc->sv); 166 STRLEN cur = enc->cur - SvPVX (enc->sv);
131 enc->cur = SvPVX (enc->sv) + cur; 168 enc->cur = SvPVX (enc->sv) + cur;
132 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1; 169 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
133 } 170 }
134} 171}
135 172
136inline void 173INLINE void
137encode_ch (enc_t *enc, char ch) 174encode_ch (enc_t *enc, char ch)
138{ 175{
139 need (enc, 1); 176 need (enc, 1);
140 *enc->cur++ = ch; 177 *enc->cur++ = ch;
141} 178}
195 { 232 {
196 uch = ch; 233 uch = ch;
197 clen = 1; 234 clen = 1;
198 } 235 }
199 236
200 if (uch > 0x10FFFFUL) 237 if (uch < 0x80/*0x20*/ || uch >= enc->limit)
201 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
202
203 if (uch < 0x80 || enc->json.flags & F_ASCII || (enc->json.flags & F_LATIN1 && uch > 0xFF))
204 { 238 {
205 if (uch > 0xFFFFUL) 239 if (uch >= 0x10000UL)
206 { 240 {
241 if (uch >= 0x110000UL)
242 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
243
207 need (enc, len += 11); 244 need (enc, len += 11);
208 sprintf (enc->cur, "\\u%04x\\u%04x", 245 sprintf (enc->cur, "\\u%04x\\u%04x",
209 (int)((uch - 0x10000) / 0x400 + 0xD800), 246 (int)((uch - 0x10000) / 0x400 + 0xD800),
210 (int)((uch - 0x10000) % 0x400 + 0xDC00)); 247 (int)((uch - 0x10000) % 0x400 + 0xDC00));
211 enc->cur += 12; 248 enc->cur += 12;
239 while (--clen); 276 while (--clen);
240 } 277 }
241 else 278 else
242 { 279 {
243 need (enc, len += UTF8_MAXBYTES - 1); // never more than 11 bytes needed 280 need (enc, len += UTF8_MAXBYTES - 1); // never more than 11 bytes needed
244 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); 281 enc->cur = encode_utf8 (enc->cur, uch);
245 ++str; 282 ++str;
246 } 283 }
247 } 284 }
248 } 285 }
249 } 286 }
250 287
251 --len; 288 --len;
252 } 289 }
253} 290}
254 291
255inline void 292INLINE void
256encode_indent (enc_t *enc) 293encode_indent (enc_t *enc)
257{ 294{
258 if (enc->json.flags & F_INDENT) 295 if (enc->json.flags & F_INDENT)
259 { 296 {
260 int spaces = enc->indent * INDENT_STEP; 297 int spaces = enc->indent * INDENT_STEP;
263 memset (enc->cur, ' ', spaces); 300 memset (enc->cur, ' ', spaces);
264 enc->cur += spaces; 301 enc->cur += spaces;
265 } 302 }
266} 303}
267 304
268inline void 305INLINE void
269encode_space (enc_t *enc) 306encode_space (enc_t *enc)
270{ 307{
271 need (enc, 1); 308 need (enc, 1);
272 encode_ch (enc, ' '); 309 encode_ch (enc, ' ');
273} 310}
274 311
275inline void 312INLINE void
276encode_nl (enc_t *enc) 313encode_nl (enc_t *enc)
277{ 314{
278 if (enc->json.flags & F_INDENT) 315 if (enc->json.flags & F_INDENT)
279 { 316 {
280 need (enc, 1); 317 need (enc, 1);
281 encode_ch (enc, '\n'); 318 encode_ch (enc, '\n');
282 } 319 }
283} 320}
284 321
285inline void 322INLINE void
286encode_comma (enc_t *enc) 323encode_comma (enc_t *enc)
287{ 324{
288 encode_ch (enc, ','); 325 encode_ch (enc, ',');
289 326
290 if (enc->json.flags & F_INDENT) 327 if (enc->json.flags & F_INDENT)
301 int i, len = av_len (av); 338 int i, len = av_len (av);
302 339
303 if (enc->indent >= enc->maxdepth) 340 if (enc->indent >= enc->maxdepth)
304 croak ("data structure too deep (hit recursion limit)"); 341 croak ("data structure too deep (hit recursion limit)");
305 342
306 encode_ch (enc, '['); encode_nl (enc); 343 encode_ch (enc, '[');
307 ++enc->indent; 344
345 if (len >= 0)
346 {
347 encode_nl (enc); ++enc->indent;
308 348
309 for (i = 0; i <= len; ++i) 349 for (i = 0; i <= len; ++i)
310 { 350 {
311 SV **svp = av_fetch (av, i, 0); 351 SV **svp = av_fetch (av, i, 0);
312 352
313 encode_indent (enc); 353 encode_indent (enc);
314 354
315 if (svp) 355 if (svp)
316 encode_sv (enc, *svp); 356 encode_sv (enc, *svp);
317 else 357 else
318 encode_str (enc, "null", 4, 0); 358 encode_str (enc, "null", 4, 0);
319 359
320 if (i < len) 360 if (i < len)
321 encode_comma (enc); 361 encode_comma (enc);
322 } 362 }
323 363
364 encode_nl (enc); --enc->indent; encode_indent (enc);
365 }
366
324 encode_nl (enc); 367 encode_ch (enc, ']');
325
326 --enc->indent;
327 encode_indent (enc); encode_ch (enc, ']');
328} 368}
329 369
330static void 370static void
331encode_he (enc_t *enc, HE *he) 371encode_hk (enc_t *enc, HE *he)
332{ 372{
333 encode_ch (enc, '"'); 373 encode_ch (enc, '"');
334 374
335 if (HeKLEN (he) == HEf_SVKEY) 375 if (HeKLEN (he) == HEf_SVKEY)
336 { 376 {
349 encode_ch (enc, '"'); 389 encode_ch (enc, '"');
350 390
351 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc); 391 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc);
352 encode_ch (enc, ':'); 392 encode_ch (enc, ':');
353 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc); 393 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc);
354 encode_sv (enc, HeVAL (he));
355} 394}
356 395
357// compare hash entries, used when all keys are bytestrings 396// compare hash entries, used when all keys are bytestrings
358static int 397static int
359he_cmp_fast (const void *a_, const void *b_) 398he_cmp_fast (const void *a_, const void *b_)
364 HE *b = *(HE **)b_; 403 HE *b = *(HE **)b_;
365 404
366 STRLEN la = HeKLEN (a); 405 STRLEN la = HeKLEN (a);
367 STRLEN lb = HeKLEN (b); 406 STRLEN lb = HeKLEN (b);
368 407
369 if (!(cmp = memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb))) 408 if (!(cmp = memcmp (HeKEY (b), HeKEY (a), lb < la ? lb : la)))
370 cmp = la - lb; 409 cmp = lb - la;
371 410
372 return cmp; 411 return cmp;
373} 412}
374 413
375// compare hash entries, used when some keys are sv's or utf-x 414// compare hash entries, used when some keys are sv's or utf-x
376static int 415static int
377he_cmp_slow (const void *a, const void *b) 416he_cmp_slow (const void *a, const void *b)
378{ 417{
379 return sv_cmp (HeSVKEY_force (*(HE **)a), HeSVKEY_force (*(HE **)b)); 418 return sv_cmp (HeSVKEY_force (*(HE **)b), HeSVKEY_force (*(HE **)a));
380} 419}
381 420
382static void 421static void
383encode_hv (enc_t *enc, HV *hv) 422encode_hv (enc_t *enc, HV *hv)
384{ 423{
424 HE *he;
385 int count, i; 425 int count;
386 426
387 if (enc->indent >= enc->maxdepth) 427 if (enc->indent >= enc->maxdepth)
388 croak ("data structure too deep (hit recursion limit)"); 428 croak ("data structure too deep (hit recursion limit)");
389 429
390 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent; 430 encode_ch (enc, '{');
391 431
392 if ((count = hv_iterinit (hv)))
393 {
394 // for canonical output we have to sort by keys first 432 // for canonical output we have to sort by keys first
395 // actually, this is mostly due to the stupid so-called 433 // actually, this is mostly due to the stupid so-called
396 // security workaround added somewhere in 5.8.x. 434 // security workaround added somewhere in 5.8.x.
397 // that randomises hash orderings 435 // that randomises hash orderings
398 if (enc->json.flags & F_CANONICAL) 436 if (enc->json.flags & F_CANONICAL)
437 {
438 int count = hv_iterinit (hv);
439
440 if (SvMAGICAL (hv))
399 { 441 {
442 // need to count by iterating. could improve by dynamically building the vector below
443 // but I don't care for the speed of this special case.
444 // note also that we will run into undefined behaviour when the two iterations
445 // do not result in the same count, something I might care for in some later release.
446
447 count = 0;
448 while (hv_iternext (hv))
449 ++count;
450
451 hv_iterinit (hv);
452 }
453
454 if (count)
455 {
400 int fast = 1; 456 int i, fast = 1;
401 HE *he;
402#if defined(__BORLANDC__) || defined(_MSC_VER) 457#if defined(__BORLANDC__) || defined(_MSC_VER)
403 HE **hes = _alloca (count * sizeof (HE)); 458 HE **hes = _alloca (count * sizeof (HE));
404#else 459#else
405 HE *hes [count]; // if your compiler dies here, you need to enable C99 mode 460 HE *hes [count]; // if your compiler dies here, you need to enable C99 mode
406#endif 461#endif
433 488
434 FREETMPS; 489 FREETMPS;
435 LEAVE; 490 LEAVE;
436 } 491 }
437 492
438 for (i = 0; i < count; ++i) 493 encode_nl (enc); ++enc->indent;
494
495 while (count--)
439 { 496 {
440 encode_indent (enc); 497 encode_indent (enc);
498 he = hes [count];
441 encode_he (enc, hes [i]); 499 encode_hk (enc, he);
500 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
442 501
443 if (i < count - 1) 502 if (count)
444 encode_comma (enc); 503 encode_comma (enc);
445 } 504 }
446 505
447 encode_nl (enc); 506 encode_nl (enc); --enc->indent; encode_indent (enc);
448 } 507 }
508 }
449 else 509 else
510 {
511 if (hv_iterinit (hv) || SvMAGICAL (hv))
512 if ((he = hv_iternext (hv)))
450 { 513 {
451 HE *he = hv_iternext (hv); 514 encode_nl (enc); ++enc->indent;
452 515
453 for (;;) 516 for (;;)
454 { 517 {
455 encode_indent (enc); 518 encode_indent (enc);
456 encode_he (enc, he); 519 encode_hk (enc, he);
520 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
457 521
458 if (!(he = hv_iternext (hv))) 522 if (!(he = hv_iternext (hv)))
459 break; 523 break;
460 524
461 encode_comma (enc); 525 encode_comma (enc);
462 } 526 }
463 527
464 encode_nl (enc); 528 encode_nl (enc); --enc->indent; encode_indent (enc);
465 } 529 }
466 } 530 }
467 531
468 --enc->indent; encode_indent (enc); encode_ch (enc, '}'); 532 encode_ch (enc, '}');
469} 533}
470 534
471// encode objects, arrays and special \0=false and \1=true values. 535// encode objects, arrays and special \0=false and \1=true values.
472static void 536static void
473encode_rv (enc_t *enc, SV *sv) 537encode_rv (enc_t *enc, SV *sv)
477 SvGETMAGIC (sv); 541 SvGETMAGIC (sv);
478 svt = SvTYPE (sv); 542 svt = SvTYPE (sv);
479 543
480 if (expect_false (SvOBJECT (sv))) 544 if (expect_false (SvOBJECT (sv)))
481 { 545 {
546 HV *stash = !JSON_SLOW || json_boolean_stash
547 ? json_boolean_stash
548 : gv_stashpv ("JSON::XS::Boolean", 1);
549
482 if (SvSTASH (sv) == json_boolean_stash) 550 if (SvSTASH (sv) == stash)
483 { 551 {
484 if (SvIV (sv)) 552 if (SvIV (sv))
485 encode_str (enc, "true", 4, 0); 553 encode_str (enc, "true", 4, 0);
486 else 554 else
487 encode_str (enc, "false", 5, 0); 555 encode_str (enc, "false", 5, 0);
499 // we re-bless the reference to get overload and other niceties right 567 // we re-bless the reference to get overload and other niceties right
500 GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 0); 568 GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 0);
501 569
502 if (to_json) 570 if (to_json)
503 { 571 {
504 int count;
505 dSP; 572 dSP;
506 573
507 ENTER; SAVETMPS; PUSHMARK (SP); 574 ENTER; SAVETMPS; PUSHMARK (SP);
508 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv))); 575 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv)));
509 576
578 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur); 645 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
579 enc->cur += strlen (enc->cur); 646 enc->cur += strlen (enc->cur);
580 } 647 }
581 else if (SvIOKp (sv)) 648 else if (SvIOKp (sv))
582 { 649 {
583 // we assume we can always read an IV as a UV 650 // we assume we can always read an IV as a UV and vice versa
584 if (SvUV (sv) & ~(UV)0x7fff) 651 // we assume two's complement
652 // we assume no aliasing issues in the union
653 if (SvIsUV (sv) ? SvUVX (sv) > 59000
654 : SvIVX (sv) > 59000 || SvIVX (sv) < -59000)
585 { 655 {
586 // large integer, use the (rather slow) snprintf way. 656 // large integer, use the (rather slow) snprintf way.
587 need (enc, sizeof (UV) * 3); 657 need (enc, sizeof (UV) * 5 / 2 + 1); // CHAR_BIT is at least 8
588 enc->cur += 658 enc->cur +=
589 SvIsUV(sv) 659 SvIsUV(sv)
590 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv)) 660 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv))
591 : snprintf (enc->cur, sizeof (UV) * 3, "%"IVdf, (IV)SvIVX (sv)); 661 : snprintf (enc->cur, sizeof (UV) * 3, "%"IVdf, (IV)SvIVX (sv));
592 } 662 }
593 else 663 else
594 { 664 {
595 // optimise the "small number case" 665 // optimise the "small number case"
596 // code will likely be branchless and use only a single multiplication 666 // code will likely be branchless and use only a single multiplication
667 // works for numbers up to 59074
597 I32 i = SvIV (sv); 668 I32 i = SvIVX (sv);
598 U32 u; 669 U32 u;
599 char digit, nz = 0; 670 char digit, nz = 0;
600 671
601 need (enc, 6); 672 need (enc, 6);
602 673
639 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 710 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
640 enc.cur = SvPVX (enc.sv); 711 enc.cur = SvPVX (enc.sv);
641 enc.end = SvEND (enc.sv); 712 enc.end = SvEND (enc.sv);
642 enc.indent = 0; 713 enc.indent = 0;
643 enc.maxdepth = DEC_DEPTH (enc.json.flags); 714 enc.maxdepth = DEC_DEPTH (enc.json.flags);
715 enc.limit = enc.json.flags & F_ASCII ? 0x000080UL
716 : enc.json.flags & F_LATIN1 ? 0x000100UL
717 : 0x110000UL;
644 718
645 SvPOK_only (enc.sv); 719 SvPOK_only (enc.sv);
646 encode_sv (&enc, scalar); 720 encode_sv (&enc, scalar);
647 721
648 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); 722 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
669 JSON json; 743 JSON json;
670 U32 depth; // recursion depth 744 U32 depth; // recursion depth
671 U32 maxdepth; // recursion depth limit 745 U32 maxdepth; // recursion depth limit
672} dec_t; 746} dec_t;
673 747
674inline void 748INLINE void
749decode_comment (dec_t *dec)
750{
751 // only '#'-style comments allowed a.t.m.
752
753 while (*dec->cur && *dec->cur != 0x0a && *dec->cur != 0x0d)
754 ++dec->cur;
755}
756
757INLINE void
675decode_ws (dec_t *dec) 758decode_ws (dec_t *dec)
676{ 759{
677 for (;;) 760 for (;;)
678 { 761 {
679 char ch = *dec->cur; 762 char ch = *dec->cur;
680 763
681 if (ch > 0x20 764 if (ch > 0x20)
765 {
766 if (expect_false (ch == '#'))
767 {
768 if (dec->json.flags & F_RELAXED)
769 decode_comment (dec);
770 else
771 break;
772 }
773 else
774 break;
775 }
682 || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)) 776 else if (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)
683 break; 777 break; // parse error, but let higher level handle it, gives better error messages
684 778
685 ++dec->cur; 779 ++dec->cur;
686 } 780 }
687} 781}
688 782
794 888
795 if (hi >= 0x80) 889 if (hi >= 0x80)
796 { 890 {
797 utf8 = 1; 891 utf8 = 1;
798 892
799 cur = (char *)uvuni_to_utf8_flags (cur, hi, 0); 893 cur = encode_utf8 (cur, hi);
800 } 894 }
801 else 895 else
802 *cur++ = hi; 896 *cur++ = hi;
803 } 897 }
804 break; 898 break;
806 default: 900 default:
807 --dec_cur; 901 --dec_cur;
808 ERR ("illegal backslash escape sequence in string"); 902 ERR ("illegal backslash escape sequence in string");
809 } 903 }
810 } 904 }
811 else if (expect_true (ch >= 0x20 && ch <= 0x7f)) 905 else if (expect_true (ch >= 0x20 && ch < 0x80))
812 *cur++ = ch; 906 *cur++ = ch;
813 else if (ch >= 0x80) 907 else if (ch >= 0x80)
814 { 908 {
815 STRLEN clen; 909 STRLEN clen;
816 UV uch; 910 UV uch;
937 is_nv = 1; 1031 is_nv = 1;
938 } 1032 }
939 1033
940 if (!is_nv) 1034 if (!is_nv)
941 { 1035 {
1036 int len = dec->cur - start;
1037
942 // special case the rather common 1..4-digit-int case, assumes 32 bit ints or so 1038 // special case the rather common 1..5-digit-int case
943 if (*start == '-') 1039 if (*start == '-')
944 switch (dec->cur - start) 1040 switch (len)
945 { 1041 {
946 case 2: return newSViv (-( start [1] - '0' * 1)); 1042 case 2: return newSViv (-( start [1] - '0' * 1));
947 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11)); 1043 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11));
948 case 4: return newSViv (-( start [1] * 100 + start [2] * 10 + start [3] - '0' * 111)); 1044 case 4: return newSViv (-( start [1] * 100 + start [2] * 10 + start [3] - '0' * 111));
949 case 5: return newSViv (-(start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111)); 1045 case 5: return newSViv (-( start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111));
1046 case 6: return newSViv (-(start [1] * 10000 + start [2] * 1000 + start [3] * 100 + start [4] * 10 + start [5] - '0' * 11111));
950 } 1047 }
951 else 1048 else
952 switch (dec->cur - start) 1049 switch (len)
953 { 1050 {
954 case 1: return newSViv ( start [0] - '0' * 1); 1051 case 1: return newSViv ( start [0] - '0' * 1);
955 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11); 1052 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11);
956 case 3: return newSViv ( start [0] * 100 + start [1] * 10 + start [2] - '0' * 111); 1053 case 3: return newSViv ( start [0] * 100 + start [1] * 10 + start [2] - '0' * 111);
957 case 4: return newSViv ( start [0] * 1000 + start [1] * 100 + start [2] * 10 + start [3] - '0' * 1111); 1054 case 4: return newSViv ( start [0] * 1000 + start [1] * 100 + start [2] * 10 + start [3] - '0' * 1111);
1055 case 5: return newSViv ( start [0] * 10000 + start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 11111);
958 } 1056 }
959 1057
960 { 1058 {
961 UV uv; 1059 UV uv;
962 int numtype = grok_number (start, dec->cur - start, &uv); 1060 int numtype = grok_number (start, len, &uv);
963 if (numtype & IS_NUMBER_IN_UV) 1061 if (numtype & IS_NUMBER_IN_UV)
964 if (numtype & IS_NUMBER_NEG) 1062 if (numtype & IS_NUMBER_NEG)
965 { 1063 {
966 if (uv < (UV)IV_MIN) 1064 if (uv < (UV)IV_MIN)
967 return newSViv (-(IV)uv); 1065 return newSViv (-(IV)uv);
968 } 1066 }
969 else 1067 else
970 return newSVuv (uv); 1068 return newSVuv (uv);
971
972 // here would likely be the place for bigint support
973 } 1069 }
974 }
975 1070
976 // if we ever support bigint or bigfloat, this is the place for bigfloat 1071 len -= *start == '-' ? 1 : 0;
1072
1073 // does not fit into IV or UV, try NV
1074 if ((sizeof (NV) == sizeof (double) && DBL_DIG >= len)
1075 #if defined (LDBL_DIG)
1076 || (sizeof (NV) == sizeof (long double) && LDBL_DIG >= len)
1077 #endif
1078 )
1079 // fits into NV without loss of precision
1080 return newSVnv (Atof (start));
1081
1082 // everything else fails, convert it to a string
1083 return newSVpvn (start, dec->cur - start);
1084 }
1085
1086 // loss of precision here
977 return newSVnv (Atof (start)); 1087 return newSVnv (Atof (start));
978 1088
979fail: 1089fail:
980 return 0; 1090 return 0;
981} 1091}
1011 1121
1012 if (*dec->cur != ',') 1122 if (*dec->cur != ',')
1013 ERR (", or ] expected while parsing array"); 1123 ERR (", or ] expected while parsing array");
1014 1124
1015 ++dec->cur; 1125 ++dec->cur;
1126
1127 decode_ws (dec);
1128
1129 if (*dec->cur == ']' && dec->json.flags & F_RELAXED)
1130 {
1131 ++dec->cur;
1132 break;
1133 }
1016 } 1134 }
1017 1135
1018 DEC_DEC_DEPTH; 1136 DEC_DEC_DEPTH;
1019 return newRV_noinc ((SV *)av); 1137 return newRV_noinc ((SV *)av);
1020 1138
1036 if (*dec->cur == '}') 1154 if (*dec->cur == '}')
1037 ++dec->cur; 1155 ++dec->cur;
1038 else 1156 else
1039 for (;;) 1157 for (;;)
1040 { 1158 {
1041 decode_ws (dec); EXPECT_CH ('"'); 1159 EXPECT_CH ('"');
1042 1160
1043 // heuristic: assume that 1161 // heuristic: assume that
1044 // a) decode_str + hv_store_ent are abysmally slow. 1162 // a) decode_str + hv_store_ent are abysmally slow.
1045 // b) most hash keys are short, simple ascii text. 1163 // b) most hash keys are short, simple ascii text.
1046 // => try to "fast-match" such strings to avoid 1164 // => try to "fast-match" such strings to avoid
1060 if (!key) 1178 if (!key)
1061 goto fail; 1179 goto fail;
1062 1180
1063 decode_ws (dec); EXPECT_CH (':'); 1181 decode_ws (dec); EXPECT_CH (':');
1064 1182
1183 decode_ws (dec);
1065 value = decode_sv (dec); 1184 value = decode_sv (dec);
1066 if (!value) 1185 if (!value)
1067 { 1186 {
1068 SvREFCNT_dec (key); 1187 SvREFCNT_dec (key);
1069 goto fail; 1188 goto fail;
1081 int len = p - key; 1200 int len = p - key;
1082 dec->cur = p + 1; 1201 dec->cur = p + 1;
1083 1202
1084 decode_ws (dec); EXPECT_CH (':'); 1203 decode_ws (dec); EXPECT_CH (':');
1085 1204
1205 decode_ws (dec);
1086 value = decode_sv (dec); 1206 value = decode_sv (dec);
1087 if (!value) 1207 if (!value)
1088 goto fail; 1208 goto fail;
1089 1209
1090 hv_store (hv, key, len, value, 0); 1210 hv_store (hv, key, len, value, 0);
1106 1226
1107 if (*dec->cur != ',') 1227 if (*dec->cur != ',')
1108 ERR (", or } expected while parsing object/hash"); 1228 ERR (", or } expected while parsing object/hash");
1109 1229
1110 ++dec->cur; 1230 ++dec->cur;
1231
1232 decode_ws (dec);
1233
1234 if (*dec->cur == '}' && dec->json.flags & F_RELAXED)
1235 {
1236 ++dec->cur;
1237 break;
1238 }
1111 } 1239 }
1112 1240
1113 DEC_DEC_DEPTH; 1241 DEC_DEC_DEPTH;
1114 sv = newRV_noinc ((SV *)hv); 1242 sv = newRV_noinc ((SV *)hv);
1115 1243
1180} 1308}
1181 1309
1182static SV * 1310static SV *
1183decode_sv (dec_t *dec) 1311decode_sv (dec_t *dec)
1184{ 1312{
1185 decode_ws (dec);
1186
1187 // the beauty of JSON: you need exactly one character lookahead 1313 // the beauty of JSON: you need exactly one character lookahead
1188 // to parse anything. 1314 // to parse everything.
1189 switch (*dec->cur) 1315 switch (*dec->cur)
1190 { 1316 {
1191 case '"': ++dec->cur; return decode_str (dec); 1317 case '"': ++dec->cur; return decode_str (dec);
1192 case '[': ++dec->cur; return decode_av (dec); 1318 case '[': ++dec->cur; return decode_av (dec);
1193 case '{': ++dec->cur; return decode_hv (dec); 1319 case '{': ++dec->cur; return decode_hv (dec);
1194 1320
1195 case '-': 1321 case '-':
1196 case '0': case '1': case '2': case '3': case '4': 1322 case '0': case '1': case '2': case '3': case '4':
1197 case '5': case '6': case '7': case '8': case '9': 1323 case '5': case '6': case '7': case '8': case '9':
1198 return decode_num (dec); 1324 return decode_num (dec);
1199 1325
1200 case 't': 1326 case 't':
1201 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1327 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
1202 { 1328 {
1203 dec->cur += 4; 1329 dec->cur += 4;
1330#if JSON_SLOW
1331 json_true = get_sv ("JSON::XS::true", 1); SvREADONLY_on (json_true);
1332#endif
1204 return SvREFCNT_inc (json_true); 1333 return SvREFCNT_inc (json_true);
1205 } 1334 }
1206 else 1335 else
1207 ERR ("'true' expected"); 1336 ERR ("'true' expected");
1208 1337
1210 1339
1211 case 'f': 1340 case 'f':
1212 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1341 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
1213 { 1342 {
1214 dec->cur += 5; 1343 dec->cur += 5;
1344#if JSON_SLOW
1345 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1346#endif
1215 return SvREFCNT_inc (json_false); 1347 return SvREFCNT_inc (json_false);
1216 } 1348 }
1217 else 1349 else
1218 ERR ("'false' expected"); 1350 ERR ("'false' expected");
1219 1351
1269 1401
1270 if (dec.json.cb_object || dec.json.cb_sk_object) 1402 if (dec.json.cb_object || dec.json.cb_sk_object)
1271 dec.json.flags |= F_HOOK; 1403 dec.json.flags |= F_HOOK;
1272 1404
1273 *dec.end = 0; // this should basically be a nop, too, but make sure it's there 1405 *dec.end = 0; // this should basically be a nop, too, but make sure it's there
1406
1407 decode_ws (&dec);
1274 sv = decode_sv (&dec); 1408 sv = decode_sv (&dec);
1275 1409
1276 if (!(offset_return || !sv)) 1410 if (!(offset_return || !sv))
1277 { 1411 {
1278 // check for trailing garbage 1412 // check for trailing garbage
1346 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false); 1480 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1347} 1481}
1348 1482
1349PROTOTYPES: DISABLE 1483PROTOTYPES: DISABLE
1350 1484
1485void CLONE (...)
1486 CODE:
1487 json_stash = 0;
1488 json_boolean_stash = 0;
1489
1351void new (char *klass) 1490void new (char *klass)
1352 PPCODE: 1491 PPCODE:
1353{ 1492{
1354 SV *pv = NEWSV (0, sizeof (JSON)); 1493 SV *pv = NEWSV (0, sizeof (JSON));
1355 SvPOK_only (pv); 1494 SvPOK_only (pv);
1356 Zero (SvPVX (pv), 1, JSON); 1495 Zero (SvPVX (pv), 1, JSON);
1357 ((JSON *)SvPVX (pv))->flags = F_DEFAULT; 1496 ((JSON *)SvPVX (pv))->flags = F_DEFAULT;
1358 XPUSHs (sv_2mortal (sv_bless (newRV_noinc (pv), json_stash))); 1497 XPUSHs (sv_2mortal (sv_bless (
1498 newRV_noinc (pv),
1499 strEQ (klass, "JSON::XS") ? JSON_STASH : gv_stashpv (klass, 1)
1500 )));
1359} 1501}
1360 1502
1361void ascii (JSON *self, int enable = 1) 1503void ascii (JSON *self, int enable = 1)
1362 ALIAS: 1504 ALIAS:
1363 ascii = F_ASCII 1505 ascii = F_ASCII
1370 pretty = F_PRETTY 1512 pretty = F_PRETTY
1371 allow_nonref = F_ALLOW_NONREF 1513 allow_nonref = F_ALLOW_NONREF
1372 shrink = F_SHRINK 1514 shrink = F_SHRINK
1373 allow_blessed = F_ALLOW_BLESSED 1515 allow_blessed = F_ALLOW_BLESSED
1374 convert_blessed = F_CONV_BLESSED 1516 convert_blessed = F_CONV_BLESSED
1517 relaxed = F_RELAXED
1375 PPCODE: 1518 PPCODE:
1376{ 1519{
1377 if (enable) 1520 if (enable)
1378 self->flags |= ix; 1521 self->flags |= ix;
1379 else 1522 else
1380 self->flags &= ~ix; 1523 self->flags &= ~ix;
1381 1524
1382 XPUSHs (ST (0)); 1525 XPUSHs (ST (0));
1383} 1526}
1384 1527
1528void get_ascii (JSON *self)
1529 ALIAS:
1530 get_ascii = F_ASCII
1531 get_latin1 = F_LATIN1
1532 get_utf8 = F_UTF8
1533 get_indent = F_INDENT
1534 get_canonical = F_CANONICAL
1535 get_space_before = F_SPACE_BEFORE
1536 get_space_after = F_SPACE_AFTER
1537 get_allow_nonref = F_ALLOW_NONREF
1538 get_shrink = F_SHRINK
1539 get_allow_blessed = F_ALLOW_BLESSED
1540 get_convert_blessed = F_CONV_BLESSED
1541 get_relaxed = F_RELAXED
1542 PPCODE:
1543 XPUSHs (boolSV (self->flags & ix));
1544
1385void max_depth (JSON *self, UV max_depth = 0x80000000UL) 1545void max_depth (JSON *self, UV max_depth = 0x80000000UL)
1386 PPCODE: 1546 PPCODE:
1387{ 1547{
1388 UV log2 = 0; 1548 UV log2 = 0;
1389 1549
1395 self->flags = self->flags & ~F_MAXDEPTH | (log2 << S_MAXDEPTH); 1555 self->flags = self->flags & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1396 1556
1397 XPUSHs (ST (0)); 1557 XPUSHs (ST (0));
1398} 1558}
1399 1559
1560U32 get_max_depth (JSON *self)
1561 CODE:
1562 RETVAL = DEC_DEPTH (self->flags);
1563 OUTPUT:
1564 RETVAL
1565
1400void max_size (JSON *self, UV max_size = 0) 1566void max_size (JSON *self, UV max_size = 0)
1401 PPCODE: 1567 PPCODE:
1402{ 1568{
1403 UV log2 = 0; 1569 UV log2 = 0;
1404 1570
1410 1576
1411 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE); 1577 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE);
1412 1578
1413 XPUSHs (ST (0)); 1579 XPUSHs (ST (0));
1414} 1580}
1581
1582int get_max_size (JSON *self)
1583 CODE:
1584 RETVAL = DEC_SIZE (self->flags);
1585 OUTPUT:
1586 RETVAL
1415 1587
1416void filter_json_object (JSON *self, SV *cb = &PL_sv_undef) 1588void filter_json_object (JSON *self, SV *cb = &PL_sv_undef)
1417 PPCODE: 1589 PPCODE:
1418{ 1590{
1419 SvREFCNT_dec (self->cb_object); 1591 SvREFCNT_dec (self->cb_object);
1466 SvREFCNT_dec (self->cb_sk_object); 1638 SvREFCNT_dec (self->cb_sk_object);
1467 SvREFCNT_dec (self->cb_object); 1639 SvREFCNT_dec (self->cb_object);
1468 1640
1469PROTOTYPES: ENABLE 1641PROTOTYPES: ENABLE
1470 1642
1471void to_json (SV *scalar) 1643void encode_json (SV *scalar)
1472 PPCODE: 1644 PPCODE:
1473{ 1645{
1474 JSON json = { F_DEFAULT | F_UTF8 }; 1646 JSON json = { F_DEFAULT | F_UTF8 };
1475 XPUSHs (encode_json (scalar, &json)); 1647 XPUSHs (encode_json (scalar, &json));
1476} 1648}
1477 1649
1478void from_json (SV *jsonstr) 1650void decode_json (SV *jsonstr)
1479 PPCODE: 1651 PPCODE:
1480{ 1652{
1481 JSON json = { F_DEFAULT | F_UTF8 }; 1653 JSON json = { F_DEFAULT | F_UTF8 };
1482 XPUSHs (decode_json (jsonstr, &json, 0)); 1654 XPUSHs (decode_json (jsonstr, &json, 0));
1483} 1655}

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines