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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines