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.45 by root, Mon Jun 25 06:57:42 2007 UTC vs.
Revision 1.75 by root, Wed Mar 19 15:37:54 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
25#define F_SPACE_BEFORE 0x00000020UL 29#define F_SPACE_BEFORE 0x00000020UL
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 // NYI 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
41#define F_HOOK 0x00080000UL // some hooks exist, so slow-path processing
35 42
36#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH)) 43#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH))
37#define DEC_SIZE(flags) (1UL << ((flags & F_MAXSIZE ) >> S_MAXSIZE )) 44#define DEC_SIZE(flags) (1UL << ((flags & F_MAXSIZE ) >> S_MAXSIZE ))
38 45
39#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER 46#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER
46 53
47#define SB do { 54#define SB do {
48#define SE } while (0) 55#define SE } while (0)
49 56
50#if __GNUC__ >= 3 57#if __GNUC__ >= 3
51# define expect(expr,value) __builtin_expect ((expr),(value)) 58# define expect(expr,value) __builtin_expect ((expr), (value))
52# define inline inline 59# define INLINE static inline
53#else 60#else
54# define expect(expr,value) (expr) 61# define expect(expr,value) (expr)
55# define inline static 62# define INLINE static
56#endif 63#endif
57 64
58#define expect_false(expr) expect ((expr) != 0, 0) 65#define expect_false(expr) expect ((expr) != 0, 0)
59#define expect_true(expr) expect ((expr) != 0, 1) 66#define expect_true(expr) expect ((expr) != 0, 1)
60 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
79
61static HV *json_stash, *json_boolean_stash; // JSON::XS:: 80static HV *json_stash, *json_boolean_stash; // JSON::XS::
62static SV *json_true, *json_false; 81static SV *json_true, *json_false;
63 82
83typedef struct {
84 U32 flags;
85 SV *cb_object;
86 HV *cb_sk_object;
87} JSON;
88
64///////////////////////////////////////////////////////////////////////////// 89/////////////////////////////////////////////////////////////////////////////
65// utility functions 90// utility functions
66 91
67static UV * 92INLINE void
68SvJSON (SV *sv)
69{
70 if (!(SvROK (sv) && SvOBJECT (SvRV (sv)) && SvSTASH (SvRV (sv)) == json_stash))
71 croak ("object is not of type JSON::XS");
72
73 return &SvUVX (SvRV (sv));
74}
75
76static void
77shrink (SV *sv) 93shrink (SV *sv)
78{ 94{
79 sv_utf8_downgrade (sv, 1); 95 sv_utf8_downgrade (sv, 1);
80 if (SvLEN (sv) > SvCUR (sv) + 1) 96 if (SvLEN (sv) > SvCUR (sv) + 1)
81 { 97 {
90// 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
91// case of an error. 107// case of an error.
92// we special-case "safe" characters from U+80 .. U+7FF, 108// we special-case "safe" characters from U+80 .. U+7FF,
93// but use the very good perl function to parse anything else. 109// but use the very good perl function to parse anything else.
94// note that we never call this function for a ascii codepoints 110// note that we never call this function for a ascii codepoints
95inline UV 111INLINE UV
96decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen) 112decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
97{ 113{
98 if (expect_false (s[0] > 0xdf || s[0] < 0xc2)) 114 if (expect_true (len >= 2
99 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY); 115 && IN_RANGE_INC (char, s[0], 0xc2, 0xdf)
100 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf) 116 && IN_RANGE_INC (char, s[1], 0x80, 0xbf)))
101 { 117 {
102 *clen = 2; 118 *clen = 2;
103 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f); 119 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
104 } 120 }
105 else 121 else
106 { 122 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY);
107 *clen = (STRLEN)-1; 123}
108 return (UV)-1; 124
109 } 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;
110} 147}
111 148
112///////////////////////////////////////////////////////////////////////////// 149/////////////////////////////////////////////////////////////////////////////
113// encoder 150// encoder
114 151
116typedef struct 153typedef struct
117{ 154{
118 char *cur; // SvPVX (sv) + current output position 155 char *cur; // SvPVX (sv) + current output position
119 char *end; // SvEND (sv) 156 char *end; // SvEND (sv)
120 SV *sv; // result scalar 157 SV *sv; // result scalar
121 U32 flags; // F_* 158 JSON json;
122 U32 indent; // indentation level 159 U32 indent; // indentation level
123 U32 maxdepth; // max. indentation/recursion level 160 U32 maxdepth; // max. indentation/recursion level
161 UV limit; // escape character values >= this value when encoding
124} enc_t; 162} enc_t;
125 163
126inline void 164INLINE void
127need (enc_t *enc, STRLEN len) 165need (enc_t *enc, STRLEN len)
128{ 166{
129 if (expect_false (enc->cur + len >= enc->end)) 167 if (expect_false (enc->cur + len >= enc->end))
130 { 168 {
131 STRLEN cur = enc->cur - SvPVX (enc->sv); 169 STRLEN cur = enc->cur - SvPVX (enc->sv);
133 enc->cur = SvPVX (enc->sv) + cur; 171 enc->cur = SvPVX (enc->sv) + cur;
134 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1; 172 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
135 } 173 }
136} 174}
137 175
138inline void 176INLINE void
139encode_ch (enc_t *enc, char ch) 177encode_ch (enc_t *enc, char ch)
140{ 178{
141 need (enc, 1); 179 need (enc, 1);
142 *enc->cur++ = ch; 180 *enc->cur++ = ch;
143} 181}
197 { 235 {
198 uch = ch; 236 uch = ch;
199 clen = 1; 237 clen = 1;
200 } 238 }
201 239
202 if (uch > 0x10FFFFUL) 240 if (uch < 0x80/*0x20*/ || uch >= enc->limit)
203 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
204
205 if (uch < 0x80 || enc->flags & F_ASCII || (enc->flags & F_LATIN1 && uch > 0xFF))
206 { 241 {
207 if (uch > 0xFFFFUL) 242 if (uch >= 0x10000UL)
208 { 243 {
244 if (uch >= 0x110000UL)
245 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
246
209 need (enc, len += 11); 247 need (enc, len += 11);
210 sprintf (enc->cur, "\\u%04x\\u%04x", 248 sprintf (enc->cur, "\\u%04x\\u%04x",
211 (int)((uch - 0x10000) / 0x400 + 0xD800), 249 (int)((uch - 0x10000) / 0x400 + 0xD800),
212 (int)((uch - 0x10000) % 0x400 + 0xDC00)); 250 (int)((uch - 0x10000) % 0x400 + 0xDC00));
213 enc->cur += 12; 251 enc->cur += 12;
224 *enc->cur++ = hexdigit [(uch >> 0) & 15]; 262 *enc->cur++ = hexdigit [(uch >> 0) & 15];
225 } 263 }
226 264
227 str += clen; 265 str += clen;
228 } 266 }
229 else if (enc->flags & F_LATIN1) 267 else if (enc->json.flags & F_LATIN1)
230 { 268 {
231 *enc->cur++ = uch; 269 *enc->cur++ = uch;
232 str += clen; 270 str += clen;
233 } 271 }
234 else if (is_utf8) 272 else if (is_utf8)
241 while (--clen); 279 while (--clen);
242 } 280 }
243 else 281 else
244 { 282 {
245 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
246 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); 284 enc->cur = encode_utf8 (enc->cur, uch);
247 ++str; 285 ++str;
248 } 286 }
249 } 287 }
250 } 288 }
251 } 289 }
252 290
253 --len; 291 --len;
254 } 292 }
255} 293}
256 294
257inline void 295INLINE void
258encode_indent (enc_t *enc) 296encode_indent (enc_t *enc)
259{ 297{
260 if (enc->flags & F_INDENT) 298 if (enc->json.flags & F_INDENT)
261 { 299 {
262 int spaces = enc->indent * INDENT_STEP; 300 int spaces = enc->indent * INDENT_STEP;
263 301
264 need (enc, spaces); 302 need (enc, spaces);
265 memset (enc->cur, ' ', spaces); 303 memset (enc->cur, ' ', spaces);
266 enc->cur += spaces; 304 enc->cur += spaces;
267 } 305 }
268} 306}
269 307
270inline void 308INLINE void
271encode_space (enc_t *enc) 309encode_space (enc_t *enc)
272{ 310{
273 need (enc, 1); 311 need (enc, 1);
274 encode_ch (enc, ' '); 312 encode_ch (enc, ' ');
275} 313}
276 314
277inline void 315INLINE void
278encode_nl (enc_t *enc) 316encode_nl (enc_t *enc)
279{ 317{
280 if (enc->flags & F_INDENT) 318 if (enc->json.flags & F_INDENT)
281 { 319 {
282 need (enc, 1); 320 need (enc, 1);
283 encode_ch (enc, '\n'); 321 encode_ch (enc, '\n');
284 } 322 }
285} 323}
286 324
287inline void 325INLINE void
288encode_comma (enc_t *enc) 326encode_comma (enc_t *enc)
289{ 327{
290 encode_ch (enc, ','); 328 encode_ch (enc, ',');
291 329
292 if (enc->flags & F_INDENT) 330 if (enc->json.flags & F_INDENT)
293 encode_nl (enc); 331 encode_nl (enc);
294 else if (enc->flags & F_SPACE_AFTER) 332 else if (enc->json.flags & F_SPACE_AFTER)
295 encode_space (enc); 333 encode_space (enc);
296} 334}
297 335
298static void encode_sv (enc_t *enc, SV *sv); 336static void encode_sv (enc_t *enc, SV *sv);
299 337
303 int i, len = av_len (av); 341 int i, len = av_len (av);
304 342
305 if (enc->indent >= enc->maxdepth) 343 if (enc->indent >= enc->maxdepth)
306 croak ("data structure too deep (hit recursion limit)"); 344 croak ("data structure too deep (hit recursion limit)");
307 345
308 encode_ch (enc, '['); encode_nl (enc); 346 encode_ch (enc, '[');
309 ++enc->indent; 347
348 if (len >= 0)
349 {
350 encode_nl (enc); ++enc->indent;
310 351
311 for (i = 0; i <= len; ++i) 352 for (i = 0; i <= len; ++i)
312 { 353 {
354 SV **svp = av_fetch (av, i, 0);
355
313 encode_indent (enc); 356 encode_indent (enc);
314 encode_sv (enc, *av_fetch (av, i, 0));
315 357
358 if (svp)
359 encode_sv (enc, *svp);
360 else
361 encode_str (enc, "null", 4, 0);
362
316 if (i < len) 363 if (i < len)
317 encode_comma (enc); 364 encode_comma (enc);
318 } 365 }
319 366
367 encode_nl (enc); --enc->indent; encode_indent (enc);
368 }
369
320 encode_nl (enc); 370 encode_ch (enc, ']');
321
322 --enc->indent;
323 encode_indent (enc); encode_ch (enc, ']');
324} 371}
325 372
326static void 373static void
327encode_he (enc_t *enc, HE *he) 374encode_hk (enc_t *enc, HE *he)
328{ 375{
329 encode_ch (enc, '"'); 376 encode_ch (enc, '"');
330 377
331 if (HeKLEN (he) == HEf_SVKEY) 378 if (HeKLEN (he) == HEf_SVKEY)
332 { 379 {
342 else 389 else
343 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he)); 390 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he));
344 391
345 encode_ch (enc, '"'); 392 encode_ch (enc, '"');
346 393
347 if (enc->flags & F_SPACE_BEFORE) encode_space (enc); 394 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc);
348 encode_ch (enc, ':'); 395 encode_ch (enc, ':');
349 if (enc->flags & F_SPACE_AFTER ) encode_space (enc); 396 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc);
350 encode_sv (enc, HeVAL (he));
351} 397}
352 398
353// compare hash entries, used when all keys are bytestrings 399// compare hash entries, used when all keys are bytestrings
354static int 400static int
355he_cmp_fast (const void *a_, const void *b_) 401he_cmp_fast (const void *a_, const void *b_)
360 HE *b = *(HE **)b_; 406 HE *b = *(HE **)b_;
361 407
362 STRLEN la = HeKLEN (a); 408 STRLEN la = HeKLEN (a);
363 STRLEN lb = HeKLEN (b); 409 STRLEN lb = HeKLEN (b);
364 410
365 if (!(cmp = memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb))) 411 if (!(cmp = memcmp (HeKEY (b), HeKEY (a), lb < la ? lb : la)))
366 cmp = la - lb; 412 cmp = lb - la;
367 413
368 return cmp; 414 return cmp;
369} 415}
370 416
371// 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
372static int 418static int
373he_cmp_slow (const void *a, const void *b) 419he_cmp_slow (const void *a, const void *b)
374{ 420{
375 return sv_cmp (HeSVKEY_force (*(HE **)a), HeSVKEY_force (*(HE **)b)); 421 return sv_cmp (HeSVKEY_force (*(HE **)b), HeSVKEY_force (*(HE **)a));
376} 422}
377 423
378static void 424static void
379encode_hv (enc_t *enc, HV *hv) 425encode_hv (enc_t *enc, HV *hv)
380{ 426{
427 HE *he;
381 int count, i; 428 int count;
382 429
383 if (enc->indent >= enc->maxdepth) 430 if (enc->indent >= enc->maxdepth)
384 croak ("data structure too deep (hit recursion limit)"); 431 croak ("data structure too deep (hit recursion limit)");
385 432
386 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent; 433 encode_ch (enc, '{');
387 434
388 if ((count = hv_iterinit (hv)))
389 {
390 // for canonical output we have to sort by keys first 435 // for canonical output we have to sort by keys first
391 // actually, this is mostly due to the stupid so-called 436 // actually, this is mostly due to the stupid so-called
392 // security workaround added somewhere in 5.8.x. 437 // security workaround added somewhere in 5.8.x.
393 // that randomises hash orderings 438 // that randomises hash orderings
394 if (enc->flags & F_CANONICAL) 439 if (enc->json.flags & F_CANONICAL)
440 {
441 int count = hv_iterinit (hv);
442
443 if (SvMAGICAL (hv))
395 { 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 {
396 int fast = 1; 459 int i, fast = 1;
397 HE *he;
398#if defined(__BORLANDC__) || defined(_MSC_VER) 460#if defined(__BORLANDC__) || defined(_MSC_VER)
399 HE **hes = _alloca (count * sizeof (HE)); 461 HE **hes = _alloca (count * sizeof (HE));
400#else 462#else
401 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
402#endif 464#endif
429 491
430 FREETMPS; 492 FREETMPS;
431 LEAVE; 493 LEAVE;
432 } 494 }
433 495
434 for (i = 0; i < count; ++i) 496 encode_nl (enc); ++enc->indent;
497
498 while (count--)
435 { 499 {
436 encode_indent (enc); 500 encode_indent (enc);
501 he = hes [count];
437 encode_he (enc, hes [i]); 502 encode_hk (enc, he);
503 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
438 504
439 if (i < count - 1) 505 if (count)
440 encode_comma (enc); 506 encode_comma (enc);
441 } 507 }
442 508
443 encode_nl (enc); 509 encode_nl (enc); --enc->indent; encode_indent (enc);
444 } 510 }
511 }
445 else 512 else
513 {
514 if (hv_iterinit (hv) || SvMAGICAL (hv))
515 if ((he = hv_iternext (hv)))
446 { 516 {
447 HE *he = hv_iternext (hv); 517 encode_nl (enc); ++enc->indent;
448 518
449 for (;;) 519 for (;;)
450 { 520 {
451 encode_indent (enc); 521 encode_indent (enc);
452 encode_he (enc, he); 522 encode_hk (enc, he);
523 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
453 524
454 if (!(he = hv_iternext (hv))) 525 if (!(he = hv_iternext (hv)))
455 break; 526 break;
456 527
457 encode_comma (enc); 528 encode_comma (enc);
458 } 529 }
459 530
460 encode_nl (enc); 531 encode_nl (enc); --enc->indent; encode_indent (enc);
461 } 532 }
462 } 533 }
463 534
464 --enc->indent; encode_indent (enc); encode_ch (enc, '}'); 535 encode_ch (enc, '}');
465} 536}
466 537
467// encode objects, arrays and special \0=false and \1=true values. 538// encode objects, arrays and special \0=false and \1=true values.
468static void 539static void
469encode_rv (enc_t *enc, SV *sv) 540encode_rv (enc_t *enc, SV *sv)
473 SvGETMAGIC (sv); 544 SvGETMAGIC (sv);
474 svt = SvTYPE (sv); 545 svt = SvTYPE (sv);
475 546
476 if (expect_false (SvOBJECT (sv))) 547 if (expect_false (SvOBJECT (sv)))
477 { 548 {
549 HV *stash = !JSON_SLOW || json_boolean_stash
550 ? json_boolean_stash
551 : gv_stashpv ("JSON::XS::Boolean", 1);
552
478 if (SvSTASH (sv) == json_boolean_stash) 553 if (SvSTASH (sv) == stash)
479 { 554 {
480 if (SvIV (sv) == 0) 555 if (SvIV (sv))
556 encode_str (enc, "true", 4, 0);
557 else
481 encode_str (enc, "false", 5, 0); 558 encode_str (enc, "false", 5, 0);
482 else
483 encode_str (enc, "true", 4, 0);
484 } 559 }
485 else 560 else
486 { 561 {
487#if 0 562#if 0
488 if (0 && sv_derived_from (rv, "JSON::Literal")) 563 if (0 && sv_derived_from (rv, "JSON::Literal"))
489 { 564 {
490 // not yet 565 // not yet
491 } 566 }
492#endif 567#endif
493 if (enc->flags & F_CONV_BLESSED) 568 if (enc->json.flags & F_CONV_BLESSED)
494 { 569 {
495 // we re-bless the reference to get overload and other niceties right 570 // we re-bless the reference to get overload and other niceties right
496 GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 1); 571 GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 0);
497 572
498 if (to_json) 573 if (to_json)
499 { 574 {
500 dSP; 575 dSP;
501 ENTER; 576
502 SAVETMPS;
503 PUSHMARK (SP); 577 ENTER; SAVETMPS; PUSHMARK (SP);
504 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv))); 578 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv)));
505 579
506 // calling with G_SCALAR ensures that we always get a 1 reutrn value 580 // calling with G_SCALAR ensures that we always get a 1 return value
507 // check anyways.
508 PUTBACK; 581 PUTBACK;
509 assert (1 == call_sv ((SV *)GvCV (to_json), G_SCALAR)); 582 call_sv ((SV *)GvCV (to_json), G_SCALAR);
510 SPAGAIN; 583 SPAGAIN;
511 584
585 // catch this surprisingly common error
586 if (SvROK (TOPs) && SvRV (TOPs) == sv)
587 croak ("%s::TO_JSON method returned same object as was passed instead of a new one", HvNAME (SvSTASH (sv)));
588
589 sv = POPs;
590 PUTBACK;
591
512 encode_sv (enc, POPs); 592 encode_sv (enc, sv);
513 593
514 FREETMPS; 594 FREETMPS; LEAVE;
515 LEAVE;
516 } 595 }
517 else if (enc->flags & F_ALLOW_BLESSED) 596 else if (enc->json.flags & F_ALLOW_BLESSED)
518 encode_str (enc, "null", 4, 0); 597 encode_str (enc, "null", 4, 0);
519 else 598 else
520 croak ("encountered object '%s', but neither allow_blessed enabled nor TO_JSON method available on it", 599 croak ("encountered object '%s', but neither allow_blessed enabled nor TO_JSON method available on it",
521 SvPV_nolen (sv_2mortal (newRV_inc (sv)))); 600 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
522 } 601 }
523 else if (enc->flags & F_ALLOW_BLESSED) 602 else if (enc->json.flags & F_ALLOW_BLESSED)
524 encode_str (enc, "null", 4, 0); 603 encode_str (enc, "null", 4, 0);
525 else 604 else
526 croak ("encountered object '%s', but neither allow_blessed nor convert_blessed settings are enabled", 605 croak ("encountered object '%s', but neither allow_blessed nor convert_blessed settings are enabled",
527 SvPV_nolen (sv_2mortal (newRV_inc (sv)))); 606 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
528 } 607 }
531 encode_hv (enc, (HV *)sv); 610 encode_hv (enc, (HV *)sv);
532 else if (svt == SVt_PVAV) 611 else if (svt == SVt_PVAV)
533 encode_av (enc, (AV *)sv); 612 encode_av (enc, (AV *)sv);
534 else if (svt < SVt_PVAV) 613 else if (svt < SVt_PVAV)
535 { 614 {
536 if (SvNIOK (sv) && SvIV (sv) == 0) 615 STRLEN len = 0;
616 char *pv = svt ? SvPV (sv, len) : 0;
617
618 if (len == 1 && *pv == '1')
619 encode_str (enc, "true", 4, 0);
620 else if (len == 1 && *pv == '0')
537 encode_str (enc, "false", 5, 0); 621 encode_str (enc, "false", 5, 0);
538 else if (SvNIOK (sv) && SvIV (sv) == 1)
539 encode_str (enc, "true", 4, 0);
540 else 622 else
541 croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1", 623 croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1",
542 SvPV_nolen (sv_2mortal (newRV_inc (sv)))); 624 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
543 } 625 }
544 else 626 else
566 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur); 648 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
567 enc->cur += strlen (enc->cur); 649 enc->cur += strlen (enc->cur);
568 } 650 }
569 else if (SvIOKp (sv)) 651 else if (SvIOKp (sv))
570 { 652 {
571 // 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
572 if (SvUV (sv) & ~(UV)0x7fff) 654 // we assume two's complement
573 { 655 // we assume no aliasing issues in the union
574 // large integer, use the (rather slow) snprintf way. 656 if (SvIsUV (sv) ? SvUVX (sv) <= 59000
575 need (enc, sizeof (UV) * 3); 657 : SvIVX (sv) <= 59000 && SvIVX (sv) >= -59000)
576 enc->cur +=
577 SvIsUV(sv)
578 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv))
579 : snprintf (enc->cur, sizeof (UV) * 3, "%"IVdf, (IV)SvIVX (sv));
580 }
581 else
582 { 658 {
583 // optimise the "small number case" 659 // optimise the "small number case"
584 // 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
585 I32 i = SvIV (sv); 662 I32 i = SvIVX (sv);
586 U32 u; 663 U32 u;
587 char digit, nz = 0; 664 char digit, nz = 0;
588 665
589 need (enc, 6); 666 need (enc, 6);
590 667
596 673
597 // 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
598 // 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,
599 // resulting in a net multiplication by 10. 676 // resulting in a net multiplication by 10.
600 // we always write the digit to memory but conditionally increment 677 // we always write the digit to memory but conditionally increment
601 // the pointer, to ease the usage of conditional move instructions. 678 // the pointer, to enable the use of conditional move instructions.
602 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;
603 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;
604 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;
605 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;
606 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));
607 } 693 }
608 } 694 }
609 else if (SvROK (sv)) 695 else if (SvROK (sv))
610 encode_rv (enc, SvRV (sv)); 696 encode_rv (enc, SvRV (sv));
611 else if (!SvOK (sv)) 697 else if (!SvOK (sv))
614 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this", 700 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this",
615 SvPV_nolen (sv), SvFLAGS (sv)); 701 SvPV_nolen (sv), SvFLAGS (sv));
616} 702}
617 703
618static SV * 704static SV *
619encode_json (SV *scalar, U32 flags) 705encode_json (SV *scalar, JSON *json)
620{ 706{
621 enc_t enc; 707 enc_t enc;
622 708
623 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar)) 709 if (!(json->flags & F_ALLOW_NONREF) && !SvROK (scalar))
624 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)"); 710 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)");
625 711
626 enc.flags = flags; 712 enc.json = *json;
627 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 713 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
628 enc.cur = SvPVX (enc.sv); 714 enc.cur = SvPVX (enc.sv);
629 enc.end = SvEND (enc.sv); 715 enc.end = SvEND (enc.sv);
630 enc.indent = 0; 716 enc.indent = 0;
631 enc.maxdepth = DEC_DEPTH (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;
632 721
633 SvPOK_only (enc.sv); 722 SvPOK_only (enc.sv);
634 encode_sv (&enc, scalar); 723 encode_sv (&enc, scalar);
635 724
636 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); 725 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
637 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings 726 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings
638 727
639 if (!(flags & (F_ASCII | F_LATIN1 | F_UTF8))) 728 if (!(enc.json.flags & (F_ASCII | F_LATIN1 | F_UTF8)))
640 SvUTF8_on (enc.sv); 729 SvUTF8_on (enc.sv);
641 730
642 if (enc.flags & F_SHRINK) 731 if (enc.json.flags & F_SHRINK)
643 shrink (enc.sv); 732 shrink (enc.sv);
644 733
645 return enc.sv; 734 return enc.sv;
646} 735}
647 736
652typedef struct 741typedef struct
653{ 742{
654 char *cur; // current parser pointer 743 char *cur; // current parser pointer
655 char *end; // end of input string 744 char *end; // end of input string
656 const char *err; // parse error, if != 0 745 const char *err; // parse error, if != 0
657 U32 flags; // F_* 746 JSON json;
658 U32 depth; // recursion depth 747 U32 depth; // recursion depth
659 U32 maxdepth; // recursion depth limit 748 U32 maxdepth; // recursion depth limit
660} dec_t; 749} dec_t;
661 750
662inline 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
663decode_ws (dec_t *dec) 761decode_ws (dec_t *dec)
664{ 762{
665 for (;;) 763 for (;;)
666 { 764 {
667 char ch = *dec->cur; 765 char ch = *dec->cur;
668 766
669 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 }
670 || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)) 779 else if (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)
671 break; 780 break; // parse error, but let higher level handle it, gives better error messages
672 781
673 ++dec->cur; 782 ++dec->cur;
674 } 783 }
675} 784}
676 785
782 891
783 if (hi >= 0x80) 892 if (hi >= 0x80)
784 { 893 {
785 utf8 = 1; 894 utf8 = 1;
786 895
787 cur = (char *)uvuni_to_utf8_flags (cur, hi, 0); 896 cur = encode_utf8 (cur, hi);
788 } 897 }
789 else 898 else
790 *cur++ = hi; 899 *cur++ = hi;
791 } 900 }
792 break; 901 break;
794 default: 903 default:
795 --dec_cur; 904 --dec_cur;
796 ERR ("illegal backslash escape sequence in string"); 905 ERR ("illegal backslash escape sequence in string");
797 } 906 }
798 } 907 }
799 else if (expect_true (ch >= 0x20 && ch <= 0x7f)) 908 else if (expect_true (ch >= 0x20 && ch < 0x80))
800 *cur++ = ch; 909 *cur++ = ch;
801 else if (ch >= 0x80) 910 else if (ch >= 0x80)
802 { 911 {
803 STRLEN clen; 912 STRLEN clen;
804 UV uch; 913 UV uch;
925 is_nv = 1; 1034 is_nv = 1;
926 } 1035 }
927 1036
928 if (!is_nv) 1037 if (!is_nv)
929 { 1038 {
1039 int len = dec->cur - start;
1040
930 // 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
931 if (*start == '-') 1042 if (*start == '-')
932 switch (dec->cur - start) 1043 switch (len)
933 { 1044 {
934 case 2: return newSViv (-( start [1] - '0' * 1)); 1045 case 2: return newSViv (-( start [1] - '0' * 1));
935 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11)); 1046 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11));
936 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));
937 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));
938 } 1050 }
939 else 1051 else
940 switch (dec->cur - start) 1052 switch (len)
941 { 1053 {
942 case 1: return newSViv ( start [0] - '0' * 1); 1054 case 1: return newSViv ( start [0] - '0' * 1);
943 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11); 1055 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11);
944 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);
945 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);
946 } 1059 }
947 1060
948 { 1061 {
949 UV uv; 1062 UV uv;
950 int numtype = grok_number (start, dec->cur - start, &uv); 1063 int numtype = grok_number (start, len, &uv);
951 if (numtype & IS_NUMBER_IN_UV) 1064 if (numtype & IS_NUMBER_IN_UV)
952 if (numtype & IS_NUMBER_NEG) 1065 if (numtype & IS_NUMBER_NEG)
953 { 1066 {
954 if (uv < (UV)IV_MIN) 1067 if (uv < (UV)IV_MIN)
955 return newSViv (-(IV)uv); 1068 return newSViv (-(IV)uv);
956 } 1069 }
957 else 1070 else
958 return newSVuv (uv); 1071 return newSVuv (uv);
959
960 // here would likely be the place for bigint support
961 } 1072 }
962 }
963 1073
964 // 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
965 return newSVnv (Atof (start)); 1090 return newSVnv (Atof (start));
966 1091
967fail: 1092fail:
968 return 0; 1093 return 0;
969} 1094}
999 1124
1000 if (*dec->cur != ',') 1125 if (*dec->cur != ',')
1001 ERR (", or ] expected while parsing array"); 1126 ERR (", or ] expected while parsing array");
1002 1127
1003 ++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 }
1004 } 1137 }
1005 1138
1006 DEC_DEC_DEPTH; 1139 DEC_DEC_DEPTH;
1007 return newRV_noinc ((SV *)av); 1140 return newRV_noinc ((SV *)av);
1008 1141
1013} 1146}
1014 1147
1015static SV * 1148static SV *
1016decode_hv (dec_t *dec) 1149decode_hv (dec_t *dec)
1017{ 1150{
1151 SV *sv;
1018 HV *hv = newHV (); 1152 HV *hv = newHV ();
1019 1153
1020 DEC_INC_DEPTH; 1154 DEC_INC_DEPTH;
1021 decode_ws (dec); 1155 decode_ws (dec);
1022 1156
1023 if (*dec->cur == '}') 1157 if (*dec->cur == '}')
1024 ++dec->cur; 1158 ++dec->cur;
1025 else 1159 else
1026 for (;;) 1160 for (;;)
1027 { 1161 {
1162 EXPECT_CH ('"');
1163
1164 // heuristic: assume that
1165 // a) decode_str + hv_store_ent are abysmally slow.
1166 // b) most hash keys are short, simple ascii text.
1167 // => try to "fast-match" such strings to avoid
1168 // the overhead of decode_str + hv_store_ent.
1169 {
1028 SV *key, *value; 1170 SV *value;
1171 char *p = dec->cur;
1172 char *e = p + 24; // only try up to 24 bytes
1029 1173
1030 decode_ws (dec); EXPECT_CH ('"'); 1174 for (;;)
1031
1032 key = decode_str (dec);
1033 if (!key)
1034 goto fail;
1035
1036 decode_ws (dec); EXPECT_CH (':');
1037
1038 value = decode_sv (dec);
1039 if (!value)
1040 { 1175 {
1176 // the >= 0x80 is true on most architectures
1177 if (p == e || *p < 0x20 || *p >= 0x80 || *p == '\\')
1178 {
1179 // slow path, back up and use decode_str
1180 SV *key = decode_str (dec);
1181 if (!key)
1182 goto fail;
1183
1184 decode_ws (dec); EXPECT_CH (':');
1185
1186 decode_ws (dec);
1187 value = decode_sv (dec);
1188 if (!value)
1189 {
1190 SvREFCNT_dec (key);
1191 goto fail;
1192 }
1193
1194 hv_store_ent (hv, key, value, 0);
1041 SvREFCNT_dec (key); 1195 SvREFCNT_dec (key);
1196
1197 break;
1198 }
1199 else if (*p == '"')
1200 {
1201 // fast path, got a simple key
1202 char *key = dec->cur;
1203 int len = p - key;
1204 dec->cur = p + 1;
1205
1206 decode_ws (dec); EXPECT_CH (':');
1207
1208 decode_ws (dec);
1209 value = decode_sv (dec);
1210 if (!value)
1042 goto fail; 1211 goto fail;
1212
1213 hv_store (hv, key, len, value, 0);
1214
1215 break;
1216 }
1217
1218 ++p;
1043 } 1219 }
1044 1220 }
1045 hv_store_ent (hv, key, value, 0);
1046 SvREFCNT_dec (key);
1047 1221
1048 decode_ws (dec); 1222 decode_ws (dec);
1049 1223
1050 if (*dec->cur == '}') 1224 if (*dec->cur == '}')
1051 { 1225 {
1055 1229
1056 if (*dec->cur != ',') 1230 if (*dec->cur != ',')
1057 ERR (", or } expected while parsing object/hash"); 1231 ERR (", or } expected while parsing object/hash");
1058 1232
1059 ++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 }
1060 } 1242 }
1061 1243
1062 DEC_DEC_DEPTH; 1244 DEC_DEC_DEPTH;
1063 return newRV_noinc ((SV *)hv); 1245 sv = newRV_noinc ((SV *)hv);
1246
1247 // check filter callbacks
1248 if (dec->json.flags & F_HOOK)
1249 {
1250 if (dec->json.cb_sk_object && HvKEYS (hv) == 1)
1251 {
1252 HE *cb, *he;
1253
1254 hv_iterinit (hv);
1255 he = hv_iternext (hv);
1256 hv_iterinit (hv);
1257
1258 // the next line creates a mortal sv each time its called.
1259 // might want to optimise this for common cases.
1260 cb = hv_fetch_ent (dec->json.cb_sk_object, hv_iterkeysv (he), 0, 0);
1261
1262 if (cb)
1263 {
1264 dSP;
1265 int count;
1266
1267 ENTER; SAVETMPS; PUSHMARK (SP);
1268 XPUSHs (HeVAL (he));
1269
1270 PUTBACK; count = call_sv (HeVAL (cb), G_ARRAY); SPAGAIN;
1271
1272 if (count == 1)
1273 {
1274 sv = newSVsv (POPs);
1275 FREETMPS; LEAVE;
1276 return sv;
1277 }
1278
1279 FREETMPS; LEAVE;
1280 }
1281 }
1282
1283 if (dec->json.cb_object)
1284 {
1285 dSP;
1286 int count;
1287
1288 ENTER; SAVETMPS; PUSHMARK (SP);
1289 XPUSHs (sv_2mortal (sv));
1290
1291 PUTBACK; count = call_sv (dec->json.cb_object, G_ARRAY); SPAGAIN;
1292
1293 if (count == 1)
1294 {
1295 sv = newSVsv (POPs);
1296 FREETMPS; LEAVE;
1297 return sv;
1298 }
1299
1300 SvREFCNT_inc (sv);
1301 FREETMPS; LEAVE;
1302 }
1303 }
1304
1305 return sv;
1064 1306
1065fail: 1307fail:
1066 SvREFCNT_dec (hv); 1308 SvREFCNT_dec (hv);
1067 DEC_DEC_DEPTH; 1309 DEC_DEC_DEPTH;
1068 return 0; 1310 return 0;
1069} 1311}
1070 1312
1071static SV * 1313static SV *
1072decode_sv (dec_t *dec) 1314decode_sv (dec_t *dec)
1073{ 1315{
1074 decode_ws (dec);
1075
1076 // the beauty of JSON: you need exactly one character lookahead 1316 // the beauty of JSON: you need exactly one character lookahead
1077 // to parse anything. 1317 // to parse everything.
1078 switch (*dec->cur) 1318 switch (*dec->cur)
1079 { 1319 {
1080 case '"': ++dec->cur; return decode_str (dec); 1320 case '"': ++dec->cur; return decode_str (dec);
1081 case '[': ++dec->cur; return decode_av (dec); 1321 case '[': ++dec->cur; return decode_av (dec);
1082 case '{': ++dec->cur; return decode_hv (dec); 1322 case '{': ++dec->cur; return decode_hv (dec);
1083 1323
1084 case '-': 1324 case '-':
1085 case '0': case '1': case '2': case '3': case '4': 1325 case '0': case '1': case '2': case '3': case '4':
1086 case '5': case '6': case '7': case '8': case '9': 1326 case '5': case '6': case '7': case '8': case '9':
1087 return decode_num (dec); 1327 return decode_num (dec);
1088 1328
1089 case 't': 1329 case 't':
1090 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1330 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
1091 { 1331 {
1092 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
1093 return SvREFCNT_inc (json_true); 1336 return SvREFCNT_inc (json_true);
1094 } 1337 }
1095 else 1338 else
1096 ERR ("'true' expected"); 1339 ERR ("'true' expected");
1097 1340
1099 1342
1100 case 'f': 1343 case 'f':
1101 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1344 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
1102 { 1345 {
1103 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
1104 return SvREFCNT_inc (json_false); 1350 return SvREFCNT_inc (json_false);
1105 } 1351 }
1106 else 1352 else
1107 ERR ("'false' expected"); 1353 ERR ("'false' expected");
1108 1354
1127fail: 1373fail:
1128 return 0; 1374 return 0;
1129} 1375}
1130 1376
1131static SV * 1377static SV *
1132decode_json (SV *string, U32 flags, UV *offset_return) 1378decode_json (SV *string, JSON *json, UV *offset_return)
1133{ 1379{
1134 dec_t dec; 1380 dec_t dec;
1135 UV offset; 1381 UV offset;
1136 SV *sv; 1382 SV *sv;
1137 1383
1138 SvGETMAGIC (string); 1384 SvGETMAGIC (string);
1139 SvUPGRADE (string, SVt_PV); 1385 SvUPGRADE (string, SVt_PV);
1140 1386
1141 if (flags & F_MAXSIZE && SvCUR (string) > DEC_SIZE (flags)) 1387 if (json->flags & F_MAXSIZE && SvCUR (string) > DEC_SIZE (json->flags))
1142 croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu", 1388 croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu",
1143 (unsigned long)SvCUR (string), (unsigned long)DEC_SIZE (flags)); 1389 (unsigned long)SvCUR (string), (unsigned long)DEC_SIZE (json->flags));
1144 1390
1145 if (flags & F_UTF8) 1391 if (json->flags & F_UTF8)
1146 sv_utf8_downgrade (string, 0); 1392 sv_utf8_downgrade (string, 0);
1147 else 1393 else
1148 sv_utf8_upgrade (string); 1394 sv_utf8_upgrade (string);
1149 1395
1150 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP 1396 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
1151 1397
1152 dec.flags = flags; 1398 dec.json = *json;
1153 dec.cur = SvPVX (string); 1399 dec.cur = SvPVX (string);
1154 dec.end = SvEND (string); 1400 dec.end = SvEND (string);
1155 dec.err = 0; 1401 dec.err = 0;
1156 dec.depth = 0; 1402 dec.depth = 0;
1157 dec.maxdepth = DEC_DEPTH (dec.flags); 1403 dec.maxdepth = DEC_DEPTH (dec.json.flags);
1404
1405 if (dec.json.cb_object || dec.json.cb_sk_object)
1406 dec.json.flags |= F_HOOK;
1158 1407
1159 *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);
1160 sv = decode_sv (&dec); 1411 sv = decode_sv (&dec);
1161 1412
1162 if (!(offset_return || !sv)) 1413 if (!(offset_return || !sv))
1163 { 1414 {
1164 // check for trailing garbage 1415 // check for trailing garbage
1172 } 1423 }
1173 } 1424 }
1174 1425
1175 if (offset_return || !sv) 1426 if (offset_return || !sv)
1176 { 1427 {
1177 offset = dec.flags & F_UTF8 1428 offset = dec.json.flags & F_UTF8
1178 ? dec.cur - SvPVX (string) 1429 ? dec.cur - SvPVX (string)
1179 : utf8_distance (dec.cur, SvPVX (string)); 1430 : utf8_distance (dec.cur, SvPVX (string));
1180 1431
1181 if (offset_return) 1432 if (offset_return)
1182 *offset_return = offset; 1433 *offset_return = offset;
1201 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); 1452 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
1202 } 1453 }
1203 1454
1204 sv = sv_2mortal (sv); 1455 sv = sv_2mortal (sv);
1205 1456
1206 if (!(dec.flags & F_ALLOW_NONREF) && !SvROK (sv)) 1457 if (!(dec.json.flags & F_ALLOW_NONREF) && !SvROK (sv))
1207 croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)"); 1458 croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)");
1208 1459
1209 return sv; 1460 return sv;
1210} 1461}
1211 1462
1232 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);
1233} 1484}
1234 1485
1235PROTOTYPES: DISABLE 1486PROTOTYPES: DISABLE
1236 1487
1237SV *new (char *dummy) 1488void CLONE (...)
1238 CODE: 1489 CODE:
1239 RETVAL = sv_bless (newRV_noinc (newSVuv (F_DEFAULT)), json_stash); 1490 json_stash = 0;
1240 OUTPUT: 1491 json_boolean_stash = 0;
1241 RETVAL
1242 1492
1493void new (char *klass)
1494 PPCODE:
1495{
1496 SV *pv = NEWSV (0, sizeof (JSON));
1497 SvPOK_only (pv);
1498 Zero (SvPVX (pv), 1, JSON);
1499 ((JSON *)SvPVX (pv))->flags = F_DEFAULT;
1500 XPUSHs (sv_2mortal (sv_bless (
1501 newRV_noinc (pv),
1502 strEQ (klass, "JSON::XS") ? JSON_STASH : gv_stashpv (klass, 1)
1503 )));
1504}
1505
1243SV *ascii (SV *self, int enable = 1) 1506void ascii (JSON *self, int enable = 1)
1244 ALIAS: 1507 ALIAS:
1245 ascii = F_ASCII 1508 ascii = F_ASCII
1246 latin1 = F_LATIN1 1509 latin1 = F_LATIN1
1247 utf8 = F_UTF8 1510 utf8 = F_UTF8
1248 indent = F_INDENT 1511 indent = F_INDENT
1252 pretty = F_PRETTY 1515 pretty = F_PRETTY
1253 allow_nonref = F_ALLOW_NONREF 1516 allow_nonref = F_ALLOW_NONREF
1254 shrink = F_SHRINK 1517 shrink = F_SHRINK
1255 allow_blessed = F_ALLOW_BLESSED 1518 allow_blessed = F_ALLOW_BLESSED
1256 convert_blessed = F_CONV_BLESSED 1519 convert_blessed = F_CONV_BLESSED
1520 relaxed = F_RELAXED
1521 PPCODE:
1522{
1523 if (enable)
1524 self->flags |= ix;
1525 else
1526 self->flags &= ~ix;
1527
1528 XPUSHs (ST (0));
1529}
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
1548void max_depth (JSON *self, UV max_depth = 0x80000000UL)
1549 PPCODE:
1550{
1551 UV log2 = 0;
1552
1553 if (max_depth > 0x80000000UL) max_depth = 0x80000000UL;
1554
1555 while ((1UL << log2) < max_depth)
1556 ++log2;
1557
1558 self->flags = self->flags & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1559
1560 XPUSHs (ST (0));
1561}
1562
1563U32 get_max_depth (JSON *self)
1257 CODE: 1564 CODE:
1258{ 1565 RETVAL = DEC_DEPTH (self->flags);
1259 UV *uv = SvJSON (self);
1260 if (enable)
1261 *uv |= ix;
1262 else
1263 *uv &= ~ix;
1264
1265 RETVAL = newSVsv (self);
1266}
1267 OUTPUT: 1566 OUTPUT:
1268 RETVAL 1567 RETVAL
1269 1568
1270SV *max_depth (SV *self, UV max_depth = 0x80000000UL) 1569void max_size (JSON *self, UV max_size = 0)
1570 PPCODE:
1571{
1572 UV log2 = 0;
1573
1574 if (max_size > 0x80000000UL) max_size = 0x80000000UL;
1575 if (max_size == 1) max_size = 2;
1576
1577 while ((1UL << log2) < max_size)
1578 ++log2;
1579
1580 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE);
1581
1582 XPUSHs (ST (0));
1583}
1584
1585int get_max_size (JSON *self)
1271 CODE: 1586 CODE:
1272{ 1587 RETVAL = DEC_SIZE (self->flags);
1273 UV *uv = SvJSON (self);
1274 UV log2 = 0;
1275
1276 if (max_depth > 0x80000000UL) max_depth = 0x80000000UL;
1277
1278 while ((1UL << log2) < max_depth)
1279 ++log2;
1280
1281 *uv = *uv & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1282
1283 RETVAL = newSVsv (self);
1284}
1285 OUTPUT: 1588 OUTPUT:
1286 RETVAL 1589 RETVAL
1287 1590
1288SV *max_size (SV *self, UV max_size = 0) 1591void filter_json_object (JSON *self, SV *cb = &PL_sv_undef)
1289 CODE:
1290{
1291 UV *uv = SvJSON (self);
1292 UV log2 = 0;
1293
1294 if (max_size > 0x80000000UL) max_size = 0x80000000UL;
1295 if (max_size == 1) max_size = 2;
1296
1297 while ((1UL << log2) < max_size)
1298 ++log2;
1299
1300 *uv = *uv & ~F_MAXSIZE | (log2 << S_MAXSIZE);
1301
1302 RETVAL = newSVsv (self);
1303}
1304 OUTPUT:
1305 RETVAL
1306
1307void encode (SV *self, SV *scalar)
1308 PPCODE: 1592 PPCODE:
1309 XPUSHs (encode_json (scalar, *SvJSON (self))); 1593{
1594 SvREFCNT_dec (self->cb_object);
1595 self->cb_object = SvOK (cb) ? newSVsv (cb) : 0;
1310 1596
1311void decode (SV *self, SV *jsonstr) 1597 XPUSHs (ST (0));
1598}
1599
1600void filter_json_single_key_object (JSON *self, SV *key, SV *cb = &PL_sv_undef)
1312 PPCODE: 1601 PPCODE:
1602{
1603 if (!self->cb_sk_object)
1604 self->cb_sk_object = newHV ();
1605
1606 if (SvOK (cb))
1607 hv_store_ent (self->cb_sk_object, key, newSVsv (cb), 0);
1608 else
1609 {
1610 hv_delete_ent (self->cb_sk_object, key, G_DISCARD, 0);
1611
1612 if (!HvKEYS (self->cb_sk_object))
1613 {
1614 SvREFCNT_dec (self->cb_sk_object);
1615 self->cb_sk_object = 0;
1616 }
1617 }
1618
1619 XPUSHs (ST (0));
1620}
1621
1622void encode (JSON *self, SV *scalar)
1623 PPCODE:
1624 XPUSHs (encode_json (scalar, self));
1625
1626void decode (JSON *self, SV *jsonstr)
1627 PPCODE:
1313 XPUSHs (decode_json (jsonstr, *SvJSON (self), 0)); 1628 XPUSHs (decode_json (jsonstr, self, 0));
1314 1629
1315void decode_prefix (SV *self, SV *jsonstr) 1630void decode_prefix (JSON *self, SV *jsonstr)
1316 PPCODE: 1631 PPCODE:
1317{ 1632{
1318 UV offset; 1633 UV offset;
1319 EXTEND (SP, 2); 1634 EXTEND (SP, 2);
1320 PUSHs (decode_json (jsonstr, *SvJSON (self), &offset)); 1635 PUSHs (decode_json (jsonstr, self, &offset));
1321 PUSHs (sv_2mortal (newSVuv (offset))); 1636 PUSHs (sv_2mortal (newSVuv (offset)));
1322} 1637}
1323 1638
1639void DESTROY (JSON *self)
1640 CODE:
1641 SvREFCNT_dec (self->cb_sk_object);
1642 SvREFCNT_dec (self->cb_object);
1643
1324PROTOTYPES: ENABLE 1644PROTOTYPES: ENABLE
1325 1645
1326void to_json (SV *scalar) 1646void encode_json (SV *scalar)
1327 ALIAS:
1328 objToJson = 0
1329 PPCODE: 1647 PPCODE:
1648{
1649 JSON json = { F_DEFAULT | F_UTF8 };
1330 XPUSHs (encode_json (scalar, F_DEFAULT | F_UTF8)); 1650 XPUSHs (encode_json (scalar, &json));
1651}
1331 1652
1332void from_json (SV *jsonstr) 1653void decode_json (SV *jsonstr)
1333 ALIAS:
1334 jsonToObj = 0
1335 PPCODE: 1654 PPCODE:
1655{
1656 JSON json = { F_DEFAULT | F_UTF8 };
1336 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8, 0)); 1657 XPUSHs (decode_json (jsonstr, &json, 0));
1658}
1337 1659

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines