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.53 by root, Tue Jul 10 15:45:34 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 {
351 SV **svp = av_fetch (av, i, 0);
352
311 encode_indent (enc); 353 encode_indent (enc);
312 encode_sv (enc, *av_fetch (av, i, 0));
313 354
355 if (svp)
356 encode_sv (enc, *svp);
357 else
358 encode_str (enc, "null", 4, 0);
359
314 if (i < len) 360 if (i < len)
315 encode_comma (enc); 361 encode_comma (enc);
316 } 362 }
317 363
364 encode_nl (enc); --enc->indent; encode_indent (enc);
365 }
366
318 encode_nl (enc); 367 encode_ch (enc, ']');
319
320 --enc->indent;
321 encode_indent (enc); encode_ch (enc, ']');
322} 368}
323 369
324static void 370static void
325encode_he (enc_t *enc, HE *he) 371encode_hk (enc_t *enc, HE *he)
326{ 372{
327 encode_ch (enc, '"'); 373 encode_ch (enc, '"');
328 374
329 if (HeKLEN (he) == HEf_SVKEY) 375 if (HeKLEN (he) == HEf_SVKEY)
330 { 376 {
343 encode_ch (enc, '"'); 389 encode_ch (enc, '"');
344 390
345 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc); 391 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc);
346 encode_ch (enc, ':'); 392 encode_ch (enc, ':');
347 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc); 393 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc);
348 encode_sv (enc, HeVAL (he));
349} 394}
350 395
351// compare hash entries, used when all keys are bytestrings 396// compare hash entries, used when all keys are bytestrings
352static int 397static int
353he_cmp_fast (const void *a_, const void *b_) 398he_cmp_fast (const void *a_, const void *b_)
358 HE *b = *(HE **)b_; 403 HE *b = *(HE **)b_;
359 404
360 STRLEN la = HeKLEN (a); 405 STRLEN la = HeKLEN (a);
361 STRLEN lb = HeKLEN (b); 406 STRLEN lb = HeKLEN (b);
362 407
363 if (!(cmp = memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb))) 408 if (!(cmp = memcmp (HeKEY (b), HeKEY (a), lb < la ? lb : la)))
364 cmp = la - lb; 409 cmp = lb - la;
365 410
366 return cmp; 411 return cmp;
367} 412}
368 413
369// 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
370static int 415static int
371he_cmp_slow (const void *a, const void *b) 416he_cmp_slow (const void *a, const void *b)
372{ 417{
373 return sv_cmp (HeSVKEY_force (*(HE **)a), HeSVKEY_force (*(HE **)b)); 418 return sv_cmp (HeSVKEY_force (*(HE **)b), HeSVKEY_force (*(HE **)a));
374} 419}
375 420
376static void 421static void
377encode_hv (enc_t *enc, HV *hv) 422encode_hv (enc_t *enc, HV *hv)
378{ 423{
424 HE *he;
379 int count, i; 425 int count;
380 426
381 if (enc->indent >= enc->maxdepth) 427 if (enc->indent >= enc->maxdepth)
382 croak ("data structure too deep (hit recursion limit)"); 428 croak ("data structure too deep (hit recursion limit)");
383 429
384 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent; 430 encode_ch (enc, '{');
385 431
386 if ((count = hv_iterinit (hv)))
387 {
388 // for canonical output we have to sort by keys first 432 // for canonical output we have to sort by keys first
389 // actually, this is mostly due to the stupid so-called 433 // actually, this is mostly due to the stupid so-called
390 // security workaround added somewhere in 5.8.x. 434 // security workaround added somewhere in 5.8.x.
391 // that randomises hash orderings 435 // that randomises hash orderings
392 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))
393 { 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 {
394 int fast = 1; 456 int i, fast = 1;
395 HE *he;
396#if defined(__BORLANDC__) || defined(_MSC_VER) 457#if defined(__BORLANDC__) || defined(_MSC_VER)
397 HE **hes = _alloca (count * sizeof (HE)); 458 HE **hes = _alloca (count * sizeof (HE));
398#else 459#else
399 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
400#endif 461#endif
427 488
428 FREETMPS; 489 FREETMPS;
429 LEAVE; 490 LEAVE;
430 } 491 }
431 492
432 for (i = 0; i < count; ++i) 493 encode_nl (enc); ++enc->indent;
494
495 while (count--)
433 { 496 {
434 encode_indent (enc); 497 encode_indent (enc);
498 he = hes [count];
435 encode_he (enc, hes [i]); 499 encode_hk (enc, he);
500 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
436 501
437 if (i < count - 1) 502 if (count)
438 encode_comma (enc); 503 encode_comma (enc);
439 } 504 }
440 505
441 encode_nl (enc); 506 encode_nl (enc); --enc->indent; encode_indent (enc);
442 } 507 }
508 }
443 else 509 else
510 {
511 if (hv_iterinit (hv) || SvMAGICAL (hv))
512 if ((he = hv_iternext (hv)))
444 { 513 {
445 HE *he = hv_iternext (hv); 514 encode_nl (enc); ++enc->indent;
446 515
447 for (;;) 516 for (;;)
448 { 517 {
449 encode_indent (enc); 518 encode_indent (enc);
450 encode_he (enc, he); 519 encode_hk (enc, he);
520 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
451 521
452 if (!(he = hv_iternext (hv))) 522 if (!(he = hv_iternext (hv)))
453 break; 523 break;
454 524
455 encode_comma (enc); 525 encode_comma (enc);
456 } 526 }
457 527
458 encode_nl (enc); 528 encode_nl (enc); --enc->indent; encode_indent (enc);
459 } 529 }
460 } 530 }
461 531
462 --enc->indent; encode_indent (enc); encode_ch (enc, '}'); 532 encode_ch (enc, '}');
463} 533}
464 534
465// encode objects, arrays and special \0=false and \1=true values. 535// encode objects, arrays and special \0=false and \1=true values.
466static void 536static void
467encode_rv (enc_t *enc, SV *sv) 537encode_rv (enc_t *enc, SV *sv)
471 SvGETMAGIC (sv); 541 SvGETMAGIC (sv);
472 svt = SvTYPE (sv); 542 svt = SvTYPE (sv);
473 543
474 if (expect_false (SvOBJECT (sv))) 544 if (expect_false (SvOBJECT (sv)))
475 { 545 {
546 HV *stash = !JSON_SLOW || json_boolean_stash
547 ? json_boolean_stash
548 : gv_stashpv ("JSON::XS::Boolean", 1);
549
476 if (SvSTASH (sv) == json_boolean_stash) 550 if (SvSTASH (sv) == stash)
477 { 551 {
478 if (SvIV (sv)) 552 if (SvIV (sv))
479 encode_str (enc, "true", 4, 0); 553 encode_str (enc, "true", 4, 0);
480 else 554 else
481 encode_str (enc, "false", 5, 0); 555 encode_str (enc, "false", 5, 0);
499 573
500 ENTER; SAVETMPS; PUSHMARK (SP); 574 ENTER; SAVETMPS; PUSHMARK (SP);
501 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv))); 575 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv)));
502 576
503 // calling with G_SCALAR ensures that we always get a 1 return value 577 // calling with G_SCALAR ensures that we always get a 1 return value
504 // check anyways.
505 PUTBACK; 578 PUTBACK;
506 assert (1 == call_sv ((SV *)GvCV (to_json), G_SCALAR)); 579 call_sv ((SV *)GvCV (to_json), G_SCALAR);
507 SPAGAIN; 580 SPAGAIN;
508 581
509 // catch this surprisingly common error 582 // catch this surprisingly common error
510 if (SvROK (TOPs) && SvRV (TOPs) == sv) 583 if (SvROK (TOPs) && SvRV (TOPs) == sv)
511 croak ("%s::TO_JSON method returned same object as was passed instead of a new one", HvNAME (SvSTASH (sv))); 584 croak ("%s::TO_JSON method returned same object as was passed instead of a new one", HvNAME (SvSTASH (sv)));
572 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur); 645 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
573 enc->cur += strlen (enc->cur); 646 enc->cur += strlen (enc->cur);
574 } 647 }
575 else if (SvIOKp (sv)) 648 else if (SvIOKp (sv))
576 { 649 {
577 // 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
578 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)
579 { 655 {
580 // large integer, use the (rather slow) snprintf way. 656 // large integer, use the (rather slow) snprintf way.
581 need (enc, sizeof (UV) * 3); 657 need (enc, sizeof (UV) * 5 / 2 + 1); // CHAR_BIT is at least 8
582 enc->cur += 658 enc->cur +=
583 SvIsUV(sv) 659 SvIsUV(sv)
584 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv)) 660 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv))
585 : snprintf (enc->cur, sizeof (UV) * 3, "%"IVdf, (IV)SvIVX (sv)); 661 : snprintf (enc->cur, sizeof (UV) * 3, "%"IVdf, (IV)SvIVX (sv));
586 } 662 }
587 else 663 else
588 { 664 {
589 // optimise the "small number case" 665 // optimise the "small number case"
590 // 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
591 I32 i = SvIV (sv); 668 I32 i = SvIVX (sv);
592 U32 u; 669 U32 u;
593 char digit, nz = 0; 670 char digit, nz = 0;
594 671
595 need (enc, 6); 672 need (enc, 6);
596 673
633 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 710 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
634 enc.cur = SvPVX (enc.sv); 711 enc.cur = SvPVX (enc.sv);
635 enc.end = SvEND (enc.sv); 712 enc.end = SvEND (enc.sv);
636 enc.indent = 0; 713 enc.indent = 0;
637 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;
638 718
639 SvPOK_only (enc.sv); 719 SvPOK_only (enc.sv);
640 encode_sv (&enc, scalar); 720 encode_sv (&enc, scalar);
641 721
642 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); 722 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
663 JSON json; 743 JSON json;
664 U32 depth; // recursion depth 744 U32 depth; // recursion depth
665 U32 maxdepth; // recursion depth limit 745 U32 maxdepth; // recursion depth limit
666} dec_t; 746} dec_t;
667 747
668inline 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
669decode_ws (dec_t *dec) 758decode_ws (dec_t *dec)
670{ 759{
671 for (;;) 760 for (;;)
672 { 761 {
673 char ch = *dec->cur; 762 char ch = *dec->cur;
674 763
675 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 }
676 || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)) 776 else if (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)
677 break; 777 break; // parse error, but let higher level handle it, gives better error messages
678 778
679 ++dec->cur; 779 ++dec->cur;
680 } 780 }
681} 781}
682 782
788 888
789 if (hi >= 0x80) 889 if (hi >= 0x80)
790 { 890 {
791 utf8 = 1; 891 utf8 = 1;
792 892
793 cur = (char *)uvuni_to_utf8_flags (cur, hi, 0); 893 cur = encode_utf8 (cur, hi);
794 } 894 }
795 else 895 else
796 *cur++ = hi; 896 *cur++ = hi;
797 } 897 }
798 break; 898 break;
800 default: 900 default:
801 --dec_cur; 901 --dec_cur;
802 ERR ("illegal backslash escape sequence in string"); 902 ERR ("illegal backslash escape sequence in string");
803 } 903 }
804 } 904 }
805 else if (expect_true (ch >= 0x20 && ch <= 0x7f)) 905 else if (expect_true (ch >= 0x20 && ch < 0x80))
806 *cur++ = ch; 906 *cur++ = ch;
807 else if (ch >= 0x80) 907 else if (ch >= 0x80)
808 { 908 {
809 STRLEN clen; 909 STRLEN clen;
810 UV uch; 910 UV uch;
931 is_nv = 1; 1031 is_nv = 1;
932 } 1032 }
933 1033
934 if (!is_nv) 1034 if (!is_nv)
935 { 1035 {
1036 int len = dec->cur - start;
1037
936 // 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
937 if (*start == '-') 1039 if (*start == '-')
938 switch (dec->cur - start) 1040 switch (len)
939 { 1041 {
940 case 2: return newSViv (-( start [1] - '0' * 1)); 1042 case 2: return newSViv (-( start [1] - '0' * 1));
941 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11)); 1043 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11));
942 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));
943 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));
944 } 1047 }
945 else 1048 else
946 switch (dec->cur - start) 1049 switch (len)
947 { 1050 {
948 case 1: return newSViv ( start [0] - '0' * 1); 1051 case 1: return newSViv ( start [0] - '0' * 1);
949 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11); 1052 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11);
950 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);
951 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);
952 } 1056 }
953 1057
954 { 1058 {
955 UV uv; 1059 UV uv;
956 int numtype = grok_number (start, dec->cur - start, &uv); 1060 int numtype = grok_number (start, len, &uv);
957 if (numtype & IS_NUMBER_IN_UV) 1061 if (numtype & IS_NUMBER_IN_UV)
958 if (numtype & IS_NUMBER_NEG) 1062 if (numtype & IS_NUMBER_NEG)
959 { 1063 {
960 if (uv < (UV)IV_MIN) 1064 if (uv < (UV)IV_MIN)
961 return newSViv (-(IV)uv); 1065 return newSViv (-(IV)uv);
962 } 1066 }
963 else 1067 else
964 return newSVuv (uv); 1068 return newSVuv (uv);
965
966 // here would likely be the place for bigint support
967 } 1069 }
968 }
969 1070
970 // 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
971 return newSVnv (Atof (start)); 1087 return newSVnv (Atof (start));
972 1088
973fail: 1089fail:
974 return 0; 1090 return 0;
975} 1091}
1005 1121
1006 if (*dec->cur != ',') 1122 if (*dec->cur != ',')
1007 ERR (", or ] expected while parsing array"); 1123 ERR (", or ] expected while parsing array");
1008 1124
1009 ++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 }
1010 } 1134 }
1011 1135
1012 DEC_DEC_DEPTH; 1136 DEC_DEC_DEPTH;
1013 return newRV_noinc ((SV *)av); 1137 return newRV_noinc ((SV *)av);
1014 1138
1030 if (*dec->cur == '}') 1154 if (*dec->cur == '}')
1031 ++dec->cur; 1155 ++dec->cur;
1032 else 1156 else
1033 for (;;) 1157 for (;;)
1034 { 1158 {
1035 decode_ws (dec); EXPECT_CH ('"'); 1159 EXPECT_CH ('"');
1036 1160
1037 // heuristic: assume that 1161 // heuristic: assume that
1038 // a) decode_str + hv_store_ent are abysmally slow. 1162 // a) decode_str + hv_store_ent are abysmally slow.
1039 // b) most hash keys are short, simple ascii text. 1163 // b) most hash keys are short, simple ascii text.
1040 // => try to "fast-match" such strings to avoid 1164 // => try to "fast-match" such strings to avoid
1054 if (!key) 1178 if (!key)
1055 goto fail; 1179 goto fail;
1056 1180
1057 decode_ws (dec); EXPECT_CH (':'); 1181 decode_ws (dec); EXPECT_CH (':');
1058 1182
1183 decode_ws (dec);
1059 value = decode_sv (dec); 1184 value = decode_sv (dec);
1060 if (!value) 1185 if (!value)
1061 { 1186 {
1062 SvREFCNT_dec (key); 1187 SvREFCNT_dec (key);
1063 goto fail; 1188 goto fail;
1075 int len = p - key; 1200 int len = p - key;
1076 dec->cur = p + 1; 1201 dec->cur = p + 1;
1077 1202
1078 decode_ws (dec); EXPECT_CH (':'); 1203 decode_ws (dec); EXPECT_CH (':');
1079 1204
1205 decode_ws (dec);
1080 value = decode_sv (dec); 1206 value = decode_sv (dec);
1081 if (!value) 1207 if (!value)
1082 goto fail; 1208 goto fail;
1083 1209
1084 hv_store (hv, key, len, value, 0); 1210 hv_store (hv, key, len, value, 0);
1100 1226
1101 if (*dec->cur != ',') 1227 if (*dec->cur != ',')
1102 ERR (", or } expected while parsing object/hash"); 1228 ERR (", or } expected while parsing object/hash");
1103 1229
1104 ++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 }
1105 } 1239 }
1106 1240
1107 DEC_DEC_DEPTH; 1241 DEC_DEC_DEPTH;
1108 sv = newRV_noinc ((SV *)hv); 1242 sv = newRV_noinc ((SV *)hv);
1109 1243
1174} 1308}
1175 1309
1176static SV * 1310static SV *
1177decode_sv (dec_t *dec) 1311decode_sv (dec_t *dec)
1178{ 1312{
1179 decode_ws (dec);
1180
1181 // the beauty of JSON: you need exactly one character lookahead 1313 // the beauty of JSON: you need exactly one character lookahead
1182 // to parse anything. 1314 // to parse everything.
1183 switch (*dec->cur) 1315 switch (*dec->cur)
1184 { 1316 {
1185 case '"': ++dec->cur; return decode_str (dec); 1317 case '"': ++dec->cur; return decode_str (dec);
1186 case '[': ++dec->cur; return decode_av (dec); 1318 case '[': ++dec->cur; return decode_av (dec);
1187 case '{': ++dec->cur; return decode_hv (dec); 1319 case '{': ++dec->cur; return decode_hv (dec);
1188 1320
1189 case '-': 1321 case '-':
1190 case '0': case '1': case '2': case '3': case '4': 1322 case '0': case '1': case '2': case '3': case '4':
1191 case '5': case '6': case '7': case '8': case '9': 1323 case '5': case '6': case '7': case '8': case '9':
1192 return decode_num (dec); 1324 return decode_num (dec);
1193 1325
1194 case 't': 1326 case 't':
1195 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1327 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
1196 { 1328 {
1197 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
1198 return SvREFCNT_inc (json_true); 1333 return SvREFCNT_inc (json_true);
1199 } 1334 }
1200 else 1335 else
1201 ERR ("'true' expected"); 1336 ERR ("'true' expected");
1202 1337
1204 1339
1205 case 'f': 1340 case 'f':
1206 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1341 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
1207 { 1342 {
1208 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
1209 return SvREFCNT_inc (json_false); 1347 return SvREFCNT_inc (json_false);
1210 } 1348 }
1211 else 1349 else
1212 ERR ("'false' expected"); 1350 ERR ("'false' expected");
1213 1351
1263 1401
1264 if (dec.json.cb_object || dec.json.cb_sk_object) 1402 if (dec.json.cb_object || dec.json.cb_sk_object)
1265 dec.json.flags |= F_HOOK; 1403 dec.json.flags |= F_HOOK;
1266 1404
1267 *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);
1268 sv = decode_sv (&dec); 1408 sv = decode_sv (&dec);
1269 1409
1270 if (!(offset_return || !sv)) 1410 if (!(offset_return || !sv))
1271 { 1411 {
1272 // check for trailing garbage 1412 // check for trailing garbage
1340 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);
1341} 1481}
1342 1482
1343PROTOTYPES: DISABLE 1483PROTOTYPES: DISABLE
1344 1484
1485void CLONE (...)
1486 CODE:
1487 json_stash = 0;
1488 json_boolean_stash = 0;
1489
1345void new (char *klass) 1490void new (char *klass)
1346 PPCODE: 1491 PPCODE:
1347{ 1492{
1348 SV *pv = NEWSV (0, sizeof (JSON)); 1493 SV *pv = NEWSV (0, sizeof (JSON));
1349 SvPOK_only (pv); 1494 SvPOK_only (pv);
1350 Zero (SvPVX (pv), 1, JSON); 1495 Zero (SvPVX (pv), 1, JSON);
1351 ((JSON *)SvPVX (pv))->flags = F_DEFAULT; 1496 ((JSON *)SvPVX (pv))->flags = F_DEFAULT;
1352 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 )));
1353} 1501}
1354 1502
1355void ascii (JSON *self, int enable = 1) 1503void ascii (JSON *self, int enable = 1)
1356 ALIAS: 1504 ALIAS:
1357 ascii = F_ASCII 1505 ascii = F_ASCII
1364 pretty = F_PRETTY 1512 pretty = F_PRETTY
1365 allow_nonref = F_ALLOW_NONREF 1513 allow_nonref = F_ALLOW_NONREF
1366 shrink = F_SHRINK 1514 shrink = F_SHRINK
1367 allow_blessed = F_ALLOW_BLESSED 1515 allow_blessed = F_ALLOW_BLESSED
1368 convert_blessed = F_CONV_BLESSED 1516 convert_blessed = F_CONV_BLESSED
1517 relaxed = F_RELAXED
1369 PPCODE: 1518 PPCODE:
1370{ 1519{
1371 if (enable) 1520 if (enable)
1372 self->flags |= ix; 1521 self->flags |= ix;
1373 else 1522 else
1374 self->flags &= ~ix; 1523 self->flags &= ~ix;
1375 1524
1376 XPUSHs (ST (0)); 1525 XPUSHs (ST (0));
1377} 1526}
1378 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
1379void max_depth (JSON *self, UV max_depth = 0x80000000UL) 1545void max_depth (JSON *self, UV max_depth = 0x80000000UL)
1380 PPCODE: 1546 PPCODE:
1381{ 1547{
1382 UV log2 = 0; 1548 UV log2 = 0;
1383 1549
1389 self->flags = self->flags & ~F_MAXDEPTH | (log2 << S_MAXDEPTH); 1555 self->flags = self->flags & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1390 1556
1391 XPUSHs (ST (0)); 1557 XPUSHs (ST (0));
1392} 1558}
1393 1559
1560U32 get_max_depth (JSON *self)
1561 CODE:
1562 RETVAL = DEC_DEPTH (self->flags);
1563 OUTPUT:
1564 RETVAL
1565
1394void max_size (JSON *self, UV max_size = 0) 1566void max_size (JSON *self, UV max_size = 0)
1395 PPCODE: 1567 PPCODE:
1396{ 1568{
1397 UV log2 = 0; 1569 UV log2 = 0;
1398 1570
1404 1576
1405 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE); 1577 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE);
1406 1578
1407 XPUSHs (ST (0)); 1579 XPUSHs (ST (0));
1408} 1580}
1581
1582int get_max_size (JSON *self)
1583 CODE:
1584 RETVAL = DEC_SIZE (self->flags);
1585 OUTPUT:
1586 RETVAL
1409 1587
1410void filter_json_object (JSON *self, SV *cb = &PL_sv_undef) 1588void filter_json_object (JSON *self, SV *cb = &PL_sv_undef)
1411 PPCODE: 1589 PPCODE:
1412{ 1590{
1413 SvREFCNT_dec (self->cb_object); 1591 SvREFCNT_dec (self->cb_object);
1460 SvREFCNT_dec (self->cb_sk_object); 1638 SvREFCNT_dec (self->cb_sk_object);
1461 SvREFCNT_dec (self->cb_object); 1639 SvREFCNT_dec (self->cb_object);
1462 1640
1463PROTOTYPES: ENABLE 1641PROTOTYPES: ENABLE
1464 1642
1465void to_json (SV *scalar) 1643void encode_json (SV *scalar)
1466 PPCODE: 1644 PPCODE:
1467{ 1645{
1468 JSON json = { F_DEFAULT | F_UTF8 }; 1646 JSON json = { F_DEFAULT | F_UTF8 };
1469 XPUSHs (encode_json (scalar, &json)); 1647 XPUSHs (encode_json (scalar, &json));
1470} 1648}
1471 1649
1472void from_json (SV *jsonstr) 1650void decode_json (SV *jsonstr)
1473 PPCODE: 1651 PPCODE:
1474{ 1652{
1475 JSON json = { F_DEFAULT | F_UTF8 }; 1653 JSON json = { F_DEFAULT | F_UTF8 };
1476 XPUSHs (decode_json (jsonstr, &json, 0)); 1654 XPUSHs (decode_json (jsonstr, &json, 0));
1477} 1655}

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines