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.40 by root, Tue Jun 12 01:27:02 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
15// some old perls do not have this, try to make it work, no
16// guarentees, though. if it breaks, you get to keep the pieces.
17#ifndef UTF8_MAXBYTES
18# define UTF8_MAXBYTES 13
19#endif
20
14#define F_ASCII 0x00000001UL 21#define F_ASCII 0x00000001UL
15#define F_LATIN1 0x00000002UL 22#define F_LATIN1 0x00000002UL
16#define F_UTF8 0x00000004UL 23#define F_UTF8 0x00000004UL
17#define F_INDENT 0x00000008UL 24#define F_INDENT 0x00000008UL
18#define F_CANONICAL 0x00000010UL 25#define F_CANONICAL 0x00000010UL
19#define F_SPACE_BEFORE 0x00000020UL 26#define F_SPACE_BEFORE 0x00000020UL
20#define F_SPACE_AFTER 0x00000040UL 27#define F_SPACE_AFTER 0x00000040UL
21#define F_ALLOW_NONREF 0x00000100UL 28#define F_ALLOW_NONREF 0x00000100UL
22#define F_SHRINK 0x00000200UL 29#define F_SHRINK 0x00000200UL
30#define F_ALLOW_BLESSED 0x00000400UL
31#define F_CONV_BLESSED 0x00000800UL
32#define F_RELAXED 0x00001000UL
33
23#define F_MAXDEPTH 0xf8000000UL 34#define F_MAXDEPTH 0xf8000000UL
24#define S_MAXDEPTH 27 35#define S_MAXDEPTH 27
36#define F_MAXSIZE 0x01f00000UL
37#define S_MAXSIZE 20
38#define F_HOOK 0x00080000UL // some hooks exist, so slow-path processing
25 39
26#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH)) 40#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH))
27 41#define DEC_SIZE(flags) (1UL << ((flags & F_MAXSIZE ) >> S_MAXSIZE ))
28// F_SELFCONVERT? <=> to_json/toJson
29// F_BLESSED? <=> { $__class__$ => }
30 42
31#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER 43#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER
32#define F_DEFAULT (9UL << S_MAXDEPTH) 44#define F_DEFAULT (9UL << S_MAXDEPTH)
33 45
34#define INIT_SIZE 32 // initial scalar size to be allocated 46#define INIT_SIZE 32 // initial scalar size to be allocated
38 50
39#define SB do { 51#define SB do {
40#define SE } while (0) 52#define SE } while (0)
41 53
42#if __GNUC__ >= 3 54#if __GNUC__ >= 3
43# define expect(expr,value) __builtin_expect ((expr),(value)) 55# define expect(expr,value) __builtin_expect ((expr), (value))
44# define inline inline 56# define INLINE static inline
45#else 57#else
46# define expect(expr,value) (expr) 58# define expect(expr,value) (expr)
47# define inline static 59# define INLINE static
48#endif 60#endif
49 61
50#define expect_false(expr) expect ((expr) != 0, 0) 62#define expect_false(expr) expect ((expr) != 0, 0)
51#define expect_true(expr) expect ((expr) != 0, 1) 63#define expect_true(expr) expect ((expr) != 0, 1)
52 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
53static HV *json_stash; // JSON::XS:: 77static HV *json_stash, *json_boolean_stash; // JSON::XS::
78static SV *json_true, *json_false;
79
80typedef struct {
81 U32 flags;
82 SV *cb_object;
83 HV *cb_sk_object;
84} JSON;
54 85
55///////////////////////////////////////////////////////////////////////////// 86/////////////////////////////////////////////////////////////////////////////
56// utility functions 87// utility functions
57 88
58static UV * 89INLINE void
59SvJSON (SV *sv)
60{
61 if (!(SvROK (sv) && SvOBJECT (SvRV (sv)) && SvSTASH (SvRV (sv)) == json_stash))
62 croak ("object is not of type JSON::XS");
63
64 return &SvUVX (SvRV (sv));
65}
66
67static void
68shrink (SV *sv) 90shrink (SV *sv)
69{ 91{
70 sv_utf8_downgrade (sv, 1); 92 sv_utf8_downgrade (sv, 1);
71 if (SvLEN (sv) > SvCUR (sv) + 1) 93 if (SvLEN (sv) > SvCUR (sv) + 1)
72 { 94 {
81// 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
82// case of an error. 104// case of an error.
83// we special-case "safe" characters from U+80 .. U+7FF, 105// we special-case "safe" characters from U+80 .. U+7FF,
84// but use the very good perl function to parse anything else. 106// but use the very good perl function to parse anything else.
85// note that we never call this function for a ascii codepoints 107// note that we never call this function for a ascii codepoints
86inline UV 108INLINE UV
87decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen) 109decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
88{ 110{
89 if (expect_false (s[0] > 0xdf || s[0] < 0xc2)) 111 if (expect_true (len >= 2
90 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY); 112 && IN_RANGE_INC (char, s[0], 0xc2, 0xdf)
91 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf) 113 && IN_RANGE_INC (char, s[1], 0x80, 0xbf)))
92 { 114 {
93 *clen = 2; 115 *clen = 2;
94 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f); 116 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
95 } 117 }
96 else 118 else
97 { 119 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY);
98 *clen = (STRLEN)-1; 120}
99 return (UV)-1; 121
100 } 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;
101} 144}
102 145
103///////////////////////////////////////////////////////////////////////////// 146/////////////////////////////////////////////////////////////////////////////
104// encoder 147// encoder
105 148
107typedef struct 150typedef struct
108{ 151{
109 char *cur; // SvPVX (sv) + current output position 152 char *cur; // SvPVX (sv) + current output position
110 char *end; // SvEND (sv) 153 char *end; // SvEND (sv)
111 SV *sv; // result scalar 154 SV *sv; // result scalar
112 U32 flags; // F_* 155 JSON json;
113 U32 indent; // indentation level 156 U32 indent; // indentation level
114 U32 maxdepth; // max. indentation/recursion level 157 U32 maxdepth; // max. indentation/recursion level
158 UV limit; // escape character values >= this value when encoding
115} enc_t; 159} enc_t;
116 160
117inline void 161INLINE void
118need (enc_t *enc, STRLEN len) 162need (enc_t *enc, STRLEN len)
119{ 163{
120 if (expect_false (enc->cur + len >= enc->end)) 164 if (expect_false (enc->cur + len >= enc->end))
121 { 165 {
122 STRLEN cur = enc->cur - SvPVX (enc->sv); 166 STRLEN cur = enc->cur - SvPVX (enc->sv);
124 enc->cur = SvPVX (enc->sv) + cur; 168 enc->cur = SvPVX (enc->sv) + cur;
125 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1; 169 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
126 } 170 }
127} 171}
128 172
129inline void 173INLINE void
130encode_ch (enc_t *enc, char ch) 174encode_ch (enc_t *enc, char ch)
131{ 175{
132 need (enc, 1); 176 need (enc, 1);
133 *enc->cur++ = ch; 177 *enc->cur++ = ch;
134} 178}
188 { 232 {
189 uch = ch; 233 uch = ch;
190 clen = 1; 234 clen = 1;
191 } 235 }
192 236
193 if (uch > 0x10FFFFUL) 237 if (uch < 0x80/*0x20*/ || uch >= enc->limit)
194 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
195
196 if (uch < 0x80 || enc->flags & F_ASCII || (enc->flags & F_LATIN1 && uch > 0xFF))
197 { 238 {
198 if (uch > 0xFFFFUL) 239 if (uch >= 0x10000UL)
199 { 240 {
241 if (uch >= 0x110000UL)
242 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
243
200 need (enc, len += 11); 244 need (enc, len += 11);
201 sprintf (enc->cur, "\\u%04x\\u%04x", 245 sprintf (enc->cur, "\\u%04x\\u%04x",
202 (int)((uch - 0x10000) / 0x400 + 0xD800), 246 (int)((uch - 0x10000) / 0x400 + 0xD800),
203 (int)((uch - 0x10000) % 0x400 + 0xDC00)); 247 (int)((uch - 0x10000) % 0x400 + 0xDC00));
204 enc->cur += 12; 248 enc->cur += 12;
215 *enc->cur++ = hexdigit [(uch >> 0) & 15]; 259 *enc->cur++ = hexdigit [(uch >> 0) & 15];
216 } 260 }
217 261
218 str += clen; 262 str += clen;
219 } 263 }
220 else if (enc->flags & F_LATIN1) 264 else if (enc->json.flags & F_LATIN1)
221 { 265 {
222 *enc->cur++ = uch; 266 *enc->cur++ = uch;
223 str += clen; 267 str += clen;
224 } 268 }
225 else if (is_utf8) 269 else if (is_utf8)
232 while (--clen); 276 while (--clen);
233 } 277 }
234 else 278 else
235 { 279 {
236 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
237 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); 281 enc->cur = encode_utf8 (enc->cur, uch);
238 ++str; 282 ++str;
239 } 283 }
240 } 284 }
241 } 285 }
242 } 286 }
243 287
244 --len; 288 --len;
245 } 289 }
246} 290}
247 291
248inline void 292INLINE void
249encode_indent (enc_t *enc) 293encode_indent (enc_t *enc)
250{ 294{
251 if (enc->flags & F_INDENT) 295 if (enc->json.flags & F_INDENT)
252 { 296 {
253 int spaces = enc->indent * INDENT_STEP; 297 int spaces = enc->indent * INDENT_STEP;
254 298
255 need (enc, spaces); 299 need (enc, spaces);
256 memset (enc->cur, ' ', spaces); 300 memset (enc->cur, ' ', spaces);
257 enc->cur += spaces; 301 enc->cur += spaces;
258 } 302 }
259} 303}
260 304
261inline void 305INLINE void
262encode_space (enc_t *enc) 306encode_space (enc_t *enc)
263{ 307{
264 need (enc, 1); 308 need (enc, 1);
265 encode_ch (enc, ' '); 309 encode_ch (enc, ' ');
266} 310}
267 311
268inline void 312INLINE void
269encode_nl (enc_t *enc) 313encode_nl (enc_t *enc)
270{ 314{
271 if (enc->flags & F_INDENT) 315 if (enc->json.flags & F_INDENT)
272 { 316 {
273 need (enc, 1); 317 need (enc, 1);
274 encode_ch (enc, '\n'); 318 encode_ch (enc, '\n');
275 } 319 }
276} 320}
277 321
278inline void 322INLINE void
279encode_comma (enc_t *enc) 323encode_comma (enc_t *enc)
280{ 324{
281 encode_ch (enc, ','); 325 encode_ch (enc, ',');
282 326
283 if (enc->flags & F_INDENT) 327 if (enc->json.flags & F_INDENT)
284 encode_nl (enc); 328 encode_nl (enc);
285 else if (enc->flags & F_SPACE_AFTER) 329 else if (enc->json.flags & F_SPACE_AFTER)
286 encode_space (enc); 330 encode_space (enc);
287} 331}
288 332
289static void encode_sv (enc_t *enc, SV *sv); 333static void encode_sv (enc_t *enc, SV *sv);
290 334
294 int i, len = av_len (av); 338 int i, len = av_len (av);
295 339
296 if (enc->indent >= enc->maxdepth) 340 if (enc->indent >= enc->maxdepth)
297 croak ("data structure too deep (hit recursion limit)"); 341 croak ("data structure too deep (hit recursion limit)");
298 342
299 encode_ch (enc, '['); encode_nl (enc); 343 encode_ch (enc, '[');
300 ++enc->indent; 344
345 if (len >= 0)
346 {
347 encode_nl (enc); ++enc->indent;
301 348
302 for (i = 0; i <= len; ++i) 349 for (i = 0; i <= len; ++i)
303 { 350 {
351 SV **svp = av_fetch (av, i, 0);
352
304 encode_indent (enc); 353 encode_indent (enc);
305 encode_sv (enc, *av_fetch (av, i, 0));
306 354
355 if (svp)
356 encode_sv (enc, *svp);
357 else
358 encode_str (enc, "null", 4, 0);
359
307 if (i < len) 360 if (i < len)
308 encode_comma (enc); 361 encode_comma (enc);
309 } 362 }
310 363
364 encode_nl (enc); --enc->indent; encode_indent (enc);
365 }
366
311 encode_nl (enc); 367 encode_ch (enc, ']');
312
313 --enc->indent;
314 encode_indent (enc); encode_ch (enc, ']');
315} 368}
316 369
317static void 370static void
318encode_he (enc_t *enc, HE *he) 371encode_hk (enc_t *enc, HE *he)
319{ 372{
320 encode_ch (enc, '"'); 373 encode_ch (enc, '"');
321 374
322 if (HeKLEN (he) == HEf_SVKEY) 375 if (HeKLEN (he) == HEf_SVKEY)
323 { 376 {
333 else 386 else
334 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he)); 387 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he));
335 388
336 encode_ch (enc, '"'); 389 encode_ch (enc, '"');
337 390
338 if (enc->flags & F_SPACE_BEFORE) encode_space (enc); 391 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc);
339 encode_ch (enc, ':'); 392 encode_ch (enc, ':');
340 if (enc->flags & F_SPACE_AFTER ) encode_space (enc); 393 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc);
341 encode_sv (enc, HeVAL (he));
342} 394}
343 395
344// compare hash entries, used when all keys are bytestrings 396// compare hash entries, used when all keys are bytestrings
345static int 397static int
346he_cmp_fast (const void *a_, const void *b_) 398he_cmp_fast (const void *a_, const void *b_)
351 HE *b = *(HE **)b_; 403 HE *b = *(HE **)b_;
352 404
353 STRLEN la = HeKLEN (a); 405 STRLEN la = HeKLEN (a);
354 STRLEN lb = HeKLEN (b); 406 STRLEN lb = HeKLEN (b);
355 407
356 if (!(cmp = memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb))) 408 if (!(cmp = memcmp (HeKEY (b), HeKEY (a), lb < la ? lb : la)))
357 cmp = la - lb; 409 cmp = lb - la;
358 410
359 return cmp; 411 return cmp;
360} 412}
361 413
362// 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
363static int 415static int
364he_cmp_slow (const void *a, const void *b) 416he_cmp_slow (const void *a, const void *b)
365{ 417{
366 return sv_cmp (HeSVKEY_force (*(HE **)a), HeSVKEY_force (*(HE **)b)); 418 return sv_cmp (HeSVKEY_force (*(HE **)b), HeSVKEY_force (*(HE **)a));
367} 419}
368 420
369static void 421static void
370encode_hv (enc_t *enc, HV *hv) 422encode_hv (enc_t *enc, HV *hv)
371{ 423{
424 HE *he;
372 int count, i; 425 int count;
373 426
374 if (enc->indent >= enc->maxdepth) 427 if (enc->indent >= enc->maxdepth)
375 croak ("data structure too deep (hit recursion limit)"); 428 croak ("data structure too deep (hit recursion limit)");
376 429
377 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent; 430 encode_ch (enc, '{');
378 431
379 if ((count = hv_iterinit (hv)))
380 {
381 // for canonical output we have to sort by keys first 432 // for canonical output we have to sort by keys first
382 // actually, this is mostly due to the stupid so-called 433 // actually, this is mostly due to the stupid so-called
383 // security workaround added somewhere in 5.8.x. 434 // security workaround added somewhere in 5.8.x.
384 // that randomises hash orderings 435 // that randomises hash orderings
385 if (enc->flags & F_CANONICAL) 436 if (enc->json.flags & F_CANONICAL)
437 {
438 int count = hv_iterinit (hv);
439
440 if (SvMAGICAL (hv))
386 { 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 {
387 int fast = 1; 456 int i, fast = 1;
388 HE *he;
389#if defined(__BORLANDC__) || defined(_MSC_VER) 457#if defined(__BORLANDC__) || defined(_MSC_VER)
390 HE **hes = _alloca (count * sizeof (HE)); 458 HE **hes = _alloca (count * sizeof (HE));
391#else 459#else
392 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
393#endif 461#endif
420 488
421 FREETMPS; 489 FREETMPS;
422 LEAVE; 490 LEAVE;
423 } 491 }
424 492
425 for (i = 0; i < count; ++i) 493 encode_nl (enc); ++enc->indent;
494
495 while (count--)
426 { 496 {
427 encode_indent (enc); 497 encode_indent (enc);
498 he = hes [count];
428 encode_he (enc, hes [i]); 499 encode_hk (enc, he);
500 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
429 501
430 if (i < count - 1) 502 if (count)
431 encode_comma (enc); 503 encode_comma (enc);
432 } 504 }
433 505
506 encode_nl (enc); --enc->indent; encode_indent (enc);
507 }
508 }
509 else
510 {
511 if (hv_iterinit (hv) || SvMAGICAL (hv))
512 if ((he = hv_iternext (hv)))
513 {
514 encode_nl (enc); ++enc->indent;
515
516 for (;;)
517 {
434 encode_nl (enc); 518 encode_indent (enc);
519 encode_hk (enc, he);
520 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
521
522 if (!(he = hv_iternext (hv)))
523 break;
524
525 encode_comma (enc);
526 }
527
528 encode_nl (enc); --enc->indent; encode_indent (enc);
529 }
530 }
531
532 encode_ch (enc, '}');
533}
534
535// encode objects, arrays and special \0=false and \1=true values.
536static void
537encode_rv (enc_t *enc, SV *sv)
538{
539 svtype svt;
540
541 SvGETMAGIC (sv);
542 svt = SvTYPE (sv);
543
544 if (expect_false (SvOBJECT (sv)))
545 {
546 HV *stash = !JSON_SLOW || json_boolean_stash
547 ? json_boolean_stash
548 : gv_stashpv ("JSON::XS::Boolean", 1);
549
550 if (SvSTASH (sv) == stash)
551 {
552 if (SvIV (sv))
553 encode_str (enc, "true", 4, 0);
554 else
555 encode_str (enc, "false", 5, 0);
435 } 556 }
436 else 557 else
437 { 558 {
438 HE *he = hv_iternext (hv); 559#if 0
439 560 if (0 && sv_derived_from (rv, "JSON::Literal"))
440 for (;;)
441 { 561 {
442 encode_indent (enc); 562 // not yet
443 encode_he (enc, he);
444
445 if (!(he = hv_iternext (hv)))
446 break;
447
448 encode_comma (enc);
449 } 563 }
564#endif
565 if (enc->json.flags & F_CONV_BLESSED)
566 {
567 // we re-bless the reference to get overload and other niceties right
568 GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 0);
450 569
570 if (to_json)
571 {
572 dSP;
573
574 ENTER; SAVETMPS; PUSHMARK (SP);
575 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv)));
576
577 // calling with G_SCALAR ensures that we always get a 1 return value
578 PUTBACK;
579 call_sv ((SV *)GvCV (to_json), G_SCALAR);
580 SPAGAIN;
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
451 encode_nl (enc); 589 encode_sv (enc, sv);
590
591 FREETMPS; LEAVE;
592 }
593 else if (enc->json.flags & F_ALLOW_BLESSED)
594 encode_str (enc, "null", 4, 0);
595 else
596 croak ("encountered object '%s', but neither allow_blessed enabled nor TO_JSON method available on it",
597 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
598 }
599 else if (enc->json.flags & F_ALLOW_BLESSED)
600 encode_str (enc, "null", 4, 0);
601 else
602 croak ("encountered object '%s', but neither allow_blessed nor convert_blessed settings are enabled",
603 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
452 } 604 }
453 } 605 }
454
455 --enc->indent; encode_indent (enc); encode_ch (enc, '}');
456}
457
458// encode objects, arrays and special \0=false and \1=true values.
459static void
460encode_rv (enc_t *enc, SV *sv)
461{
462 svtype svt;
463
464 SvGETMAGIC (sv);
465 svt = SvTYPE (sv);
466
467 if (svt == SVt_PVHV) 606 else if (svt == SVt_PVHV)
468 encode_hv (enc, (HV *)sv); 607 encode_hv (enc, (HV *)sv);
469 else if (svt == SVt_PVAV) 608 else if (svt == SVt_PVAV)
470 encode_av (enc, (AV *)sv); 609 encode_av (enc, (AV *)sv);
471 else if (svt < SVt_PVAV) 610 else if (svt < SVt_PVAV)
472 { 611 {
473 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')
474 encode_str (enc, "false", 5, 0); 618 encode_str (enc, "false", 5, 0);
475 else if (SvNIOK (sv) && SvIV (sv) == 1)
476 encode_str (enc, "true", 4, 0);
477 else 619 else
478 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",
479 SvPV_nolen (sv_2mortal (newRV_inc (sv)))); 621 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
480 } 622 }
481 else 623 else
503 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur); 645 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
504 enc->cur += strlen (enc->cur); 646 enc->cur += strlen (enc->cur);
505 } 647 }
506 else if (SvIOKp (sv)) 648 else if (SvIOKp (sv))
507 { 649 {
508 // 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
509 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)
510 { 655 {
511 // large integer, use the (rather slow) snprintf way. 656 // large integer, use the (rather slow) snprintf way.
512 need (enc, sizeof (UV) * 3); 657 need (enc, sizeof (UV) * 5 / 2 + 1); // CHAR_BIT is at least 8
513 enc->cur += 658 enc->cur +=
514 SvIsUV(sv) 659 SvIsUV(sv)
515 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv)) 660 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv))
516 : snprintf (enc->cur, sizeof (UV) * 3, "%"IVdf, (IV)SvIVX (sv)); 661 : snprintf (enc->cur, sizeof (UV) * 3, "%"IVdf, (IV)SvIVX (sv));
517 } 662 }
518 else 663 else
519 { 664 {
520 // optimise the "small number case" 665 // optimise the "small number case"
521 // 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
522 I32 i = SvIV (sv); 668 I32 i = SvIVX (sv);
523 U32 u; 669 U32 u;
524 char digit, nz = 0; 670 char digit, nz = 0;
525 671
526 need (enc, 6); 672 need (enc, 6);
527 673
551 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",
552 SvPV_nolen (sv), SvFLAGS (sv)); 698 SvPV_nolen (sv), SvFLAGS (sv));
553} 699}
554 700
555static SV * 701static SV *
556encode_json (SV *scalar, U32 flags) 702encode_json (SV *scalar, JSON *json)
557{ 703{
558 enc_t enc; 704 enc_t enc;
559 705
560 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar)) 706 if (!(json->flags & F_ALLOW_NONREF) && !SvROK (scalar))
561 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)");
562 708
563 enc.flags = flags; 709 enc.json = *json;
564 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 710 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
565 enc.cur = SvPVX (enc.sv); 711 enc.cur = SvPVX (enc.sv);
566 enc.end = SvEND (enc.sv); 712 enc.end = SvEND (enc.sv);
567 enc.indent = 0; 713 enc.indent = 0;
568 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;
569 718
570 SvPOK_only (enc.sv); 719 SvPOK_only (enc.sv);
571 encode_sv (&enc, scalar); 720 encode_sv (&enc, scalar);
572 721
573 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); 722 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
574 *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
575 724
576 if (!(flags & (F_ASCII | F_LATIN1 | F_UTF8))) 725 if (!(enc.json.flags & (F_ASCII | F_LATIN1 | F_UTF8)))
577 SvUTF8_on (enc.sv); 726 SvUTF8_on (enc.sv);
578 727
579 if (enc.flags & F_SHRINK) 728 if (enc.json.flags & F_SHRINK)
580 shrink (enc.sv); 729 shrink (enc.sv);
581 730
582 return enc.sv; 731 return enc.sv;
583} 732}
584 733
589typedef struct 738typedef struct
590{ 739{
591 char *cur; // current parser pointer 740 char *cur; // current parser pointer
592 char *end; // end of input string 741 char *end; // end of input string
593 const char *err; // parse error, if != 0 742 const char *err; // parse error, if != 0
594 U32 flags; // F_* 743 JSON json;
595 U32 depth; // recursion depth 744 U32 depth; // recursion depth
596 U32 maxdepth; // recursion depth limit 745 U32 maxdepth; // recursion depth limit
597} dec_t; 746} dec_t;
598 747
599inline 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
600decode_ws (dec_t *dec) 758decode_ws (dec_t *dec)
601{ 759{
602 for (;;) 760 for (;;)
603 { 761 {
604 char ch = *dec->cur; 762 char ch = *dec->cur;
605 763
606 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 }
607 || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)) 776 else if (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)
608 break; 777 break; // parse error, but let higher level handle it, gives better error messages
609 778
610 ++dec->cur; 779 ++dec->cur;
611 } 780 }
612} 781}
613 782
719 888
720 if (hi >= 0x80) 889 if (hi >= 0x80)
721 { 890 {
722 utf8 = 1; 891 utf8 = 1;
723 892
724 cur = (char *)uvuni_to_utf8_flags (cur, hi, 0); 893 cur = encode_utf8 (cur, hi);
725 } 894 }
726 else 895 else
727 *cur++ = hi; 896 *cur++ = hi;
728 } 897 }
729 break; 898 break;
731 default: 900 default:
732 --dec_cur; 901 --dec_cur;
733 ERR ("illegal backslash escape sequence in string"); 902 ERR ("illegal backslash escape sequence in string");
734 } 903 }
735 } 904 }
736 else if (expect_true (ch >= 0x20 && ch <= 0x7f)) 905 else if (expect_true (ch >= 0x20 && ch < 0x80))
737 *cur++ = ch; 906 *cur++ = ch;
738 else if (ch >= 0x80) 907 else if (ch >= 0x80)
739 { 908 {
740 STRLEN clen; 909 STRLEN clen;
741 UV uch; 910 UV uch;
862 is_nv = 1; 1031 is_nv = 1;
863 } 1032 }
864 1033
865 if (!is_nv) 1034 if (!is_nv)
866 { 1035 {
1036 int len = dec->cur - start;
1037
867 // 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
868 if (*start == '-') 1039 if (*start == '-')
869 switch (dec->cur - start) 1040 switch (len)
870 { 1041 {
871 case 2: return newSViv (-( start [1] - '0' * 1)); 1042 case 2: return newSViv (-( start [1] - '0' * 1));
872 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11)); 1043 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11));
873 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));
874 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));
875 } 1047 }
876 else 1048 else
877 switch (dec->cur - start) 1049 switch (len)
878 { 1050 {
879 case 1: return newSViv ( start [0] - '0' * 1); 1051 case 1: return newSViv ( start [0] - '0' * 1);
880 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11); 1052 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11);
881 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);
882 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);
883 } 1056 }
884 1057
885 { 1058 {
886 UV uv; 1059 UV uv;
887 int numtype = grok_number (start, dec->cur - start, &uv); 1060 int numtype = grok_number (start, len, &uv);
888 if (numtype & IS_NUMBER_IN_UV) 1061 if (numtype & IS_NUMBER_IN_UV)
889 if (numtype & IS_NUMBER_NEG) 1062 if (numtype & IS_NUMBER_NEG)
890 { 1063 {
891 if (uv < (UV)IV_MIN) 1064 if (uv < (UV)IV_MIN)
892 return newSViv (-(IV)uv); 1065 return newSViv (-(IV)uv);
893 } 1066 }
894 else 1067 else
895 return newSVuv (uv); 1068 return newSVuv (uv);
896
897 // here would likely be the place for bigint support
898 } 1069 }
899 }
900 1070
901 // 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
902 return newSVnv (Atof (start)); 1087 return newSVnv (Atof (start));
903 1088
904fail: 1089fail:
905 return 0; 1090 return 0;
906} 1091}
936 1121
937 if (*dec->cur != ',') 1122 if (*dec->cur != ',')
938 ERR (", or ] expected while parsing array"); 1123 ERR (", or ] expected while parsing array");
939 1124
940 ++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 }
941 } 1134 }
942 1135
943 DEC_DEC_DEPTH; 1136 DEC_DEC_DEPTH;
944 return newRV_noinc ((SV *)av); 1137 return newRV_noinc ((SV *)av);
945 1138
950} 1143}
951 1144
952static SV * 1145static SV *
953decode_hv (dec_t *dec) 1146decode_hv (dec_t *dec)
954{ 1147{
1148 SV *sv;
955 HV *hv = newHV (); 1149 HV *hv = newHV ();
956 1150
957 DEC_INC_DEPTH; 1151 DEC_INC_DEPTH;
958 decode_ws (dec); 1152 decode_ws (dec);
959 1153
960 if (*dec->cur == '}') 1154 if (*dec->cur == '}')
961 ++dec->cur; 1155 ++dec->cur;
962 else 1156 else
963 for (;;) 1157 for (;;)
964 { 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 {
965 SV *key, *value; 1167 SV *value;
1168 char *p = dec->cur;
1169 char *e = p + 24; // only try up to 24 bytes
966 1170
967 decode_ws (dec); EXPECT_CH ('"'); 1171 for (;;)
968
969 key = decode_str (dec);
970 if (!key)
971 goto fail;
972
973 decode_ws (dec); EXPECT_CH (':');
974
975 value = decode_sv (dec);
976 if (!value)
977 { 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);
978 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)
979 goto fail; 1208 goto fail;
1209
1210 hv_store (hv, key, len, value, 0);
1211
1212 break;
1213 }
1214
1215 ++p;
980 } 1216 }
981 1217 }
982 hv_store_ent (hv, key, value, 0);
983 SvREFCNT_dec (key);
984 1218
985 decode_ws (dec); 1219 decode_ws (dec);
986 1220
987 if (*dec->cur == '}') 1221 if (*dec->cur == '}')
988 { 1222 {
992 1226
993 if (*dec->cur != ',') 1227 if (*dec->cur != ',')
994 ERR (", or } expected while parsing object/hash"); 1228 ERR (", or } expected while parsing object/hash");
995 1229
996 ++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 }
997 } 1239 }
998 1240
999 DEC_DEC_DEPTH; 1241 DEC_DEC_DEPTH;
1000 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;
1001 1303
1002fail: 1304fail:
1003 SvREFCNT_dec (hv); 1305 SvREFCNT_dec (hv);
1004 DEC_DEC_DEPTH; 1306 DEC_DEC_DEPTH;
1005 return 0; 1307 return 0;
1006} 1308}
1007 1309
1008static SV * 1310static SV *
1009decode_sv (dec_t *dec) 1311decode_sv (dec_t *dec)
1010{ 1312{
1011 decode_ws (dec);
1012
1013 // the beauty of JSON: you need exactly one character lookahead 1313 // the beauty of JSON: you need exactly one character lookahead
1014 // to parse anything. 1314 // to parse everything.
1015 switch (*dec->cur) 1315 switch (*dec->cur)
1016 { 1316 {
1017 case '"': ++dec->cur; return decode_str (dec); 1317 case '"': ++dec->cur; return decode_str (dec);
1018 case '[': ++dec->cur; return decode_av (dec); 1318 case '[': ++dec->cur; return decode_av (dec);
1019 case '{': ++dec->cur; return decode_hv (dec); 1319 case '{': ++dec->cur; return decode_hv (dec);
1020 1320
1021 case '-': 1321 case '-':
1022 case '0': case '1': case '2': case '3': case '4': 1322 case '0': case '1': case '2': case '3': case '4':
1023 case '5': case '6': case '7': case '8': case '9': 1323 case '5': case '6': case '7': case '8': case '9':
1024 return decode_num (dec); 1324 return decode_num (dec);
1025 1325
1026 case 't': 1326 case 't':
1027 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1327 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
1028 { 1328 {
1029 dec->cur += 4; 1329 dec->cur += 4;
1030 return newSViv (1); 1330#if JSON_SLOW
1331 json_true = get_sv ("JSON::XS::true", 1); SvREADONLY_on (json_true);
1332#endif
1333 return SvREFCNT_inc (json_true);
1031 } 1334 }
1032 else 1335 else
1033 ERR ("'true' expected"); 1336 ERR ("'true' expected");
1034 1337
1035 break; 1338 break;
1036 1339
1037 case 'f': 1340 case 'f':
1038 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1341 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
1039 { 1342 {
1040 dec->cur += 5; 1343 dec->cur += 5;
1041 return newSViv (0); 1344#if JSON_SLOW
1345 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1346#endif
1347 return SvREFCNT_inc (json_false);
1042 } 1348 }
1043 else 1349 else
1044 ERR ("'false' expected"); 1350 ERR ("'false' expected");
1045 1351
1046 break; 1352 break;
1064fail: 1370fail:
1065 return 0; 1371 return 0;
1066} 1372}
1067 1373
1068static SV * 1374static SV *
1069decode_json (SV *string, U32 flags, UV *offset_return) 1375decode_json (SV *string, JSON *json, UV *offset_return)
1070{ 1376{
1071 dec_t dec; 1377 dec_t dec;
1072 UV offset; 1378 UV offset;
1073 SV *sv; 1379 SV *sv;
1074 1380
1075 SvGETMAGIC (string); 1381 SvGETMAGIC (string);
1076 SvUPGRADE (string, SVt_PV); 1382 SvUPGRADE (string, SVt_PV);
1077 1383
1384 if (json->flags & F_MAXSIZE && SvCUR (string) > DEC_SIZE (json->flags))
1385 croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu",
1386 (unsigned long)SvCUR (string), (unsigned long)DEC_SIZE (json->flags));
1387
1078 if (flags & F_UTF8) 1388 if (json->flags & F_UTF8)
1079 sv_utf8_downgrade (string, 0); 1389 sv_utf8_downgrade (string, 0);
1080 else 1390 else
1081 sv_utf8_upgrade (string); 1391 sv_utf8_upgrade (string);
1082 1392
1083 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP 1393 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
1084 1394
1085 dec.flags = flags; 1395 dec.json = *json;
1086 dec.cur = SvPVX (string); 1396 dec.cur = SvPVX (string);
1087 dec.end = SvEND (string); 1397 dec.end = SvEND (string);
1088 dec.err = 0; 1398 dec.err = 0;
1089 dec.depth = 0; 1399 dec.depth = 0;
1090 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;
1091 1404
1092 *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);
1093 sv = decode_sv (&dec); 1408 sv = decode_sv (&dec);
1094 1409
1095 if (!(offset_return || !sv)) 1410 if (!(offset_return || !sv))
1096 { 1411 {
1097 // check for trailing garbage 1412 // check for trailing garbage
1105 } 1420 }
1106 } 1421 }
1107 1422
1108 if (offset_return || !sv) 1423 if (offset_return || !sv)
1109 { 1424 {
1110 offset = dec.flags & F_UTF8 1425 offset = dec.json.flags & F_UTF8
1111 ? dec.cur - SvPVX (string) 1426 ? dec.cur - SvPVX (string)
1112 : utf8_distance (dec.cur, SvPVX (string)); 1427 : utf8_distance (dec.cur, SvPVX (string));
1113 1428
1114 if (offset_return) 1429 if (offset_return)
1115 *offset_return = offset; 1430 *offset_return = offset;
1134 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); 1449 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
1135 } 1450 }
1136 1451
1137 sv = sv_2mortal (sv); 1452 sv = sv_2mortal (sv);
1138 1453
1139 if (!(dec.flags & F_ALLOW_NONREF) && !SvROK (sv)) 1454 if (!(dec.json.flags & F_ALLOW_NONREF) && !SvROK (sv))
1140 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)");
1141 1456
1142 return sv; 1457 return sv;
1143} 1458}
1144 1459
1156 i >= '0' && i <= '9' ? i - '0' 1471 i >= '0' && i <= '9' ? i - '0'
1157 : i >= 'a' && i <= 'f' ? i - 'a' + 10 1472 : i >= 'a' && i <= 'f' ? i - 'a' + 10
1158 : i >= 'A' && i <= 'F' ? i - 'A' + 10 1473 : i >= 'A' && i <= 'F' ? i - 'A' + 10
1159 : -1; 1474 : -1;
1160 1475
1161 json_stash = gv_stashpv ("JSON::XS", 1); 1476 json_stash = gv_stashpv ("JSON::XS" , 1);
1477 json_boolean_stash = gv_stashpv ("JSON::XS::Boolean", 1);
1478
1479 json_true = get_sv ("JSON::XS::true" , 1); SvREADONLY_on (json_true );
1480 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1162} 1481}
1163 1482
1164PROTOTYPES: DISABLE 1483PROTOTYPES: DISABLE
1165 1484
1166SV *new (char *dummy) 1485void CLONE (...)
1167 CODE: 1486 CODE:
1168 RETVAL = sv_bless (newRV_noinc (newSVuv (F_DEFAULT)), json_stash); 1487 json_stash = 0;
1488 json_boolean_stash = 0;
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
1503void ascii (JSON *self, int enable = 1)
1504 ALIAS:
1505 ascii = F_ASCII
1506 latin1 = F_LATIN1
1507 utf8 = F_UTF8
1508 indent = F_INDENT
1509 canonical = F_CANONICAL
1510 space_before = F_SPACE_BEFORE
1511 space_after = F_SPACE_AFTER
1512 pretty = F_PRETTY
1513 allow_nonref = F_ALLOW_NONREF
1514 shrink = F_SHRINK
1515 allow_blessed = F_ALLOW_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)
1561 CODE:
1562 RETVAL = DEC_DEPTH (self->flags);
1169 OUTPUT: 1563 OUTPUT:
1170 RETVAL 1564 RETVAL
1171 1565
1172SV *ascii (SV *self, int enable = 1) 1566void max_size (JSON *self, UV max_size = 0)
1173 ALIAS: 1567 PPCODE:
1174 ascii = F_ASCII 1568{
1175 latin1 = F_LATIN1 1569 UV log2 = 0;
1176 utf8 = F_UTF8 1570
1177 indent = F_INDENT 1571 if (max_size > 0x80000000UL) max_size = 0x80000000UL;
1178 canonical = F_CANONICAL 1572 if (max_size == 1) max_size = 2;
1179 space_before = F_SPACE_BEFORE 1573
1180 space_after = F_SPACE_AFTER 1574 while ((1UL << log2) < max_size)
1181 pretty = F_PRETTY 1575 ++log2;
1182 allow_nonref = F_ALLOW_NONREF 1576
1183 shrink = F_SHRINK 1577 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE);
1578
1579 XPUSHs (ST (0));
1580}
1581
1582int get_max_size (JSON *self)
1184 CODE: 1583 CODE:
1185{ 1584 RETVAL = DEC_SIZE (self->flags);
1186 UV *uv = SvJSON (self);
1187 if (enable)
1188 *uv |= ix;
1189 else
1190 *uv &= ~ix;
1191
1192 RETVAL = newSVsv (self);
1193}
1194 OUTPUT: 1585 OUTPUT:
1195 RETVAL 1586 RETVAL
1196 1587
1197SV *max_depth (SV *self, UV max_depth = 0x80000000UL) 1588void filter_json_object (JSON *self, SV *cb = &PL_sv_undef)
1198 CODE:
1199{
1200 UV *uv = SvJSON (self);
1201 UV log2 = 0;
1202
1203 if (max_depth > 0x80000000UL) max_depth = 0x80000000UL;
1204
1205 while ((1UL << log2) < max_depth)
1206 ++log2;
1207
1208 *uv = *uv & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1209
1210 RETVAL = newSVsv (self);
1211}
1212 OUTPUT:
1213 RETVAL
1214
1215void encode (SV *self, SV *scalar)
1216 PPCODE: 1589 PPCODE:
1217 XPUSHs (encode_json (scalar, *SvJSON (self))); 1590{
1591 SvREFCNT_dec (self->cb_object);
1592 self->cb_object = SvOK (cb) ? newSVsv (cb) : 0;
1218 1593
1219void 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)
1220 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:
1221 XPUSHs (decode_json (jsonstr, *SvJSON (self), 0)); 1625 XPUSHs (decode_json (jsonstr, self, 0));
1222 1626
1223void decode_prefix (SV *self, SV *jsonstr) 1627void decode_prefix (JSON *self, SV *jsonstr)
1224 PPCODE: 1628 PPCODE:
1225{ 1629{
1226 UV offset; 1630 UV offset;
1227 EXTEND (SP, 2); 1631 EXTEND (SP, 2);
1228 PUSHs (decode_json (jsonstr, *SvJSON (self), &offset)); 1632 PUSHs (decode_json (jsonstr, self, &offset));
1229 PUSHs (sv_2mortal (newSVuv (offset))); 1633 PUSHs (sv_2mortal (newSVuv (offset)));
1230} 1634}
1231 1635
1636void DESTROY (JSON *self)
1637 CODE:
1638 SvREFCNT_dec (self->cb_sk_object);
1639 SvREFCNT_dec (self->cb_object);
1640
1232PROTOTYPES: ENABLE 1641PROTOTYPES: ENABLE
1233 1642
1234void to_json (SV *scalar) 1643void encode_json (SV *scalar)
1235 ALIAS:
1236 objToJson = 0
1237 PPCODE: 1644 PPCODE:
1645{
1646 JSON json = { F_DEFAULT | F_UTF8 };
1238 XPUSHs (encode_json (scalar, F_DEFAULT | F_UTF8)); 1647 XPUSHs (encode_json (scalar, &json));
1648}
1239 1649
1240void from_json (SV *jsonstr) 1650void decode_json (SV *jsonstr)
1241 ALIAS:
1242 jsonToObj = 0
1243 PPCODE: 1651 PPCODE:
1652{
1653 JSON json = { F_DEFAULT | F_UTF8 };
1244 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8, 0)); 1654 XPUSHs (decode_json (jsonstr, &json, 0));
1655}
1245 1656

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines