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.73 by root, Wed Mar 19 13:44:43 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
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 (ch <= 0x7FF)
100 } 129 {
130 *s++ = (ch >> 6) | 0xc0;
131 *s++ = (ch & 0x3f) | 0x80;
132 }
133 else
134 s = uvuni_to_utf8_flags (s, ch, 0);
135
136 return s;
101} 137}
102 138
103///////////////////////////////////////////////////////////////////////////// 139/////////////////////////////////////////////////////////////////////////////
104// encoder 140// encoder
105 141
107typedef struct 143typedef struct
108{ 144{
109 char *cur; // SvPVX (sv) + current output position 145 char *cur; // SvPVX (sv) + current output position
110 char *end; // SvEND (sv) 146 char *end; // SvEND (sv)
111 SV *sv; // result scalar 147 SV *sv; // result scalar
112 U32 flags; // F_* 148 JSON json;
113 U32 indent; // indentation level 149 U32 indent; // indentation level
114 U32 maxdepth; // max. indentation/recursion level 150 U32 maxdepth; // max. indentation/recursion level
151 UV limit; // escape character values >= this value when encoding
115} enc_t; 152} enc_t;
116 153
117inline void 154INLINE void
118need (enc_t *enc, STRLEN len) 155need (enc_t *enc, STRLEN len)
119{ 156{
120 if (expect_false (enc->cur + len >= enc->end)) 157 if (expect_false (enc->cur + len >= enc->end))
121 { 158 {
122 STRLEN cur = enc->cur - SvPVX (enc->sv); 159 STRLEN cur = enc->cur - SvPVX (enc->sv);
124 enc->cur = SvPVX (enc->sv) + cur; 161 enc->cur = SvPVX (enc->sv) + cur;
125 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1; 162 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
126 } 163 }
127} 164}
128 165
129inline void 166INLINE void
130encode_ch (enc_t *enc, char ch) 167encode_ch (enc_t *enc, char ch)
131{ 168{
132 need (enc, 1); 169 need (enc, 1);
133 *enc->cur++ = ch; 170 *enc->cur++ = ch;
134} 171}
188 { 225 {
189 uch = ch; 226 uch = ch;
190 clen = 1; 227 clen = 1;
191 } 228 }
192 229
193 if (uch > 0x10FFFFUL) 230 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 { 231 {
198 if (uch > 0xFFFFUL) 232 if (uch > 0xFFFFUL)
199 { 233 {
234 if (uch > 0x10FFFFUL)
235 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
236
200 need (enc, len += 11); 237 need (enc, len += 11);
201 sprintf (enc->cur, "\\u%04x\\u%04x", 238 sprintf (enc->cur, "\\u%04x\\u%04x",
202 (int)((uch - 0x10000) / 0x400 + 0xD800), 239 (int)((uch - 0x10000) / 0x400 + 0xD800),
203 (int)((uch - 0x10000) % 0x400 + 0xDC00)); 240 (int)((uch - 0x10000) % 0x400 + 0xDC00));
204 enc->cur += 12; 241 enc->cur += 12;
215 *enc->cur++ = hexdigit [(uch >> 0) & 15]; 252 *enc->cur++ = hexdigit [(uch >> 0) & 15];
216 } 253 }
217 254
218 str += clen; 255 str += clen;
219 } 256 }
220 else if (enc->flags & F_LATIN1) 257 else if (enc->json.flags & F_LATIN1)
221 { 258 {
222 *enc->cur++ = uch; 259 *enc->cur++ = uch;
223 str += clen; 260 str += clen;
224 } 261 }
225 else if (is_utf8) 262 else if (is_utf8)
232 while (--clen); 269 while (--clen);
233 } 270 }
234 else 271 else
235 { 272 {
236 need (enc, len += UTF8_MAXBYTES - 1); // never more than 11 bytes needed 273 need (enc, len += UTF8_MAXBYTES - 1); // never more than 11 bytes needed
237 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); 274 enc->cur = encode_utf8 (enc->cur, uch);
238 ++str; 275 ++str;
239 } 276 }
240 } 277 }
241 } 278 }
242 } 279 }
243 280
244 --len; 281 --len;
245 } 282 }
246} 283}
247 284
248inline void 285INLINE void
249encode_indent (enc_t *enc) 286encode_indent (enc_t *enc)
250{ 287{
251 if (enc->flags & F_INDENT) 288 if (enc->json.flags & F_INDENT)
252 { 289 {
253 int spaces = enc->indent * INDENT_STEP; 290 int spaces = enc->indent * INDENT_STEP;
254 291
255 need (enc, spaces); 292 need (enc, spaces);
256 memset (enc->cur, ' ', spaces); 293 memset (enc->cur, ' ', spaces);
257 enc->cur += spaces; 294 enc->cur += spaces;
258 } 295 }
259} 296}
260 297
261inline void 298INLINE void
262encode_space (enc_t *enc) 299encode_space (enc_t *enc)
263{ 300{
264 need (enc, 1); 301 need (enc, 1);
265 encode_ch (enc, ' '); 302 encode_ch (enc, ' ');
266} 303}
267 304
268inline void 305INLINE void
269encode_nl (enc_t *enc) 306encode_nl (enc_t *enc)
270{ 307{
271 if (enc->flags & F_INDENT) 308 if (enc->json.flags & F_INDENT)
272 { 309 {
273 need (enc, 1); 310 need (enc, 1);
274 encode_ch (enc, '\n'); 311 encode_ch (enc, '\n');
275 } 312 }
276} 313}
277 314
278inline void 315INLINE void
279encode_comma (enc_t *enc) 316encode_comma (enc_t *enc)
280{ 317{
281 encode_ch (enc, ','); 318 encode_ch (enc, ',');
282 319
283 if (enc->flags & F_INDENT) 320 if (enc->json.flags & F_INDENT)
284 encode_nl (enc); 321 encode_nl (enc);
285 else if (enc->flags & F_SPACE_AFTER) 322 else if (enc->json.flags & F_SPACE_AFTER)
286 encode_space (enc); 323 encode_space (enc);
287} 324}
288 325
289static void encode_sv (enc_t *enc, SV *sv); 326static void encode_sv (enc_t *enc, SV *sv);
290 327
294 int i, len = av_len (av); 331 int i, len = av_len (av);
295 332
296 if (enc->indent >= enc->maxdepth) 333 if (enc->indent >= enc->maxdepth)
297 croak ("data structure too deep (hit recursion limit)"); 334 croak ("data structure too deep (hit recursion limit)");
298 335
299 encode_ch (enc, '['); encode_nl (enc); 336 encode_ch (enc, '[');
300 ++enc->indent; 337
338 if (len >= 0)
339 {
340 encode_nl (enc); ++enc->indent;
301 341
302 for (i = 0; i <= len; ++i) 342 for (i = 0; i <= len; ++i)
303 { 343 {
344 SV **svp = av_fetch (av, i, 0);
345
304 encode_indent (enc); 346 encode_indent (enc);
305 encode_sv (enc, *av_fetch (av, i, 0));
306 347
348 if (svp)
349 encode_sv (enc, *svp);
350 else
351 encode_str (enc, "null", 4, 0);
352
307 if (i < len) 353 if (i < len)
308 encode_comma (enc); 354 encode_comma (enc);
309 } 355 }
310 356
357 encode_nl (enc); --enc->indent; encode_indent (enc);
358 }
359
311 encode_nl (enc); 360 encode_ch (enc, ']');
312
313 --enc->indent;
314 encode_indent (enc); encode_ch (enc, ']');
315} 361}
316 362
317static void 363static void
318encode_he (enc_t *enc, HE *he) 364encode_hk (enc_t *enc, HE *he)
319{ 365{
320 encode_ch (enc, '"'); 366 encode_ch (enc, '"');
321 367
322 if (HeKLEN (he) == HEf_SVKEY) 368 if (HeKLEN (he) == HEf_SVKEY)
323 { 369 {
333 else 379 else
334 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he)); 380 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he));
335 381
336 encode_ch (enc, '"'); 382 encode_ch (enc, '"');
337 383
338 if (enc->flags & F_SPACE_BEFORE) encode_space (enc); 384 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc);
339 encode_ch (enc, ':'); 385 encode_ch (enc, ':');
340 if (enc->flags & F_SPACE_AFTER ) encode_space (enc); 386 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc);
341 encode_sv (enc, HeVAL (he));
342} 387}
343 388
344// compare hash entries, used when all keys are bytestrings 389// compare hash entries, used when all keys are bytestrings
345static int 390static int
346he_cmp_fast (const void *a_, const void *b_) 391he_cmp_fast (const void *a_, const void *b_)
351 HE *b = *(HE **)b_; 396 HE *b = *(HE **)b_;
352 397
353 STRLEN la = HeKLEN (a); 398 STRLEN la = HeKLEN (a);
354 STRLEN lb = HeKLEN (b); 399 STRLEN lb = HeKLEN (b);
355 400
356 if (!(cmp = memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb))) 401 if (!(cmp = memcmp (HeKEY (b), HeKEY (a), lb < la ? lb : la)))
357 cmp = la - lb; 402 cmp = lb - la;
358 403
359 return cmp; 404 return cmp;
360} 405}
361 406
362// compare hash entries, used when some keys are sv's or utf-x 407// compare hash entries, used when some keys are sv's or utf-x
363static int 408static int
364he_cmp_slow (const void *a, const void *b) 409he_cmp_slow (const void *a, const void *b)
365{ 410{
366 return sv_cmp (HeSVKEY_force (*(HE **)a), HeSVKEY_force (*(HE **)b)); 411 return sv_cmp (HeSVKEY_force (*(HE **)b), HeSVKEY_force (*(HE **)a));
367} 412}
368 413
369static void 414static void
370encode_hv (enc_t *enc, HV *hv) 415encode_hv (enc_t *enc, HV *hv)
371{ 416{
417 HE *he;
372 int count, i; 418 int count;
373 419
374 if (enc->indent >= enc->maxdepth) 420 if (enc->indent >= enc->maxdepth)
375 croak ("data structure too deep (hit recursion limit)"); 421 croak ("data structure too deep (hit recursion limit)");
376 422
377 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent; 423 encode_ch (enc, '{');
378 424
379 if ((count = hv_iterinit (hv)))
380 {
381 // for canonical output we have to sort by keys first 425 // for canonical output we have to sort by keys first
382 // actually, this is mostly due to the stupid so-called 426 // actually, this is mostly due to the stupid so-called
383 // security workaround added somewhere in 5.8.x. 427 // security workaround added somewhere in 5.8.x.
384 // that randomises hash orderings 428 // that randomises hash orderings
385 if (enc->flags & F_CANONICAL) 429 if (enc->json.flags & F_CANONICAL)
430 {
431 int count = hv_iterinit (hv);
432
433 if (SvMAGICAL (hv))
386 { 434 {
435 // need to count by iterating. could improve by dynamically building the vector below
436 // but I don't care for the speed of this special case.
437 // note also that we will run into undefined behaviour when the two iterations
438 // do not result in the same count, something I might care for in some later release.
439
440 count = 0;
441 while (hv_iternext (hv))
442 ++count;
443
444 hv_iterinit (hv);
445 }
446
447 if (count)
448 {
387 int fast = 1; 449 int i, fast = 1;
388 HE *he;
389#if defined(__BORLANDC__) || defined(_MSC_VER) 450#if defined(__BORLANDC__) || defined(_MSC_VER)
390 HE **hes = _alloca (count * sizeof (HE)); 451 HE **hes = _alloca (count * sizeof (HE));
391#else 452#else
392 HE *hes [count]; // if your compiler dies here, you need to enable C99 mode 453 HE *hes [count]; // if your compiler dies here, you need to enable C99 mode
393#endif 454#endif
420 481
421 FREETMPS; 482 FREETMPS;
422 LEAVE; 483 LEAVE;
423 } 484 }
424 485
425 for (i = 0; i < count; ++i) 486 encode_nl (enc); ++enc->indent;
487
488 while (count--)
426 { 489 {
427 encode_indent (enc); 490 encode_indent (enc);
491 he = hes [count];
428 encode_he (enc, hes [i]); 492 encode_hk (enc, he);
493 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
429 494
430 if (i < count - 1) 495 if (count)
431 encode_comma (enc); 496 encode_comma (enc);
432 } 497 }
433 498
499 encode_nl (enc); --enc->indent; encode_indent (enc);
500 }
501 }
502 else
503 {
504 if (hv_iterinit (hv) || SvMAGICAL (hv))
505 if ((he = hv_iternext (hv)))
506 {
507 encode_nl (enc); ++enc->indent;
508
509 for (;;)
510 {
434 encode_nl (enc); 511 encode_indent (enc);
512 encode_hk (enc, he);
513 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
514
515 if (!(he = hv_iternext (hv)))
516 break;
517
518 encode_comma (enc);
519 }
520
521 encode_nl (enc); --enc->indent; encode_indent (enc);
522 }
523 }
524
525 encode_ch (enc, '}');
526}
527
528// encode objects, arrays and special \0=false and \1=true values.
529static void
530encode_rv (enc_t *enc, SV *sv)
531{
532 svtype svt;
533
534 SvGETMAGIC (sv);
535 svt = SvTYPE (sv);
536
537 if (expect_false (SvOBJECT (sv)))
538 {
539 HV *stash = !JSON_SLOW || json_boolean_stash
540 ? json_boolean_stash
541 : gv_stashpv ("JSON::XS::Boolean", 1);
542
543 if (SvSTASH (sv) == stash)
544 {
545 if (SvIV (sv))
546 encode_str (enc, "true", 4, 0);
547 else
548 encode_str (enc, "false", 5, 0);
435 } 549 }
436 else 550 else
437 { 551 {
438 HE *he = hv_iternext (hv); 552#if 0
439 553 if (0 && sv_derived_from (rv, "JSON::Literal"))
440 for (;;)
441 { 554 {
442 encode_indent (enc); 555 // not yet
443 encode_he (enc, he);
444
445 if (!(he = hv_iternext (hv)))
446 break;
447
448 encode_comma (enc);
449 } 556 }
557#endif
558 if (enc->json.flags & F_CONV_BLESSED)
559 {
560 // we re-bless the reference to get overload and other niceties right
561 GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 0);
450 562
563 if (to_json)
564 {
565 dSP;
566
567 ENTER; SAVETMPS; PUSHMARK (SP);
568 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv)));
569
570 // calling with G_SCALAR ensures that we always get a 1 return value
571 PUTBACK;
572 call_sv ((SV *)GvCV (to_json), G_SCALAR);
573 SPAGAIN;
574
575 // catch this surprisingly common error
576 if (SvROK (TOPs) && SvRV (TOPs) == sv)
577 croak ("%s::TO_JSON method returned same object as was passed instead of a new one", HvNAME (SvSTASH (sv)));
578
579 sv = POPs;
580 PUTBACK;
581
451 encode_nl (enc); 582 encode_sv (enc, sv);
583
584 FREETMPS; LEAVE;
585 }
586 else if (enc->json.flags & F_ALLOW_BLESSED)
587 encode_str (enc, "null", 4, 0);
588 else
589 croak ("encountered object '%s', but neither allow_blessed enabled nor TO_JSON method available on it",
590 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
591 }
592 else if (enc->json.flags & F_ALLOW_BLESSED)
593 encode_str (enc, "null", 4, 0);
594 else
595 croak ("encountered object '%s', but neither allow_blessed nor convert_blessed settings are enabled",
596 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
452 } 597 }
453 } 598 }
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) 599 else if (svt == SVt_PVHV)
468 encode_hv (enc, (HV *)sv); 600 encode_hv (enc, (HV *)sv);
469 else if (svt == SVt_PVAV) 601 else if (svt == SVt_PVAV)
470 encode_av (enc, (AV *)sv); 602 encode_av (enc, (AV *)sv);
471 else if (svt < SVt_PVAV) 603 else if (svt < SVt_PVAV)
472 { 604 {
473 if (SvNIOK (sv) && SvIV (sv) == 0) 605 STRLEN len = 0;
606 char *pv = svt ? SvPV (sv, len) : 0;
607
608 if (len == 1 && *pv == '1')
609 encode_str (enc, "true", 4, 0);
610 else if (len == 1 && *pv == '0')
474 encode_str (enc, "false", 5, 0); 611 encode_str (enc, "false", 5, 0);
475 else if (SvNIOK (sv) && SvIV (sv) == 1)
476 encode_str (enc, "true", 4, 0);
477 else 612 else
478 croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1", 613 croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1",
479 SvPV_nolen (sv_2mortal (newRV_inc (sv)))); 614 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
480 } 615 }
481 else 616 else
551 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this", 686 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this",
552 SvPV_nolen (sv), SvFLAGS (sv)); 687 SvPV_nolen (sv), SvFLAGS (sv));
553} 688}
554 689
555static SV * 690static SV *
556encode_json (SV *scalar, U32 flags) 691encode_json (SV *scalar, JSON *json)
557{ 692{
558 enc_t enc; 693 enc_t enc;
559 694
560 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar)) 695 if (!(json->flags & F_ALLOW_NONREF) && !SvROK (scalar))
561 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)"); 696 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)");
562 697
563 enc.flags = flags; 698 enc.json = *json;
564 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 699 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
565 enc.cur = SvPVX (enc.sv); 700 enc.cur = SvPVX (enc.sv);
566 enc.end = SvEND (enc.sv); 701 enc.end = SvEND (enc.sv);
567 enc.indent = 0; 702 enc.indent = 0;
568 enc.maxdepth = DEC_DEPTH (flags); 703 enc.maxdepth = DEC_DEPTH (enc.json.flags);
704 enc.limit = enc.json.flags & F_ASCII ? 0x000080UL
705 : enc.json.flags & F_LATIN1 ? 0x000100UL
706 : 0x10FFFFUL;
569 707
570 SvPOK_only (enc.sv); 708 SvPOK_only (enc.sv);
571 encode_sv (&enc, scalar); 709 encode_sv (&enc, scalar);
572 710
573 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); 711 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
574 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings 712 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings
575 713
576 if (!(flags & (F_ASCII | F_LATIN1 | F_UTF8))) 714 if (!(enc.json.flags & (F_ASCII | F_LATIN1 | F_UTF8)))
577 SvUTF8_on (enc.sv); 715 SvUTF8_on (enc.sv);
578 716
579 if (enc.flags & F_SHRINK) 717 if (enc.json.flags & F_SHRINK)
580 shrink (enc.sv); 718 shrink (enc.sv);
581 719
582 return enc.sv; 720 return enc.sv;
583} 721}
584 722
589typedef struct 727typedef struct
590{ 728{
591 char *cur; // current parser pointer 729 char *cur; // current parser pointer
592 char *end; // end of input string 730 char *end; // end of input string
593 const char *err; // parse error, if != 0 731 const char *err; // parse error, if != 0
594 U32 flags; // F_* 732 JSON json;
595 U32 depth; // recursion depth 733 U32 depth; // recursion depth
596 U32 maxdepth; // recursion depth limit 734 U32 maxdepth; // recursion depth limit
597} dec_t; 735} dec_t;
598 736
599inline void 737INLINE void
738decode_comment (dec_t *dec)
739{
740 // only '#'-style comments allowed a.t.m.
741
742 while (*dec->cur && *dec->cur != 0x0a && *dec->cur != 0x0d)
743 ++dec->cur;
744}
745
746INLINE void
600decode_ws (dec_t *dec) 747decode_ws (dec_t *dec)
601{ 748{
602 for (;;) 749 for (;;)
603 { 750 {
604 char ch = *dec->cur; 751 char ch = *dec->cur;
605 752
606 if (ch > 0x20 753 if (ch > 0x20)
754 {
755 if (expect_false (ch == '#'))
756 {
757 if (dec->json.flags & F_RELAXED)
758 decode_comment (dec);
759 else
760 break;
761 }
762 else
763 break;
764 }
607 || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)) 765 else if (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)
608 break; 766 break; // parse error, but let higher level handle it, gives better error messages
609 767
610 ++dec->cur; 768 ++dec->cur;
611 } 769 }
612} 770}
613 771
719 877
720 if (hi >= 0x80) 878 if (hi >= 0x80)
721 { 879 {
722 utf8 = 1; 880 utf8 = 1;
723 881
724 cur = (char *)uvuni_to_utf8_flags (cur, hi, 0); 882 cur = encode_utf8 (cur, hi);
725 } 883 }
726 else 884 else
727 *cur++ = hi; 885 *cur++ = hi;
728 } 886 }
729 break; 887 break;
862 is_nv = 1; 1020 is_nv = 1;
863 } 1021 }
864 1022
865 if (!is_nv) 1023 if (!is_nv)
866 { 1024 {
1025 int len = dec->cur - start;
1026
867 // special case the rather common 1..4-digit-int case, assumes 32 bit ints or so 1027 // special case the rather common 1..5-digit-int case
868 if (*start == '-') 1028 if (*start == '-')
869 switch (dec->cur - start) 1029 switch (len)
870 { 1030 {
871 case 2: return newSViv (-( start [1] - '0' * 1)); 1031 case 2: return newSViv (-( start [1] - '0' * 1));
872 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11)); 1032 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)); 1033 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)); 1034 case 5: return newSViv (-( start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111));
1035 case 6: return newSViv (-(start [1] * 10000 + start [2] * 1000 + start [3] * 100 + start [4] * 10 + start [5] - '0' * 11111));
875 } 1036 }
876 else 1037 else
877 switch (dec->cur - start) 1038 switch (len)
878 { 1039 {
879 case 1: return newSViv ( start [0] - '0' * 1); 1040 case 1: return newSViv ( start [0] - '0' * 1);
880 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11); 1041 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); 1042 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); 1043 case 4: return newSViv ( start [0] * 1000 + start [1] * 100 + start [2] * 10 + start [3] - '0' * 1111);
1044 case 5: return newSViv ( start [0] * 10000 + start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 11111);
883 } 1045 }
884 1046
885 { 1047 {
886 UV uv; 1048 UV uv;
887 int numtype = grok_number (start, dec->cur - start, &uv); 1049 int numtype = grok_number (start, len, &uv);
888 if (numtype & IS_NUMBER_IN_UV) 1050 if (numtype & IS_NUMBER_IN_UV)
889 if (numtype & IS_NUMBER_NEG) 1051 if (numtype & IS_NUMBER_NEG)
890 { 1052 {
891 if (uv < (UV)IV_MIN) 1053 if (uv < (UV)IV_MIN)
892 return newSViv (-(IV)uv); 1054 return newSViv (-(IV)uv);
893 } 1055 }
894 else 1056 else
895 return newSVuv (uv); 1057 return newSVuv (uv);
896
897 // here would likely be the place for bigint support
898 } 1058 }
899 }
900 1059
901 // if we ever support bigint or bigfloat, this is the place for bigfloat 1060 len -= *start == '-' ? 1 : 0;
1061
1062 // does not fit into IV or UV, try NV
1063 if ((sizeof (NV) == sizeof (double) && DBL_DIG >= len)
1064 #if defined (LDBL_DIG)
1065 || (sizeof (NV) == sizeof (long double) && LDBL_DIG >= len)
1066 #endif
1067 )
1068 // fits into NV without loss of precision
1069 return newSVnv (Atof (start));
1070
1071 // everything else fails, convert it to a string
1072 return newSVpvn (start, dec->cur - start);
1073 }
1074
1075 // loss of precision here
902 return newSVnv (Atof (start)); 1076 return newSVnv (Atof (start));
903 1077
904fail: 1078fail:
905 return 0; 1079 return 0;
906} 1080}
936 1110
937 if (*dec->cur != ',') 1111 if (*dec->cur != ',')
938 ERR (", or ] expected while parsing array"); 1112 ERR (", or ] expected while parsing array");
939 1113
940 ++dec->cur; 1114 ++dec->cur;
1115
1116 decode_ws (dec);
1117
1118 if (*dec->cur == ']' && dec->json.flags & F_RELAXED)
1119 {
1120 ++dec->cur;
1121 break;
1122 }
941 } 1123 }
942 1124
943 DEC_DEC_DEPTH; 1125 DEC_DEC_DEPTH;
944 return newRV_noinc ((SV *)av); 1126 return newRV_noinc ((SV *)av);
945 1127
950} 1132}
951 1133
952static SV * 1134static SV *
953decode_hv (dec_t *dec) 1135decode_hv (dec_t *dec)
954{ 1136{
1137 SV *sv;
955 HV *hv = newHV (); 1138 HV *hv = newHV ();
956 1139
957 DEC_INC_DEPTH; 1140 DEC_INC_DEPTH;
958 decode_ws (dec); 1141 decode_ws (dec);
959 1142
960 if (*dec->cur == '}') 1143 if (*dec->cur == '}')
961 ++dec->cur; 1144 ++dec->cur;
962 else 1145 else
963 for (;;) 1146 for (;;)
964 { 1147 {
1148 EXPECT_CH ('"');
1149
1150 // heuristic: assume that
1151 // a) decode_str + hv_store_ent are abysmally slow.
1152 // b) most hash keys are short, simple ascii text.
1153 // => try to "fast-match" such strings to avoid
1154 // the overhead of decode_str + hv_store_ent.
1155 {
965 SV *key, *value; 1156 SV *value;
1157 char *p = dec->cur;
1158 char *e = p + 24; // only try up to 24 bytes
966 1159
967 decode_ws (dec); EXPECT_CH ('"'); 1160 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 { 1161 {
1162 // the >= 0x80 is true on most architectures
1163 if (p == e || *p < 0x20 || *p >= 0x80 || *p == '\\')
1164 {
1165 // slow path, back up and use decode_str
1166 SV *key = decode_str (dec);
1167 if (!key)
1168 goto fail;
1169
1170 decode_ws (dec); EXPECT_CH (':');
1171
1172 decode_ws (dec);
1173 value = decode_sv (dec);
1174 if (!value)
1175 {
1176 SvREFCNT_dec (key);
1177 goto fail;
1178 }
1179
1180 hv_store_ent (hv, key, value, 0);
978 SvREFCNT_dec (key); 1181 SvREFCNT_dec (key);
1182
1183 break;
1184 }
1185 else if (*p == '"')
1186 {
1187 // fast path, got a simple key
1188 char *key = dec->cur;
1189 int len = p - key;
1190 dec->cur = p + 1;
1191
1192 decode_ws (dec); EXPECT_CH (':');
1193
1194 decode_ws (dec);
1195 value = decode_sv (dec);
1196 if (!value)
979 goto fail; 1197 goto fail;
1198
1199 hv_store (hv, key, len, value, 0);
1200
1201 break;
1202 }
1203
1204 ++p;
980 } 1205 }
981 1206 }
982 hv_store_ent (hv, key, value, 0);
983 SvREFCNT_dec (key);
984 1207
985 decode_ws (dec); 1208 decode_ws (dec);
986 1209
987 if (*dec->cur == '}') 1210 if (*dec->cur == '}')
988 { 1211 {
992 1215
993 if (*dec->cur != ',') 1216 if (*dec->cur != ',')
994 ERR (", or } expected while parsing object/hash"); 1217 ERR (", or } expected while parsing object/hash");
995 1218
996 ++dec->cur; 1219 ++dec->cur;
1220
1221 decode_ws (dec);
1222
1223 if (*dec->cur == '}' && dec->json.flags & F_RELAXED)
1224 {
1225 ++dec->cur;
1226 break;
1227 }
997 } 1228 }
998 1229
999 DEC_DEC_DEPTH; 1230 DEC_DEC_DEPTH;
1000 return newRV_noinc ((SV *)hv); 1231 sv = newRV_noinc ((SV *)hv);
1232
1233 // check filter callbacks
1234 if (dec->json.flags & F_HOOK)
1235 {
1236 if (dec->json.cb_sk_object && HvKEYS (hv) == 1)
1237 {
1238 HE *cb, *he;
1239
1240 hv_iterinit (hv);
1241 he = hv_iternext (hv);
1242 hv_iterinit (hv);
1243
1244 // the next line creates a mortal sv each time its called.
1245 // might want to optimise this for common cases.
1246 cb = hv_fetch_ent (dec->json.cb_sk_object, hv_iterkeysv (he), 0, 0);
1247
1248 if (cb)
1249 {
1250 dSP;
1251 int count;
1252
1253 ENTER; SAVETMPS; PUSHMARK (SP);
1254 XPUSHs (HeVAL (he));
1255
1256 PUTBACK; count = call_sv (HeVAL (cb), G_ARRAY); SPAGAIN;
1257
1258 if (count == 1)
1259 {
1260 sv = newSVsv (POPs);
1261 FREETMPS; LEAVE;
1262 return sv;
1263 }
1264
1265 FREETMPS; LEAVE;
1266 }
1267 }
1268
1269 if (dec->json.cb_object)
1270 {
1271 dSP;
1272 int count;
1273
1274 ENTER; SAVETMPS; PUSHMARK (SP);
1275 XPUSHs (sv_2mortal (sv));
1276
1277 PUTBACK; count = call_sv (dec->json.cb_object, G_ARRAY); SPAGAIN;
1278
1279 if (count == 1)
1280 {
1281 sv = newSVsv (POPs);
1282 FREETMPS; LEAVE;
1283 return sv;
1284 }
1285
1286 SvREFCNT_inc (sv);
1287 FREETMPS; LEAVE;
1288 }
1289 }
1290
1291 return sv;
1001 1292
1002fail: 1293fail:
1003 SvREFCNT_dec (hv); 1294 SvREFCNT_dec (hv);
1004 DEC_DEC_DEPTH; 1295 DEC_DEC_DEPTH;
1005 return 0; 1296 return 0;
1006} 1297}
1007 1298
1008static SV * 1299static SV *
1009decode_sv (dec_t *dec) 1300decode_sv (dec_t *dec)
1010{ 1301{
1011 decode_ws (dec);
1012
1013 // the beauty of JSON: you need exactly one character lookahead 1302 // the beauty of JSON: you need exactly one character lookahead
1014 // to parse anything. 1303 // to parse everything.
1015 switch (*dec->cur) 1304 switch (*dec->cur)
1016 { 1305 {
1017 case '"': ++dec->cur; return decode_str (dec); 1306 case '"': ++dec->cur; return decode_str (dec);
1018 case '[': ++dec->cur; return decode_av (dec); 1307 case '[': ++dec->cur; return decode_av (dec);
1019 case '{': ++dec->cur; return decode_hv (dec); 1308 case '{': ++dec->cur; return decode_hv (dec);
1020 1309
1021 case '-': 1310 case '-':
1022 case '0': case '1': case '2': case '3': case '4': 1311 case '0': case '1': case '2': case '3': case '4':
1023 case '5': case '6': case '7': case '8': case '9': 1312 case '5': case '6': case '7': case '8': case '9':
1024 return decode_num (dec); 1313 return decode_num (dec);
1025 1314
1026 case 't': 1315 case 't':
1027 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1316 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
1028 { 1317 {
1029 dec->cur += 4; 1318 dec->cur += 4;
1030 return newSViv (1); 1319#if JSON_SLOW
1320 json_true = get_sv ("JSON::XS::true", 1); SvREADONLY_on (json_true);
1321#endif
1322 return SvREFCNT_inc (json_true);
1031 } 1323 }
1032 else 1324 else
1033 ERR ("'true' expected"); 1325 ERR ("'true' expected");
1034 1326
1035 break; 1327 break;
1036 1328
1037 case 'f': 1329 case 'f':
1038 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1330 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
1039 { 1331 {
1040 dec->cur += 5; 1332 dec->cur += 5;
1041 return newSViv (0); 1333#if JSON_SLOW
1334 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1335#endif
1336 return SvREFCNT_inc (json_false);
1042 } 1337 }
1043 else 1338 else
1044 ERR ("'false' expected"); 1339 ERR ("'false' expected");
1045 1340
1046 break; 1341 break;
1064fail: 1359fail:
1065 return 0; 1360 return 0;
1066} 1361}
1067 1362
1068static SV * 1363static SV *
1069decode_json (SV *string, U32 flags, UV *offset_return) 1364decode_json (SV *string, JSON *json, UV *offset_return)
1070{ 1365{
1071 dec_t dec; 1366 dec_t dec;
1072 UV offset; 1367 UV offset;
1073 SV *sv; 1368 SV *sv;
1074 1369
1075 SvGETMAGIC (string); 1370 SvGETMAGIC (string);
1076 SvUPGRADE (string, SVt_PV); 1371 SvUPGRADE (string, SVt_PV);
1077 1372
1373 if (json->flags & F_MAXSIZE && SvCUR (string) > DEC_SIZE (json->flags))
1374 croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu",
1375 (unsigned long)SvCUR (string), (unsigned long)DEC_SIZE (json->flags));
1376
1078 if (flags & F_UTF8) 1377 if (json->flags & F_UTF8)
1079 sv_utf8_downgrade (string, 0); 1378 sv_utf8_downgrade (string, 0);
1080 else 1379 else
1081 sv_utf8_upgrade (string); 1380 sv_utf8_upgrade (string);
1082 1381
1083 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP 1382 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
1084 1383
1085 dec.flags = flags; 1384 dec.json = *json;
1086 dec.cur = SvPVX (string); 1385 dec.cur = SvPVX (string);
1087 dec.end = SvEND (string); 1386 dec.end = SvEND (string);
1088 dec.err = 0; 1387 dec.err = 0;
1089 dec.depth = 0; 1388 dec.depth = 0;
1090 dec.maxdepth = DEC_DEPTH (dec.flags); 1389 dec.maxdepth = DEC_DEPTH (dec.json.flags);
1390
1391 if (dec.json.cb_object || dec.json.cb_sk_object)
1392 dec.json.flags |= F_HOOK;
1091 1393
1092 *dec.end = 0; // this should basically be a nop, too, but make sure it's there 1394 *dec.end = 0; // this should basically be a nop, too, but make sure it's there
1395
1396 decode_ws (&dec);
1093 sv = decode_sv (&dec); 1397 sv = decode_sv (&dec);
1094 1398
1095 if (!(offset_return || !sv)) 1399 if (!(offset_return || !sv))
1096 { 1400 {
1097 // check for trailing garbage 1401 // check for trailing garbage
1105 } 1409 }
1106 } 1410 }
1107 1411
1108 if (offset_return || !sv) 1412 if (offset_return || !sv)
1109 { 1413 {
1110 offset = dec.flags & F_UTF8 1414 offset = dec.json.flags & F_UTF8
1111 ? dec.cur - SvPVX (string) 1415 ? dec.cur - SvPVX (string)
1112 : utf8_distance (dec.cur, SvPVX (string)); 1416 : utf8_distance (dec.cur, SvPVX (string));
1113 1417
1114 if (offset_return) 1418 if (offset_return)
1115 *offset_return = offset; 1419 *offset_return = offset;
1134 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); 1438 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
1135 } 1439 }
1136 1440
1137 sv = sv_2mortal (sv); 1441 sv = sv_2mortal (sv);
1138 1442
1139 if (!(dec.flags & F_ALLOW_NONREF) && !SvROK (sv)) 1443 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)"); 1444 croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)");
1141 1445
1142 return sv; 1446 return sv;
1143} 1447}
1144 1448
1156 i >= '0' && i <= '9' ? i - '0' 1460 i >= '0' && i <= '9' ? i - '0'
1157 : i >= 'a' && i <= 'f' ? i - 'a' + 10 1461 : i >= 'a' && i <= 'f' ? i - 'a' + 10
1158 : i >= 'A' && i <= 'F' ? i - 'A' + 10 1462 : i >= 'A' && i <= 'F' ? i - 'A' + 10
1159 : -1; 1463 : -1;
1160 1464
1161 json_stash = gv_stashpv ("JSON::XS", 1); 1465 json_stash = gv_stashpv ("JSON::XS" , 1);
1466 json_boolean_stash = gv_stashpv ("JSON::XS::Boolean", 1);
1467
1468 json_true = get_sv ("JSON::XS::true" , 1); SvREADONLY_on (json_true );
1469 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1162} 1470}
1163 1471
1164PROTOTYPES: DISABLE 1472PROTOTYPES: DISABLE
1165 1473
1166SV *new (char *dummy) 1474void CLONE (...)
1167 CODE: 1475 CODE:
1168 RETVAL = sv_bless (newRV_noinc (newSVuv (F_DEFAULT)), json_stash); 1476 json_stash = 0;
1477 json_boolean_stash = 0;
1478
1479void new (char *klass)
1480 PPCODE:
1481{
1482 SV *pv = NEWSV (0, sizeof (JSON));
1483 SvPOK_only (pv);
1484 Zero (SvPVX (pv), 1, JSON);
1485 ((JSON *)SvPVX (pv))->flags = F_DEFAULT;
1486 XPUSHs (sv_2mortal (sv_bless (
1487 newRV_noinc (pv),
1488 strEQ (klass, "JSON::XS") ? JSON_STASH : gv_stashpv (klass, 1)
1489 )));
1490}
1491
1492void ascii (JSON *self, int enable = 1)
1493 ALIAS:
1494 ascii = F_ASCII
1495 latin1 = F_LATIN1
1496 utf8 = F_UTF8
1497 indent = F_INDENT
1498 canonical = F_CANONICAL
1499 space_before = F_SPACE_BEFORE
1500 space_after = F_SPACE_AFTER
1501 pretty = F_PRETTY
1502 allow_nonref = F_ALLOW_NONREF
1503 shrink = F_SHRINK
1504 allow_blessed = F_ALLOW_BLESSED
1505 convert_blessed = F_CONV_BLESSED
1506 relaxed = F_RELAXED
1507 PPCODE:
1508{
1509 if (enable)
1510 self->flags |= ix;
1511 else
1512 self->flags &= ~ix;
1513
1514 XPUSHs (ST (0));
1515}
1516
1517void get_ascii (JSON *self)
1518 ALIAS:
1519 get_ascii = F_ASCII
1520 get_latin1 = F_LATIN1
1521 get_utf8 = F_UTF8
1522 get_indent = F_INDENT
1523 get_canonical = F_CANONICAL
1524 get_space_before = F_SPACE_BEFORE
1525 get_space_after = F_SPACE_AFTER
1526 get_allow_nonref = F_ALLOW_NONREF
1527 get_shrink = F_SHRINK
1528 get_allow_blessed = F_ALLOW_BLESSED
1529 get_convert_blessed = F_CONV_BLESSED
1530 get_relaxed = F_RELAXED
1531 PPCODE:
1532 XPUSHs (boolSV (self->flags & ix));
1533
1534void max_depth (JSON *self, UV max_depth = 0x80000000UL)
1535 PPCODE:
1536{
1537 UV log2 = 0;
1538
1539 if (max_depth > 0x80000000UL) max_depth = 0x80000000UL;
1540
1541 while ((1UL << log2) < max_depth)
1542 ++log2;
1543
1544 self->flags = self->flags & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1545
1546 XPUSHs (ST (0));
1547}
1548
1549U32 get_max_depth (JSON *self)
1550 CODE:
1551 RETVAL = DEC_DEPTH (self->flags);
1169 OUTPUT: 1552 OUTPUT:
1170 RETVAL 1553 RETVAL
1171 1554
1172SV *ascii (SV *self, int enable = 1) 1555void max_size (JSON *self, UV max_size = 0)
1173 ALIAS: 1556 PPCODE:
1174 ascii = F_ASCII 1557{
1175 latin1 = F_LATIN1 1558 UV log2 = 0;
1176 utf8 = F_UTF8 1559
1177 indent = F_INDENT 1560 if (max_size > 0x80000000UL) max_size = 0x80000000UL;
1178 canonical = F_CANONICAL 1561 if (max_size == 1) max_size = 2;
1179 space_before = F_SPACE_BEFORE 1562
1180 space_after = F_SPACE_AFTER 1563 while ((1UL << log2) < max_size)
1181 pretty = F_PRETTY 1564 ++log2;
1182 allow_nonref = F_ALLOW_NONREF 1565
1183 shrink = F_SHRINK 1566 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE);
1567
1568 XPUSHs (ST (0));
1569}
1570
1571int get_max_size (JSON *self)
1184 CODE: 1572 CODE:
1185{ 1573 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: 1574 OUTPUT:
1195 RETVAL 1575 RETVAL
1196 1576
1197SV *max_depth (SV *self, UV max_depth = 0x80000000UL) 1577void 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: 1578 PPCODE:
1217 XPUSHs (encode_json (scalar, *SvJSON (self))); 1579{
1580 SvREFCNT_dec (self->cb_object);
1581 self->cb_object = SvOK (cb) ? newSVsv (cb) : 0;
1218 1582
1219void decode (SV *self, SV *jsonstr) 1583 XPUSHs (ST (0));
1584}
1585
1586void filter_json_single_key_object (JSON *self, SV *key, SV *cb = &PL_sv_undef)
1220 PPCODE: 1587 PPCODE:
1588{
1589 if (!self->cb_sk_object)
1590 self->cb_sk_object = newHV ();
1591
1592 if (SvOK (cb))
1593 hv_store_ent (self->cb_sk_object, key, newSVsv (cb), 0);
1594 else
1595 {
1596 hv_delete_ent (self->cb_sk_object, key, G_DISCARD, 0);
1597
1598 if (!HvKEYS (self->cb_sk_object))
1599 {
1600 SvREFCNT_dec (self->cb_sk_object);
1601 self->cb_sk_object = 0;
1602 }
1603 }
1604
1605 XPUSHs (ST (0));
1606}
1607
1608void encode (JSON *self, SV *scalar)
1609 PPCODE:
1610 XPUSHs (encode_json (scalar, self));
1611
1612void decode (JSON *self, SV *jsonstr)
1613 PPCODE:
1221 XPUSHs (decode_json (jsonstr, *SvJSON (self), 0)); 1614 XPUSHs (decode_json (jsonstr, self, 0));
1222 1615
1223void decode_prefix (SV *self, SV *jsonstr) 1616void decode_prefix (JSON *self, SV *jsonstr)
1224 PPCODE: 1617 PPCODE:
1225{ 1618{
1226 UV offset; 1619 UV offset;
1227 EXTEND (SP, 2); 1620 EXTEND (SP, 2);
1228 PUSHs (decode_json (jsonstr, *SvJSON (self), &offset)); 1621 PUSHs (decode_json (jsonstr, self, &offset));
1229 PUSHs (sv_2mortal (newSVuv (offset))); 1622 PUSHs (sv_2mortal (newSVuv (offset)));
1230} 1623}
1231 1624
1625void DESTROY (JSON *self)
1626 CODE:
1627 SvREFCNT_dec (self->cb_sk_object);
1628 SvREFCNT_dec (self->cb_object);
1629
1232PROTOTYPES: ENABLE 1630PROTOTYPES: ENABLE
1233 1631
1234void to_json (SV *scalar) 1632void encode_json (SV *scalar)
1235 ALIAS:
1236 objToJson = 0
1237 PPCODE: 1633 PPCODE:
1634{
1635 JSON json = { F_DEFAULT | F_UTF8 };
1238 XPUSHs (encode_json (scalar, F_DEFAULT | F_UTF8)); 1636 XPUSHs (encode_json (scalar, &json));
1637}
1239 1638
1240void from_json (SV *jsonstr) 1639void decode_json (SV *jsonstr)
1241 ALIAS:
1242 jsonToObj = 0
1243 PPCODE: 1640 PPCODE:
1641{
1642 JSON json = { F_DEFAULT | F_UTF8 };
1244 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8, 0)); 1643 XPUSHs (decode_json (jsonstr, &json, 0));
1644}
1245 1645

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines