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.76 by root, Thu Mar 20 00:56:37 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 <limits.h>
10#include <float.h>
9 11
10#if defined(__BORLANDC__) || defined(_MSC_VER) 12#if defined(__BORLANDC__) || defined(_MSC_VER)
11# define snprintf _snprintf // C compilers have this in stdio.h 13# define snprintf _snprintf // C compilers have this in stdio.h
12#endif 14#endif
13 15
14// 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
15// guarentees, though. if it breaks, you get to keep the pieces. 17// guarentees, though. if it breaks, you get to keep the pieces.
16#ifndef UTF8_MAXBYTES 18#ifndef UTF8_MAXBYTES
17# define UTF8_MAXBYTES 13 19# define UTF8_MAXBYTES 13
18#endif 20#endif
21
22#define IVUV_MAXCHARS (sizeof (UV) * CHAR_BIT * 28 / 93 + 2)
19 23
20#define F_ASCII 0x00000001UL 24#define F_ASCII 0x00000001UL
21#define F_LATIN1 0x00000002UL 25#define F_LATIN1 0x00000002UL
22#define F_UTF8 0x00000004UL 26#define F_UTF8 0x00000004UL
23#define F_INDENT 0x00000008UL 27#define F_INDENT 0x00000008UL
26#define F_SPACE_AFTER 0x00000040UL 30#define F_SPACE_AFTER 0x00000040UL
27#define F_ALLOW_NONREF 0x00000100UL 31#define F_ALLOW_NONREF 0x00000100UL
28#define F_SHRINK 0x00000200UL 32#define F_SHRINK 0x00000200UL
29#define F_ALLOW_BLESSED 0x00000400UL 33#define F_ALLOW_BLESSED 0x00000400UL
30#define F_CONV_BLESSED 0x00000800UL 34#define F_CONV_BLESSED 0x00000800UL
35#define F_RELAXED 0x00001000UL
36
31#define F_MAXDEPTH 0xf8000000UL 37#define F_MAXDEPTH 0xf8000000UL
32#define S_MAXDEPTH 27 38#define S_MAXDEPTH 27
33#define F_MAXSIZE 0x01f00000UL 39#define F_MAXSIZE 0x01f00000UL
34#define S_MAXSIZE 20 40#define S_MAXSIZE 20
35#define F_HOOK 0x00080000UL // some hooks exist, so slow-path processing 41#define F_HOOK 0x00080000UL // some hooks exist, so slow-path processing
47 53
48#define SB do { 54#define SB do {
49#define SE } while (0) 55#define SE } while (0)
50 56
51#if __GNUC__ >= 3 57#if __GNUC__ >= 3
52# define expect(expr,value) __builtin_expect ((expr),(value)) 58# define expect(expr,value) __builtin_expect ((expr), (value))
53# define inline inline 59# define INLINE static inline
54#else 60#else
55# define expect(expr,value) (expr) 61# define expect(expr,value) (expr)
56# define inline static 62# define INLINE static
57#endif 63#endif
58 64
59#define expect_false(expr) expect ((expr) != 0, 0) 65#define expect_false(expr) expect ((expr) != 0, 0)
60#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)))
71
72#ifdef USE_ITHREADS
73# define JSON_SLOW 1
74# define JSON_STASH (json_stash ? json_stash : gv_stashpv ("JSON::XS", 1))
75#else
76# define JSON_SLOW 0
77# define JSON_STASH json_stash
78#endif
61 79
62static HV *json_stash, *json_boolean_stash; // JSON::XS:: 80static HV *json_stash, *json_boolean_stash; // JSON::XS::
63static SV *json_true, *json_false; 81static SV *json_true, *json_false;
64 82
65typedef struct { 83typedef struct {
69} JSON; 87} JSON;
70 88
71///////////////////////////////////////////////////////////////////////////// 89/////////////////////////////////////////////////////////////////////////////
72// utility functions 90// utility functions
73 91
74inline void 92INLINE void
75shrink (SV *sv) 93shrink (SV *sv)
76{ 94{
77 sv_utf8_downgrade (sv, 1); 95 sv_utf8_downgrade (sv, 1);
78 if (SvLEN (sv) > SvCUR (sv) + 1) 96 if (SvLEN (sv) > SvCUR (sv) + 1)
79 { 97 {
88// 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
89// case of an error. 107// case of an error.
90// we special-case "safe" characters from U+80 .. U+7FF, 108// we special-case "safe" characters from U+80 .. U+7FF,
91// but use the very good perl function to parse anything else. 109// but use the very good perl function to parse anything else.
92// note that we never call this function for a ascii codepoints 110// note that we never call this function for a ascii codepoints
93inline UV 111INLINE UV
94decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen) 112decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
95{ 113{
96 if (expect_false (s[0] > 0xdf || s[0] < 0xc2)) 114 if (expect_true (len >= 2
97 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY); 115 && IN_RANGE_INC (char, s[0], 0xc2, 0xdf)
98 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf) 116 && IN_RANGE_INC (char, s[1], 0x80, 0xbf)))
99 { 117 {
100 *clen = 2; 118 *clen = 2;
101 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f); 119 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
102 } 120 }
103 else 121 else
104 { 122 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY);
105 *clen = (STRLEN)-1; 123}
106 return (UV)-1; 124
107 } 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;
108} 147}
109 148
110///////////////////////////////////////////////////////////////////////////// 149/////////////////////////////////////////////////////////////////////////////
111// encoder 150// encoder
112 151
117 char *end; // SvEND (sv) 156 char *end; // SvEND (sv)
118 SV *sv; // result scalar 157 SV *sv; // result scalar
119 JSON json; 158 JSON json;
120 U32 indent; // indentation level 159 U32 indent; // indentation level
121 U32 maxdepth; // max. indentation/recursion level 160 U32 maxdepth; // max. indentation/recursion level
161 UV limit; // escape character values >= this value when encoding
122} enc_t; 162} enc_t;
123 163
124inline void 164INLINE void
125need (enc_t *enc, STRLEN len) 165need (enc_t *enc, STRLEN len)
126{ 166{
127 if (expect_false (enc->cur + len >= enc->end)) 167 if (expect_false (enc->cur + len >= enc->end))
128 { 168 {
129 STRLEN cur = enc->cur - SvPVX (enc->sv); 169 STRLEN cur = enc->cur - SvPVX (enc->sv);
131 enc->cur = SvPVX (enc->sv) + cur; 171 enc->cur = SvPVX (enc->sv) + cur;
132 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1; 172 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
133 } 173 }
134} 174}
135 175
136inline void 176INLINE void
137encode_ch (enc_t *enc, char ch) 177encode_ch (enc_t *enc, char ch)
138{ 178{
139 need (enc, 1); 179 need (enc, 1);
140 *enc->cur++ = ch; 180 *enc->cur++ = ch;
141} 181}
195 { 235 {
196 uch = ch; 236 uch = ch;
197 clen = 1; 237 clen = 1;
198 } 238 }
199 239
200 if (uch > 0x10FFFFUL) 240 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 { 241 {
205 if (uch > 0xFFFFUL) 242 if (uch >= 0x10000UL)
206 { 243 {
244 if (uch >= 0x110000UL)
245 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
246
207 need (enc, len += 11); 247 need (enc, len += 11);
208 sprintf (enc->cur, "\\u%04x\\u%04x", 248 sprintf (enc->cur, "\\u%04x\\u%04x",
209 (int)((uch - 0x10000) / 0x400 + 0xD800), 249 (int)((uch - 0x10000) / 0x400 + 0xD800),
210 (int)((uch - 0x10000) % 0x400 + 0xDC00)); 250 (int)((uch - 0x10000) % 0x400 + 0xDC00));
211 enc->cur += 12; 251 enc->cur += 12;
239 while (--clen); 279 while (--clen);
240 } 280 }
241 else 281 else
242 { 282 {
243 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
244 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); 284 enc->cur = encode_utf8 (enc->cur, uch);
245 ++str; 285 ++str;
246 } 286 }
247 } 287 }
248 } 288 }
249 } 289 }
250 290
251 --len; 291 --len;
252 } 292 }
253} 293}
254 294
255inline void 295INLINE void
256encode_indent (enc_t *enc) 296encode_indent (enc_t *enc)
257{ 297{
258 if (enc->json.flags & F_INDENT) 298 if (enc->json.flags & F_INDENT)
259 { 299 {
260 int spaces = enc->indent * INDENT_STEP; 300 int spaces = enc->indent * INDENT_STEP;
263 memset (enc->cur, ' ', spaces); 303 memset (enc->cur, ' ', spaces);
264 enc->cur += spaces; 304 enc->cur += spaces;
265 } 305 }
266} 306}
267 307
268inline void 308INLINE void
269encode_space (enc_t *enc) 309encode_space (enc_t *enc)
270{ 310{
271 need (enc, 1); 311 need (enc, 1);
272 encode_ch (enc, ' '); 312 encode_ch (enc, ' ');
273} 313}
274 314
275inline void 315INLINE void
276encode_nl (enc_t *enc) 316encode_nl (enc_t *enc)
277{ 317{
278 if (enc->json.flags & F_INDENT) 318 if (enc->json.flags & F_INDENT)
279 { 319 {
280 need (enc, 1); 320 need (enc, 1);
281 encode_ch (enc, '\n'); 321 encode_ch (enc, '\n');
282 } 322 }
283} 323}
284 324
285inline void 325INLINE void
286encode_comma (enc_t *enc) 326encode_comma (enc_t *enc)
287{ 327{
288 encode_ch (enc, ','); 328 encode_ch (enc, ',');
289 329
290 if (enc->json.flags & F_INDENT) 330 if (enc->json.flags & F_INDENT)
301 int i, len = av_len (av); 341 int i, len = av_len (av);
302 342
303 if (enc->indent >= enc->maxdepth) 343 if (enc->indent >= enc->maxdepth)
304 croak ("data structure too deep (hit recursion limit)"); 344 croak ("data structure too deep (hit recursion limit)");
305 345
306 encode_ch (enc, '['); encode_nl (enc); 346 encode_ch (enc, '[');
307 ++enc->indent; 347
348 if (len >= 0)
349 {
350 encode_nl (enc); ++enc->indent;
308 351
309 for (i = 0; i <= len; ++i) 352 for (i = 0; i <= len; ++i)
310 { 353 {
354 SV **svp = av_fetch (av, i, 0);
355
311 encode_indent (enc); 356 encode_indent (enc);
312 encode_sv (enc, *av_fetch (av, i, 0));
313 357
358 if (svp)
359 encode_sv (enc, *svp);
360 else
361 encode_str (enc, "null", 4, 0);
362
314 if (i < len) 363 if (i < len)
315 encode_comma (enc); 364 encode_comma (enc);
316 } 365 }
317 366
367 encode_nl (enc); --enc->indent; encode_indent (enc);
368 }
369
318 encode_nl (enc); 370 encode_ch (enc, ']');
319
320 --enc->indent;
321 encode_indent (enc); encode_ch (enc, ']');
322} 371}
323 372
324static void 373static void
325encode_he (enc_t *enc, HE *he) 374encode_hk (enc_t *enc, HE *he)
326{ 375{
327 encode_ch (enc, '"'); 376 encode_ch (enc, '"');
328 377
329 if (HeKLEN (he) == HEf_SVKEY) 378 if (HeKLEN (he) == HEf_SVKEY)
330 { 379 {
343 encode_ch (enc, '"'); 392 encode_ch (enc, '"');
344 393
345 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc); 394 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc);
346 encode_ch (enc, ':'); 395 encode_ch (enc, ':');
347 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc); 396 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc);
348 encode_sv (enc, HeVAL (he));
349} 397}
350 398
351// compare hash entries, used when all keys are bytestrings 399// compare hash entries, used when all keys are bytestrings
352static int 400static int
353he_cmp_fast (const void *a_, const void *b_) 401he_cmp_fast (const void *a_, const void *b_)
358 HE *b = *(HE **)b_; 406 HE *b = *(HE **)b_;
359 407
360 STRLEN la = HeKLEN (a); 408 STRLEN la = HeKLEN (a);
361 STRLEN lb = HeKLEN (b); 409 STRLEN lb = HeKLEN (b);
362 410
363 if (!(cmp = memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb))) 411 if (!(cmp = memcmp (HeKEY (b), HeKEY (a), lb < la ? lb : la)))
364 cmp = la - lb; 412 cmp = lb - la;
365 413
366 return cmp; 414 return cmp;
367} 415}
368 416
369// 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
370static int 418static int
371he_cmp_slow (const void *a, const void *b) 419he_cmp_slow (const void *a, const void *b)
372{ 420{
373 return sv_cmp (HeSVKEY_force (*(HE **)a), HeSVKEY_force (*(HE **)b)); 421 return sv_cmp (HeSVKEY_force (*(HE **)b), HeSVKEY_force (*(HE **)a));
374} 422}
375 423
376static void 424static void
377encode_hv (enc_t *enc, HV *hv) 425encode_hv (enc_t *enc, HV *hv)
378{ 426{
427 HE *he;
379 int count, i; 428 int count;
380 429
381 if (enc->indent >= enc->maxdepth) 430 if (enc->indent >= enc->maxdepth)
382 croak ("data structure too deep (hit recursion limit)"); 431 croak ("data structure too deep (hit recursion limit)");
383 432
384 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent; 433 encode_ch (enc, '{');
385 434
386 if ((count = hv_iterinit (hv)))
387 {
388 // for canonical output we have to sort by keys first 435 // for canonical output we have to sort by keys first
389 // actually, this is mostly due to the stupid so-called 436 // actually, this is mostly due to the stupid so-called
390 // security workaround added somewhere in 5.8.x. 437 // security workaround added somewhere in 5.8.x.
391 // that randomises hash orderings 438 // that randomises hash orderings
392 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))
393 { 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 {
394 int fast = 1; 459 int i, fast = 1;
395 HE *he;
396#if defined(__BORLANDC__) || defined(_MSC_VER) 460#if defined(__BORLANDC__) || defined(_MSC_VER)
397 HE **hes = _alloca (count * sizeof (HE)); 461 HE **hes = _alloca (count * sizeof (HE));
398#else 462#else
399 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
400#endif 464#endif
427 491
428 FREETMPS; 492 FREETMPS;
429 LEAVE; 493 LEAVE;
430 } 494 }
431 495
432 for (i = 0; i < count; ++i) 496 encode_nl (enc); ++enc->indent;
497
498 while (count--)
433 { 499 {
434 encode_indent (enc); 500 encode_indent (enc);
501 he = hes [count];
435 encode_he (enc, hes [i]); 502 encode_hk (enc, he);
503 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
436 504
437 if (i < count - 1) 505 if (count)
438 encode_comma (enc); 506 encode_comma (enc);
439 } 507 }
440 508
441 encode_nl (enc); 509 encode_nl (enc); --enc->indent; encode_indent (enc);
442 } 510 }
511 }
443 else 512 else
513 {
514 if (hv_iterinit (hv) || SvMAGICAL (hv))
515 if ((he = hv_iternext (hv)))
444 { 516 {
445 HE *he = hv_iternext (hv); 517 encode_nl (enc); ++enc->indent;
446 518
447 for (;;) 519 for (;;)
448 { 520 {
449 encode_indent (enc); 521 encode_indent (enc);
450 encode_he (enc, he); 522 encode_hk (enc, he);
523 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
451 524
452 if (!(he = hv_iternext (hv))) 525 if (!(he = hv_iternext (hv)))
453 break; 526 break;
454 527
455 encode_comma (enc); 528 encode_comma (enc);
456 } 529 }
457 530
458 encode_nl (enc); 531 encode_nl (enc); --enc->indent; encode_indent (enc);
459 } 532 }
460 } 533 }
461 534
462 --enc->indent; encode_indent (enc); encode_ch (enc, '}'); 535 encode_ch (enc, '}');
463} 536}
464 537
465// encode objects, arrays and special \0=false and \1=true values. 538// encode objects, arrays and special \0=false and \1=true values.
466static void 539static void
467encode_rv (enc_t *enc, SV *sv) 540encode_rv (enc_t *enc, SV *sv)
471 SvGETMAGIC (sv); 544 SvGETMAGIC (sv);
472 svt = SvTYPE (sv); 545 svt = SvTYPE (sv);
473 546
474 if (expect_false (SvOBJECT (sv))) 547 if (expect_false (SvOBJECT (sv)))
475 { 548 {
549 HV *stash = !JSON_SLOW || json_boolean_stash
550 ? json_boolean_stash
551 : gv_stashpv ("JSON::XS::Boolean", 1);
552
476 if (SvSTASH (sv) == json_boolean_stash) 553 if (SvSTASH (sv) == stash)
477 { 554 {
478 if (SvIV (sv)) 555 if (SvIV (sv))
479 encode_str (enc, "true", 4, 0); 556 encode_str (enc, "true", 4, 0);
480 else 557 else
481 encode_str (enc, "false", 5, 0); 558 encode_str (enc, "false", 5, 0);
499 576
500 ENTER; SAVETMPS; PUSHMARK (SP); 577 ENTER; SAVETMPS; PUSHMARK (SP);
501 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv))); 578 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv)));
502 579
503 // calling with G_SCALAR ensures that we always get a 1 return value 580 // calling with G_SCALAR ensures that we always get a 1 return value
504 // check anyways.
505 PUTBACK; 581 PUTBACK;
506 assert (1 == call_sv ((SV *)GvCV (to_json), G_SCALAR)); 582 call_sv ((SV *)GvCV (to_json), G_SCALAR);
507 SPAGAIN; 583 SPAGAIN;
508 584
509 // catch this surprisingly common error 585 // catch this surprisingly common error
510 if (SvROK (TOPs) && SvRV (TOPs) == sv) 586 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))); 587 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); 648 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
573 enc->cur += strlen (enc->cur); 649 enc->cur += strlen (enc->cur);
574 } 650 }
575 else if (SvIOKp (sv)) 651 else if (SvIOKp (sv))
576 { 652 {
577 // 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
578 if (SvUV (sv) & ~(UV)0x7fff) 654 // we assume two's complement
579 { 655 // we assume no aliasing issues in the union
580 // large integer, use the (rather slow) snprintf way. 656 if (SvIsUV (sv) ? SvUVX (sv) <= 59000
581 need (enc, sizeof (UV) * 3); 657 : SvIVX (sv) <= 59000 && SvIVX (sv) >= -59000)
582 enc->cur +=
583 SvIsUV(sv)
584 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv))
585 : snprintf (enc->cur, sizeof (UV) * 3, "%"IVdf, (IV)SvIVX (sv));
586 }
587 else
588 { 658 {
589 // optimise the "small number case" 659 // optimise the "small number case"
590 // 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
591 I32 i = SvIV (sv); 662 I32 i = SvIVX (sv);
592 U32 u; 663 U32 u;
593 char digit, nz = 0; 664 char digit, nz = 0;
594 665
595 need (enc, 6); 666 need (enc, 6);
596 667
602 673
603 // 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
604 // 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,
605 // resulting in a net multiplication by 10. 676 // resulting in a net multiplication by 10.
606 // we always write the digit to memory but conditionally increment 677 // we always write the digit to memory but conditionally increment
607 // the pointer, to ease the usage of conditional move instructions. 678 // the pointer, to enable the use of conditional move instructions.
608 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;
609 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;
610 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;
611 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;
612 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));
613 } 693 }
614 } 694 }
615 else if (SvROK (sv)) 695 else if (SvROK (sv))
616 encode_rv (enc, SvRV (sv)); 696 encode_rv (enc, SvRV (sv));
617 else if (!SvOK (sv)) 697 else if (!SvOK (sv))
633 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 713 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
634 enc.cur = SvPVX (enc.sv); 714 enc.cur = SvPVX (enc.sv);
635 enc.end = SvEND (enc.sv); 715 enc.end = SvEND (enc.sv);
636 enc.indent = 0; 716 enc.indent = 0;
637 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;
638 721
639 SvPOK_only (enc.sv); 722 SvPOK_only (enc.sv);
640 encode_sv (&enc, scalar); 723 encode_sv (&enc, scalar);
641 724
642 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); 725 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
663 JSON json; 746 JSON json;
664 U32 depth; // recursion depth 747 U32 depth; // recursion depth
665 U32 maxdepth; // recursion depth limit 748 U32 maxdepth; // recursion depth limit
666} dec_t; 749} dec_t;
667 750
668inline 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
669decode_ws (dec_t *dec) 761decode_ws (dec_t *dec)
670{ 762{
671 for (;;) 763 for (;;)
672 { 764 {
673 char ch = *dec->cur; 765 char ch = *dec->cur;
674 766
675 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 }
676 || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)) 779 else if (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)
677 break; 780 break; // parse error, but let higher level handle it, gives better error messages
678 781
679 ++dec->cur; 782 ++dec->cur;
680 } 783 }
681} 784}
682 785
788 891
789 if (hi >= 0x80) 892 if (hi >= 0x80)
790 { 893 {
791 utf8 = 1; 894 utf8 = 1;
792 895
793 cur = (char *)uvuni_to_utf8_flags (cur, hi, 0); 896 cur = encode_utf8 (cur, hi);
794 } 897 }
795 else 898 else
796 *cur++ = hi; 899 *cur++ = hi;
797 } 900 }
798 break; 901 break;
800 default: 903 default:
801 --dec_cur; 904 --dec_cur;
802 ERR ("illegal backslash escape sequence in string"); 905 ERR ("illegal backslash escape sequence in string");
803 } 906 }
804 } 907 }
805 else if (expect_true (ch >= 0x20 && ch <= 0x7f)) 908 else if (expect_true (ch >= 0x20 && ch < 0x80))
806 *cur++ = ch; 909 *cur++ = ch;
807 else if (ch >= 0x80) 910 else if (ch >= 0x80)
808 { 911 {
809 STRLEN clen; 912 STRLEN clen;
810 UV uch; 913 UV uch;
931 is_nv = 1; 1034 is_nv = 1;
932 } 1035 }
933 1036
934 if (!is_nv) 1037 if (!is_nv)
935 { 1038 {
1039 int len = dec->cur - start;
1040
936 // 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
937 if (*start == '-') 1042 if (*start == '-')
938 switch (dec->cur - start) 1043 switch (len)
939 { 1044 {
940 case 2: return newSViv (-( start [1] - '0' * 1)); 1045 case 2: return newSViv (-( start [1] - '0' * 1));
941 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11)); 1046 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)); 1047 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)); 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));
944 } 1050 }
945 else 1051 else
946 switch (dec->cur - start) 1052 switch (len)
947 { 1053 {
948 case 1: return newSViv ( start [0] - '0' * 1); 1054 case 1: return newSViv ( start [0] - '0' * 1);
949 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11); 1055 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); 1056 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); 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);
952 } 1059 }
953 1060
954 { 1061 {
955 UV uv; 1062 UV uv;
956 int numtype = grok_number (start, dec->cur - start, &uv); 1063 int numtype = grok_number (start, len, &uv);
957 if (numtype & IS_NUMBER_IN_UV) 1064 if (numtype & IS_NUMBER_IN_UV)
958 if (numtype & IS_NUMBER_NEG) 1065 if (numtype & IS_NUMBER_NEG)
959 { 1066 {
960 if (uv < (UV)IV_MIN) 1067 if (uv < (UV)IV_MIN)
961 return newSViv (-(IV)uv); 1068 return newSViv (-(IV)uv);
962 } 1069 }
963 else 1070 else
964 return newSVuv (uv); 1071 return newSVuv (uv);
965
966 // here would likely be the place for bigint support
967 } 1072 }
968 }
969 1073
970 // if we ever support bigint or bigfloat, this is the place for bigfloat 1074 len -= *start == '-' ? 1 : 0;
1075
1076 // does not fit into IV or UV, try NV
1077 if ((sizeof (NV) == sizeof (double) && DBL_DIG >= len)
1078 #if defined (LDBL_DIG)
1079 || (sizeof (NV) == sizeof (long double) && LDBL_DIG >= len)
1080 #endif
1081 )
1082 // fits into NV without loss of precision
1083 return newSVnv (Atof (start));
1084
1085 // everything else fails, convert it to a string
1086 return newSVpvn (start, dec->cur - start);
1087 }
1088
1089 // loss of precision here
971 return newSVnv (Atof (start)); 1090 return newSVnv (Atof (start));
972 1091
973fail: 1092fail:
974 return 0; 1093 return 0;
975} 1094}
1005 1124
1006 if (*dec->cur != ',') 1125 if (*dec->cur != ',')
1007 ERR (", or ] expected while parsing array"); 1126 ERR (", or ] expected while parsing array");
1008 1127
1009 ++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 }
1010 } 1137 }
1011 1138
1012 DEC_DEC_DEPTH; 1139 DEC_DEC_DEPTH;
1013 return newRV_noinc ((SV *)av); 1140 return newRV_noinc ((SV *)av);
1014 1141
1030 if (*dec->cur == '}') 1157 if (*dec->cur == '}')
1031 ++dec->cur; 1158 ++dec->cur;
1032 else 1159 else
1033 for (;;) 1160 for (;;)
1034 { 1161 {
1035 decode_ws (dec); EXPECT_CH ('"'); 1162 EXPECT_CH ('"');
1036 1163
1037 // heuristic: assume that 1164 // heuristic: assume that
1038 // a) decode_str + hv_store_ent are abysmally slow. 1165 // a) decode_str + hv_store_ent are abysmally slow.
1039 // b) most hash keys are short, simple ascii text. 1166 // b) most hash keys are short, simple ascii text.
1040 // => try to "fast-match" such strings to avoid 1167 // => try to "fast-match" such strings to avoid
1054 if (!key) 1181 if (!key)
1055 goto fail; 1182 goto fail;
1056 1183
1057 decode_ws (dec); EXPECT_CH (':'); 1184 decode_ws (dec); EXPECT_CH (':');
1058 1185
1186 decode_ws (dec);
1059 value = decode_sv (dec); 1187 value = decode_sv (dec);
1060 if (!value) 1188 if (!value)
1061 { 1189 {
1062 SvREFCNT_dec (key); 1190 SvREFCNT_dec (key);
1063 goto fail; 1191 goto fail;
1075 int len = p - key; 1203 int len = p - key;
1076 dec->cur = p + 1; 1204 dec->cur = p + 1;
1077 1205
1078 decode_ws (dec); EXPECT_CH (':'); 1206 decode_ws (dec); EXPECT_CH (':');
1079 1207
1208 decode_ws (dec);
1080 value = decode_sv (dec); 1209 value = decode_sv (dec);
1081 if (!value) 1210 if (!value)
1082 goto fail; 1211 goto fail;
1083 1212
1084 hv_store (hv, key, len, value, 0); 1213 hv_store (hv, key, len, value, 0);
1100 1229
1101 if (*dec->cur != ',') 1230 if (*dec->cur != ',')
1102 ERR (", or } expected while parsing object/hash"); 1231 ERR (", or } expected while parsing object/hash");
1103 1232
1104 ++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 }
1105 } 1242 }
1106 1243
1107 DEC_DEC_DEPTH; 1244 DEC_DEC_DEPTH;
1108 sv = newRV_noinc ((SV *)hv); 1245 sv = newRV_noinc ((SV *)hv);
1109 1246
1174} 1311}
1175 1312
1176static SV * 1313static SV *
1177decode_sv (dec_t *dec) 1314decode_sv (dec_t *dec)
1178{ 1315{
1179 decode_ws (dec);
1180
1181 // the beauty of JSON: you need exactly one character lookahead 1316 // the beauty of JSON: you need exactly one character lookahead
1182 // to parse anything. 1317 // to parse everything.
1183 switch (*dec->cur) 1318 switch (*dec->cur)
1184 { 1319 {
1185 case '"': ++dec->cur; return decode_str (dec); 1320 case '"': ++dec->cur; return decode_str (dec);
1186 case '[': ++dec->cur; return decode_av (dec); 1321 case '[': ++dec->cur; return decode_av (dec);
1187 case '{': ++dec->cur; return decode_hv (dec); 1322 case '{': ++dec->cur; return decode_hv (dec);
1188 1323
1189 case '-': 1324 case '-':
1190 case '0': case '1': case '2': case '3': case '4': 1325 case '0': case '1': case '2': case '3': case '4':
1191 case '5': case '6': case '7': case '8': case '9': 1326 case '5': case '6': case '7': case '8': case '9':
1192 return decode_num (dec); 1327 return decode_num (dec);
1193 1328
1194 case 't': 1329 case 't':
1195 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1330 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
1196 { 1331 {
1197 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
1198 return SvREFCNT_inc (json_true); 1336 return SvREFCNT_inc (json_true);
1199 } 1337 }
1200 else 1338 else
1201 ERR ("'true' expected"); 1339 ERR ("'true' expected");
1202 1340
1204 1342
1205 case 'f': 1343 case 'f':
1206 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1344 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
1207 { 1345 {
1208 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
1209 return SvREFCNT_inc (json_false); 1350 return SvREFCNT_inc (json_false);
1210 } 1351 }
1211 else 1352 else
1212 ERR ("'false' expected"); 1353 ERR ("'false' expected");
1213 1354
1263 1404
1264 if (dec.json.cb_object || dec.json.cb_sk_object) 1405 if (dec.json.cb_object || dec.json.cb_sk_object)
1265 dec.json.flags |= F_HOOK; 1406 dec.json.flags |= F_HOOK;
1266 1407
1267 *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);
1268 sv = decode_sv (&dec); 1411 sv = decode_sv (&dec);
1269 1412
1270 if (!(offset_return || !sv)) 1413 if (!(offset_return || !sv))
1271 { 1414 {
1272 // check for trailing garbage 1415 // check for trailing garbage
1340 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false); 1483 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1341} 1484}
1342 1485
1343PROTOTYPES: DISABLE 1486PROTOTYPES: DISABLE
1344 1487
1488void CLONE (...)
1489 CODE:
1490 json_stash = 0;
1491 json_boolean_stash = 0;
1492
1345void new (char *klass) 1493void new (char *klass)
1346 PPCODE: 1494 PPCODE:
1347{ 1495{
1348 SV *pv = NEWSV (0, sizeof (JSON)); 1496 SV *pv = NEWSV (0, sizeof (JSON));
1349 SvPOK_only (pv); 1497 SvPOK_only (pv);
1350 Zero (SvPVX (pv), 1, JSON); 1498 Zero (SvPVX (pv), 1, JSON);
1351 ((JSON *)SvPVX (pv))->flags = F_DEFAULT; 1499 ((JSON *)SvPVX (pv))->flags = F_DEFAULT;
1352 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 )));
1353} 1504}
1354 1505
1355void ascii (JSON *self, int enable = 1) 1506void ascii (JSON *self, int enable = 1)
1356 ALIAS: 1507 ALIAS:
1357 ascii = F_ASCII 1508 ascii = F_ASCII
1364 pretty = F_PRETTY 1515 pretty = F_PRETTY
1365 allow_nonref = F_ALLOW_NONREF 1516 allow_nonref = F_ALLOW_NONREF
1366 shrink = F_SHRINK 1517 shrink = F_SHRINK
1367 allow_blessed = F_ALLOW_BLESSED 1518 allow_blessed = F_ALLOW_BLESSED
1368 convert_blessed = F_CONV_BLESSED 1519 convert_blessed = F_CONV_BLESSED
1520 relaxed = F_RELAXED
1369 PPCODE: 1521 PPCODE:
1370{ 1522{
1371 if (enable) 1523 if (enable)
1372 self->flags |= ix; 1524 self->flags |= ix;
1373 else 1525 else
1374 self->flags &= ~ix; 1526 self->flags &= ~ix;
1375 1527
1376 XPUSHs (ST (0)); 1528 XPUSHs (ST (0));
1377} 1529}
1378 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
1379void max_depth (JSON *self, UV max_depth = 0x80000000UL) 1548void max_depth (JSON *self, UV max_depth = 0x80000000UL)
1380 PPCODE: 1549 PPCODE:
1381{ 1550{
1382 UV log2 = 0; 1551 UV log2 = 0;
1383 1552
1389 self->flags = self->flags & ~F_MAXDEPTH | (log2 << S_MAXDEPTH); 1558 self->flags = self->flags & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1390 1559
1391 XPUSHs (ST (0)); 1560 XPUSHs (ST (0));
1392} 1561}
1393 1562
1563U32 get_max_depth (JSON *self)
1564 CODE:
1565 RETVAL = DEC_DEPTH (self->flags);
1566 OUTPUT:
1567 RETVAL
1568
1394void max_size (JSON *self, UV max_size = 0) 1569void max_size (JSON *self, UV max_size = 0)
1395 PPCODE: 1570 PPCODE:
1396{ 1571{
1397 UV log2 = 0; 1572 UV log2 = 0;
1398 1573
1404 1579
1405 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE); 1580 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE);
1406 1581
1407 XPUSHs (ST (0)); 1582 XPUSHs (ST (0));
1408} 1583}
1584
1585int get_max_size (JSON *self)
1586 CODE:
1587 RETVAL = DEC_SIZE (self->flags);
1588 OUTPUT:
1589 RETVAL
1409 1590
1410void filter_json_object (JSON *self, SV *cb = &PL_sv_undef) 1591void filter_json_object (JSON *self, SV *cb = &PL_sv_undef)
1411 PPCODE: 1592 PPCODE:
1412{ 1593{
1413 SvREFCNT_dec (self->cb_object); 1594 SvREFCNT_dec (self->cb_object);
1460 SvREFCNT_dec (self->cb_sk_object); 1641 SvREFCNT_dec (self->cb_sk_object);
1461 SvREFCNT_dec (self->cb_object); 1642 SvREFCNT_dec (self->cb_object);
1462 1643
1463PROTOTYPES: ENABLE 1644PROTOTYPES: ENABLE
1464 1645
1465void to_json (SV *scalar) 1646void encode_json (SV *scalar)
1647 ALIAS:
1648 to_json_ = 0
1649 encode_json = F_UTF8
1466 PPCODE: 1650 PPCODE:
1467{ 1651{
1468 JSON json = { F_DEFAULT | F_UTF8 }; 1652 JSON json = { F_DEFAULT | ix };
1469 XPUSHs (encode_json (scalar, &json)); 1653 XPUSHs (encode_json (scalar, &json));
1470} 1654}
1471 1655
1472void from_json (SV *jsonstr) 1656void decode_json (SV *jsonstr)
1657 ALIAS:
1658 from_json_ = 0
1659 decode_json = F_UTF8
1473 PPCODE: 1660 PPCODE:
1474{ 1661{
1475 JSON json = { F_DEFAULT | F_UTF8 }; 1662 JSON json = { F_DEFAULT | ix };
1476 XPUSHs (decode_json (jsonstr, &json, 0)); 1663 XPUSHs (decode_json (jsonstr, &json, 0));
1477} 1664}
1478 1665

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines