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.46 by root, Mon Jun 25 22:11:39 2007 UTC vs.
Revision 1.72 by root, Wed Mar 19 04:08:22 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
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)
109 } 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;
110} 137}
111 138
112///////////////////////////////////////////////////////////////////////////// 139/////////////////////////////////////////////////////////////////////////////
113// encoder 140// encoder
114 141
116typedef struct 143typedef struct
117{ 144{
118 char *cur; // SvPVX (sv) + current output position 145 char *cur; // SvPVX (sv) + current output position
119 char *end; // SvEND (sv) 146 char *end; // SvEND (sv)
120 SV *sv; // result scalar 147 SV *sv; // result scalar
121 U32 flags; // F_* 148 JSON json;
122 U32 indent; // indentation level 149 U32 indent; // indentation level
123 U32 maxdepth; // max. indentation/recursion level 150 U32 maxdepth; // max. indentation/recursion level
151 UV limit; // escape character values >= this value when encoding
124} enc_t; 152} enc_t;
125 153
126inline void 154INLINE void
127need (enc_t *enc, STRLEN len) 155need (enc_t *enc, STRLEN len)
128{ 156{
129 if (expect_false (enc->cur + len >= enc->end)) 157 if (expect_false (enc->cur + len >= enc->end))
130 { 158 {
131 STRLEN cur = enc->cur - SvPVX (enc->sv); 159 STRLEN cur = enc->cur - SvPVX (enc->sv);
133 enc->cur = SvPVX (enc->sv) + cur; 161 enc->cur = SvPVX (enc->sv) + cur;
134 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1; 162 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
135 } 163 }
136} 164}
137 165
138inline void 166INLINE void
139encode_ch (enc_t *enc, char ch) 167encode_ch (enc_t *enc, char ch)
140{ 168{
141 need (enc, 1); 169 need (enc, 1);
142 *enc->cur++ = ch; 170 *enc->cur++ = ch;
143} 171}
197 { 225 {
198 uch = ch; 226 uch = ch;
199 clen = 1; 227 clen = 1;
200 } 228 }
201 229
202 if (uch > 0x10FFFFUL) 230 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 { 231 {
207 if (uch > 0xFFFFUL) 232 if (uch > 0xFFFFUL)
208 { 233 {
234 if (uch > 0x10FFFFUL)
235 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
236
209 need (enc, len += 11); 237 need (enc, len += 11);
210 sprintf (enc->cur, "\\u%04x\\u%04x", 238 sprintf (enc->cur, "\\u%04x\\u%04x",
211 (int)((uch - 0x10000) / 0x400 + 0xD800), 239 (int)((uch - 0x10000) / 0x400 + 0xD800),
212 (int)((uch - 0x10000) % 0x400 + 0xDC00)); 240 (int)((uch - 0x10000) % 0x400 + 0xDC00));
213 enc->cur += 12; 241 enc->cur += 12;
224 *enc->cur++ = hexdigit [(uch >> 0) & 15]; 252 *enc->cur++ = hexdigit [(uch >> 0) & 15];
225 } 253 }
226 254
227 str += clen; 255 str += clen;
228 } 256 }
229 else if (enc->flags & F_LATIN1) 257 else if (enc->json.flags & F_LATIN1)
230 { 258 {
231 *enc->cur++ = uch; 259 *enc->cur++ = uch;
232 str += clen; 260 str += clen;
233 } 261 }
234 else if (is_utf8) 262 else if (is_utf8)
241 while (--clen); 269 while (--clen);
242 } 270 }
243 else 271 else
244 { 272 {
245 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
246 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); 274 enc->cur = encode_utf8 (enc->cur, uch);
247 ++str; 275 ++str;
248 } 276 }
249 } 277 }
250 } 278 }
251 } 279 }
252 280
253 --len; 281 --len;
254 } 282 }
255} 283}
256 284
257inline void 285INLINE void
258encode_indent (enc_t *enc) 286encode_indent (enc_t *enc)
259{ 287{
260 if (enc->flags & F_INDENT) 288 if (enc->json.flags & F_INDENT)
261 { 289 {
262 int spaces = enc->indent * INDENT_STEP; 290 int spaces = enc->indent * INDENT_STEP;
263 291
264 need (enc, spaces); 292 need (enc, spaces);
265 memset (enc->cur, ' ', spaces); 293 memset (enc->cur, ' ', spaces);
266 enc->cur += spaces; 294 enc->cur += spaces;
267 } 295 }
268} 296}
269 297
270inline void 298INLINE void
271encode_space (enc_t *enc) 299encode_space (enc_t *enc)
272{ 300{
273 need (enc, 1); 301 need (enc, 1);
274 encode_ch (enc, ' '); 302 encode_ch (enc, ' ');
275} 303}
276 304
277inline void 305INLINE void
278encode_nl (enc_t *enc) 306encode_nl (enc_t *enc)
279{ 307{
280 if (enc->flags & F_INDENT) 308 if (enc->json.flags & F_INDENT)
281 { 309 {
282 need (enc, 1); 310 need (enc, 1);
283 encode_ch (enc, '\n'); 311 encode_ch (enc, '\n');
284 } 312 }
285} 313}
286 314
287inline void 315INLINE void
288encode_comma (enc_t *enc) 316encode_comma (enc_t *enc)
289{ 317{
290 encode_ch (enc, ','); 318 encode_ch (enc, ',');
291 319
292 if (enc->flags & F_INDENT) 320 if (enc->json.flags & F_INDENT)
293 encode_nl (enc); 321 encode_nl (enc);
294 else if (enc->flags & F_SPACE_AFTER) 322 else if (enc->json.flags & F_SPACE_AFTER)
295 encode_space (enc); 323 encode_space (enc);
296} 324}
297 325
298static void encode_sv (enc_t *enc, SV *sv); 326static void encode_sv (enc_t *enc, SV *sv);
299 327
303 int i, len = av_len (av); 331 int i, len = av_len (av);
304 332
305 if (enc->indent >= enc->maxdepth) 333 if (enc->indent >= enc->maxdepth)
306 croak ("data structure too deep (hit recursion limit)"); 334 croak ("data structure too deep (hit recursion limit)");
307 335
308 encode_ch (enc, '['); encode_nl (enc); 336 encode_ch (enc, '[');
309 ++enc->indent; 337
338 if (len >= 0)
339 {
340 encode_nl (enc); ++enc->indent;
310 341
311 for (i = 0; i <= len; ++i) 342 for (i = 0; i <= len; ++i)
312 { 343 {
344 SV **svp = av_fetch (av, i, 0);
345
313 encode_indent (enc); 346 encode_indent (enc);
314 encode_sv (enc, *av_fetch (av, i, 0));
315 347
348 if (svp)
349 encode_sv (enc, *svp);
350 else
351 encode_str (enc, "null", 4, 0);
352
316 if (i < len) 353 if (i < len)
317 encode_comma (enc); 354 encode_comma (enc);
318 } 355 }
319 356
357 encode_nl (enc); --enc->indent; encode_indent (enc);
358 }
359
320 encode_nl (enc); 360 encode_ch (enc, ']');
321
322 --enc->indent;
323 encode_indent (enc); encode_ch (enc, ']');
324} 361}
325 362
326static void 363static void
327encode_he (enc_t *enc, HE *he) 364encode_hk (enc_t *enc, HE *he)
328{ 365{
329 encode_ch (enc, '"'); 366 encode_ch (enc, '"');
330 367
331 if (HeKLEN (he) == HEf_SVKEY) 368 if (HeKLEN (he) == HEf_SVKEY)
332 { 369 {
342 else 379 else
343 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he)); 380 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he));
344 381
345 encode_ch (enc, '"'); 382 encode_ch (enc, '"');
346 383
347 if (enc->flags & F_SPACE_BEFORE) encode_space (enc); 384 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc);
348 encode_ch (enc, ':'); 385 encode_ch (enc, ':');
349 if (enc->flags & F_SPACE_AFTER ) encode_space (enc); 386 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc);
350 encode_sv (enc, HeVAL (he));
351} 387}
352 388
353// compare hash entries, used when all keys are bytestrings 389// compare hash entries, used when all keys are bytestrings
354static int 390static int
355he_cmp_fast (const void *a_, const void *b_) 391he_cmp_fast (const void *a_, const void *b_)
360 HE *b = *(HE **)b_; 396 HE *b = *(HE **)b_;
361 397
362 STRLEN la = HeKLEN (a); 398 STRLEN la = HeKLEN (a);
363 STRLEN lb = HeKLEN (b); 399 STRLEN lb = HeKLEN (b);
364 400
365 if (!(cmp = memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb))) 401 if (!(cmp = memcmp (HeKEY (b), HeKEY (a), lb < la ? lb : la)))
366 cmp = la - lb; 402 cmp = lb - la;
367 403
368 return cmp; 404 return cmp;
369} 405}
370 406
371// 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
372static int 408static int
373he_cmp_slow (const void *a, const void *b) 409he_cmp_slow (const void *a, const void *b)
374{ 410{
375 return sv_cmp (HeSVKEY_force (*(HE **)a), HeSVKEY_force (*(HE **)b)); 411 return sv_cmp (HeSVKEY_force (*(HE **)b), HeSVKEY_force (*(HE **)a));
376} 412}
377 413
378static void 414static void
379encode_hv (enc_t *enc, HV *hv) 415encode_hv (enc_t *enc, HV *hv)
380{ 416{
417 HE *he;
381 int count, i; 418 int count;
382 419
383 if (enc->indent >= enc->maxdepth) 420 if (enc->indent >= enc->maxdepth)
384 croak ("data structure too deep (hit recursion limit)"); 421 croak ("data structure too deep (hit recursion limit)");
385 422
386 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent; 423 encode_ch (enc, '{');
387 424
388 if ((count = hv_iterinit (hv)))
389 {
390 // for canonical output we have to sort by keys first 425 // for canonical output we have to sort by keys first
391 // actually, this is mostly due to the stupid so-called 426 // actually, this is mostly due to the stupid so-called
392 // security workaround added somewhere in 5.8.x. 427 // security workaround added somewhere in 5.8.x.
393 // that randomises hash orderings 428 // that randomises hash orderings
394 if (enc->flags & F_CANONICAL) 429 if (enc->json.flags & F_CANONICAL)
430 {
431 int count = hv_iterinit (hv);
432
433 if (SvMAGICAL (hv))
395 { 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 {
396 int fast = 1; 449 int i, fast = 1;
397 HE *he;
398#if defined(__BORLANDC__) || defined(_MSC_VER) 450#if defined(__BORLANDC__) || defined(_MSC_VER)
399 HE **hes = _alloca (count * sizeof (HE)); 451 HE **hes = _alloca (count * sizeof (HE));
400#else 452#else
401 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
402#endif 454#endif
429 481
430 FREETMPS; 482 FREETMPS;
431 LEAVE; 483 LEAVE;
432 } 484 }
433 485
434 for (i = 0; i < count; ++i) 486 encode_nl (enc); ++enc->indent;
487
488 while (count--)
435 { 489 {
436 encode_indent (enc); 490 encode_indent (enc);
491 he = hes [count];
437 encode_he (enc, hes [i]); 492 encode_hk (enc, he);
493 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
438 494
439 if (i < count - 1) 495 if (count)
440 encode_comma (enc); 496 encode_comma (enc);
441 } 497 }
442 498
443 encode_nl (enc); 499 encode_nl (enc); --enc->indent; encode_indent (enc);
444 } 500 }
501 }
445 else 502 else
503 {
504 if (hv_iterinit (hv) || SvMAGICAL (hv))
505 if ((he = hv_iternext (hv)))
446 { 506 {
447 HE *he = hv_iternext (hv); 507 encode_nl (enc); ++enc->indent;
448 508
449 for (;;) 509 for (;;)
450 { 510 {
451 encode_indent (enc); 511 encode_indent (enc);
452 encode_he (enc, he); 512 encode_hk (enc, he);
513 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
453 514
454 if (!(he = hv_iternext (hv))) 515 if (!(he = hv_iternext (hv)))
455 break; 516 break;
456 517
457 encode_comma (enc); 518 encode_comma (enc);
458 } 519 }
459 520
460 encode_nl (enc); 521 encode_nl (enc); --enc->indent; encode_indent (enc);
461 } 522 }
462 } 523 }
463 524
464 --enc->indent; encode_indent (enc); encode_ch (enc, '}'); 525 encode_ch (enc, '}');
465} 526}
466 527
467// encode objects, arrays and special \0=false and \1=true values. 528// encode objects, arrays and special \0=false and \1=true values.
468static void 529static void
469encode_rv (enc_t *enc, SV *sv) 530encode_rv (enc_t *enc, SV *sv)
473 SvGETMAGIC (sv); 534 SvGETMAGIC (sv);
474 svt = SvTYPE (sv); 535 svt = SvTYPE (sv);
475 536
476 if (expect_false (SvOBJECT (sv))) 537 if (expect_false (SvOBJECT (sv)))
477 { 538 {
539 HV *stash = !JSON_SLOW || json_boolean_stash
540 ? json_boolean_stash
541 : gv_stashpv ("JSON::XS::Boolean", 1);
542
478 if (SvSTASH (sv) == json_boolean_stash) 543 if (SvSTASH (sv) == stash)
479 { 544 {
480 if (SvIV (sv) == 0) 545 if (SvIV (sv))
546 encode_str (enc, "true", 4, 0);
547 else
481 encode_str (enc, "false", 5, 0); 548 encode_str (enc, "false", 5, 0);
482 else
483 encode_str (enc, "true", 4, 0);
484 } 549 }
485 else 550 else
486 { 551 {
487#if 0 552#if 0
488 if (0 && sv_derived_from (rv, "JSON::Literal")) 553 if (0 && sv_derived_from (rv, "JSON::Literal"))
489 { 554 {
490 // not yet 555 // not yet
491 } 556 }
492#endif 557#endif
493 if (enc->flags & F_CONV_BLESSED) 558 if (enc->json.flags & F_CONV_BLESSED)
494 { 559 {
495 // we re-bless the reference to get overload and other niceties right 560 // we re-bless the reference to get overload and other niceties right
496 GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 1); 561 GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 0);
497 562
498 if (to_json) 563 if (to_json)
499 { 564 {
500 dSP; 565 dSP;
501 ENTER; 566
502 SAVETMPS;
503 PUSHMARK (SP); 567 ENTER; SAVETMPS; PUSHMARK (SP);
504 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv))); 568 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv)));
505 569
506 // calling with G_SCALAR ensures that we always get a 1 reutrn value 570 // calling with G_SCALAR ensures that we always get a 1 return value
507 // check anyways.
508 PUTBACK; 571 PUTBACK;
509 assert (1 == call_sv ((SV *)GvCV (to_json), G_SCALAR)); 572 call_sv ((SV *)GvCV (to_json), G_SCALAR);
510 SPAGAIN; 573 SPAGAIN;
511 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
512 encode_sv (enc, POPs); 582 encode_sv (enc, sv);
513 583
514 FREETMPS; 584 FREETMPS; LEAVE;
515 LEAVE;
516 } 585 }
517 else if (enc->flags & F_ALLOW_BLESSED) 586 else if (enc->json.flags & F_ALLOW_BLESSED)
518 encode_str (enc, "null", 4, 0); 587 encode_str (enc, "null", 4, 0);
519 else 588 else
520 croak ("encountered object '%s', but neither allow_blessed enabled nor TO_JSON method available on it", 589 croak ("encountered object '%s', but neither allow_blessed enabled nor TO_JSON method available on it",
521 SvPV_nolen (sv_2mortal (newRV_inc (sv)))); 590 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
522 } 591 }
523 else if (enc->flags & F_ALLOW_BLESSED) 592 else if (enc->json.flags & F_ALLOW_BLESSED)
524 encode_str (enc, "null", 4, 0); 593 encode_str (enc, "null", 4, 0);
525 else 594 else
526 croak ("encountered object '%s', but neither allow_blessed nor convert_blessed settings are enabled", 595 croak ("encountered object '%s', but neither allow_blessed nor convert_blessed settings are enabled",
527 SvPV_nolen (sv_2mortal (newRV_inc (sv)))); 596 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
528 } 597 }
531 encode_hv (enc, (HV *)sv); 600 encode_hv (enc, (HV *)sv);
532 else if (svt == SVt_PVAV) 601 else if (svt == SVt_PVAV)
533 encode_av (enc, (AV *)sv); 602 encode_av (enc, (AV *)sv);
534 else if (svt < SVt_PVAV) 603 else if (svt < SVt_PVAV)
535 { 604 {
536 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')
537 encode_str (enc, "false", 5, 0); 611 encode_str (enc, "false", 5, 0);
538 else if (SvNIOK (sv) && SvIV (sv) == 1)
539 encode_str (enc, "true", 4, 0);
540 else 612 else
541 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",
542 SvPV_nolen (sv_2mortal (newRV_inc (sv)))); 614 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
543 } 615 }
544 else 616 else
614 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",
615 SvPV_nolen (sv), SvFLAGS (sv)); 687 SvPV_nolen (sv), SvFLAGS (sv));
616} 688}
617 689
618static SV * 690static SV *
619encode_json (SV *scalar, U32 flags) 691encode_json (SV *scalar, JSON *json)
620{ 692{
621 enc_t enc; 693 enc_t enc;
622 694
623 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar)) 695 if (!(json->flags & F_ALLOW_NONREF) && !SvROK (scalar))
624 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)");
625 697
626 enc.flags = flags; 698 enc.json = *json;
627 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 699 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
628 enc.cur = SvPVX (enc.sv); 700 enc.cur = SvPVX (enc.sv);
629 enc.end = SvEND (enc.sv); 701 enc.end = SvEND (enc.sv);
630 enc.indent = 0; 702 enc.indent = 0;
631 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;
632 707
633 SvPOK_only (enc.sv); 708 SvPOK_only (enc.sv);
634 encode_sv (&enc, scalar); 709 encode_sv (&enc, scalar);
635 710
636 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); 711 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
637 *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
638 713
639 if (!(flags & (F_ASCII | F_LATIN1 | F_UTF8))) 714 if (!(enc.json.flags & (F_ASCII | F_LATIN1 | F_UTF8)))
640 SvUTF8_on (enc.sv); 715 SvUTF8_on (enc.sv);
641 716
642 if (enc.flags & F_SHRINK) 717 if (enc.json.flags & F_SHRINK)
643 shrink (enc.sv); 718 shrink (enc.sv);
644 719
645 return enc.sv; 720 return enc.sv;
646} 721}
647 722
652typedef struct 727typedef struct
653{ 728{
654 char *cur; // current parser pointer 729 char *cur; // current parser pointer
655 char *end; // end of input string 730 char *end; // end of input string
656 const char *err; // parse error, if != 0 731 const char *err; // parse error, if != 0
657 U32 flags; // F_* 732 JSON json;
658 U32 depth; // recursion depth 733 U32 depth; // recursion depth
659 U32 maxdepth; // recursion depth limit 734 U32 maxdepth; // recursion depth limit
660} dec_t; 735} dec_t;
661 736
662inline 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
663decode_ws (dec_t *dec) 747decode_ws (dec_t *dec)
664{ 748{
665 for (;;) 749 for (;;)
666 { 750 {
667 char ch = *dec->cur; 751 char ch = *dec->cur;
668 752
669 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 }
670 || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)) 765 else if (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)
671 break; 766 break; // parse error, but let higher level handle it, gives better error messages
672 767
673 ++dec->cur; 768 ++dec->cur;
674 } 769 }
675} 770}
676 771
782 877
783 if (hi >= 0x80) 878 if (hi >= 0x80)
784 { 879 {
785 utf8 = 1; 880 utf8 = 1;
786 881
787 cur = (char *)uvuni_to_utf8_flags (cur, hi, 0); 882 cur = encode_utf8 (cur, hi);
788 } 883 }
789 else 884 else
790 *cur++ = hi; 885 *cur++ = hi;
791 } 886 }
792 break; 887 break;
925 is_nv = 1; 1020 is_nv = 1;
926 } 1021 }
927 1022
928 if (!is_nv) 1023 if (!is_nv)
929 { 1024 {
1025 int len = dec->cur - start;
1026
930 // 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
931 if (*start == '-') 1028 if (*start == '-')
932 switch (dec->cur - start) 1029 switch (len)
933 { 1030 {
934 case 2: return newSViv (-( start [1] - '0' * 1)); 1031 case 2: return newSViv (-( start [1] - '0' * 1));
935 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11)); 1032 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)); 1033 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)); 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));
938 } 1036 }
939 else 1037 else
940 switch (dec->cur - start) 1038 switch (len)
941 { 1039 {
942 case 1: return newSViv ( start [0] - '0' * 1); 1040 case 1: return newSViv ( start [0] - '0' * 1);
943 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11); 1041 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); 1042 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); 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);
946 } 1045 }
947 1046
948 { 1047 {
949 UV uv; 1048 UV uv;
950 int numtype = grok_number (start, dec->cur - start, &uv); 1049 int numtype = grok_number (start, len, &uv);
951 if (numtype & IS_NUMBER_IN_UV) 1050 if (numtype & IS_NUMBER_IN_UV)
952 if (numtype & IS_NUMBER_NEG) 1051 if (numtype & IS_NUMBER_NEG)
953 { 1052 {
954 if (uv < (UV)IV_MIN) 1053 if (uv < (UV)IV_MIN)
955 return newSViv (-(IV)uv); 1054 return newSViv (-(IV)uv);
956 } 1055 }
957 else 1056 else
958 return newSVuv (uv); 1057 return newSVuv (uv);
959
960 // here would likely be the place for bigint support
961 } 1058 }
962 }
963 1059
964 // 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
965 return newSVnv (Atof (start)); 1076 return newSVnv (Atof (start));
966 1077
967fail: 1078fail:
968 return 0; 1079 return 0;
969} 1080}
999 1110
1000 if (*dec->cur != ',') 1111 if (*dec->cur != ',')
1001 ERR (", or ] expected while parsing array"); 1112 ERR (", or ] expected while parsing array");
1002 1113
1003 ++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 }
1004 } 1123 }
1005 1124
1006 DEC_DEC_DEPTH; 1125 DEC_DEC_DEPTH;
1007 return newRV_noinc ((SV *)av); 1126 return newRV_noinc ((SV *)av);
1008 1127
1013} 1132}
1014 1133
1015static SV * 1134static SV *
1016decode_hv (dec_t *dec) 1135decode_hv (dec_t *dec)
1017{ 1136{
1137 SV *sv;
1018 HV *hv = newHV (); 1138 HV *hv = newHV ();
1019 1139
1020 DEC_INC_DEPTH; 1140 DEC_INC_DEPTH;
1021 decode_ws (dec); 1141 decode_ws (dec);
1022 1142
1023 if (*dec->cur == '}') 1143 if (*dec->cur == '}')
1024 ++dec->cur; 1144 ++dec->cur;
1025 else 1145 else
1026 for (;;) 1146 for (;;)
1027 { 1147 {
1028 decode_ws (dec); EXPECT_CH ('"'); 1148 EXPECT_CH ('"');
1029 1149
1030 // heuristic: assume that 1150 // heuristic: assume that
1031 // a) decode_str + hv_store_ent are abysmally slow 1151 // a) decode_str + hv_store_ent are abysmally slow.
1032 // b) most hash keys are short, simple ascii text 1152 // b) most hash keys are short, simple ascii text.
1033 // so try to "fast-match" such strings to avoid 1153 // => try to "fast-match" such strings to avoid
1034 // the overhead of hv_store_ent. 1154 // the overhead of decode_str + hv_store_ent.
1035 { 1155 {
1036 SV *value; 1156 SV *value;
1037 char *p = dec->cur; 1157 char *p = dec->cur;
1038 char *e = p + 24; // only try up to 24 bytes 1158 char *e = p + 24; // only try up to 24 bytes
1039 1159
1040 for (;;) 1160 for (;;)
1041 { 1161 {
1162 // the >= 0x80 is true on most architectures
1042 if (p == e || *p < 0x20 || *p >= 0x80 || *p == '\\') 1163 if (p == e || *p < 0x20 || *p >= 0x80 || *p == '\\')
1043 { 1164 {
1044 // slow path, back up and use decode_str 1165 // slow path, back up and use decode_str
1045 SV *key = decode_str (dec); 1166 SV *key = decode_str (dec);
1046 if (!key) 1167 if (!key)
1047 goto fail; 1168 goto fail;
1048 1169
1049 decode_ws (dec); EXPECT_CH (':'); 1170 decode_ws (dec); EXPECT_CH (':');
1050 1171
1172 decode_ws (dec);
1051 value = decode_sv (dec); 1173 value = decode_sv (dec);
1052 if (!value) 1174 if (!value)
1053 { 1175 {
1054 SvREFCNT_dec (key); 1176 SvREFCNT_dec (key);
1055 goto fail; 1177 goto fail;
1067 int len = p - key; 1189 int len = p - key;
1068 dec->cur = p + 1; 1190 dec->cur = p + 1;
1069 1191
1070 decode_ws (dec); EXPECT_CH (':'); 1192 decode_ws (dec); EXPECT_CH (':');
1071 1193
1194 decode_ws (dec);
1072 value = decode_sv (dec); 1195 value = decode_sv (dec);
1073 if (!value) 1196 if (!value)
1074 goto fail; 1197 goto fail;
1075 1198
1076 hv_store (hv, key, len, value, 0); 1199 hv_store (hv, key, len, value, 0);
1092 1215
1093 if (*dec->cur != ',') 1216 if (*dec->cur != ',')
1094 ERR (", or } expected while parsing object/hash"); 1217 ERR (", or } expected while parsing object/hash");
1095 1218
1096 ++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 }
1097 } 1228 }
1098 1229
1099 DEC_DEC_DEPTH; 1230 DEC_DEC_DEPTH;
1100 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;
1101 1292
1102fail: 1293fail:
1103 SvREFCNT_dec (hv); 1294 SvREFCNT_dec (hv);
1104 DEC_DEC_DEPTH; 1295 DEC_DEC_DEPTH;
1105 return 0; 1296 return 0;
1106} 1297}
1107 1298
1108static SV * 1299static SV *
1109decode_sv (dec_t *dec) 1300decode_sv (dec_t *dec)
1110{ 1301{
1111 decode_ws (dec);
1112
1113 // the beauty of JSON: you need exactly one character lookahead 1302 // the beauty of JSON: you need exactly one character lookahead
1114 // to parse anything. 1303 // to parse anything.
1115 switch (*dec->cur) 1304 switch (*dec->cur)
1116 { 1305 {
1117 case '"': ++dec->cur; return decode_str (dec); 1306 case '"': ++dec->cur; return decode_str (dec);
1125 1314
1126 case 't': 1315 case 't':
1127 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1316 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
1128 { 1317 {
1129 dec->cur += 4; 1318 dec->cur += 4;
1319#if JSON_SLOW
1320 json_true = get_sv ("JSON::XS::true", 1); SvREADONLY_on (json_true);
1321#endif
1130 return SvREFCNT_inc (json_true); 1322 return SvREFCNT_inc (json_true);
1131 } 1323 }
1132 else 1324 else
1133 ERR ("'true' expected"); 1325 ERR ("'true' expected");
1134 1326
1136 1328
1137 case 'f': 1329 case 'f':
1138 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1330 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
1139 { 1331 {
1140 dec->cur += 5; 1332 dec->cur += 5;
1333#if JSON_SLOW
1334 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1335#endif
1141 return SvREFCNT_inc (json_false); 1336 return SvREFCNT_inc (json_false);
1142 } 1337 }
1143 else 1338 else
1144 ERR ("'false' expected"); 1339 ERR ("'false' expected");
1145 1340
1164fail: 1359fail:
1165 return 0; 1360 return 0;
1166} 1361}
1167 1362
1168static SV * 1363static SV *
1169decode_json (SV *string, U32 flags, UV *offset_return) 1364decode_json (SV *string, JSON *json, UV *offset_return)
1170{ 1365{
1171 dec_t dec; 1366 dec_t dec;
1172 UV offset; 1367 UV offset;
1173 SV *sv; 1368 SV *sv;
1174 1369
1175 SvGETMAGIC (string); 1370 SvGETMAGIC (string);
1176 SvUPGRADE (string, SVt_PV); 1371 SvUPGRADE (string, SVt_PV);
1177 1372
1178 if (flags & F_MAXSIZE && SvCUR (string) > DEC_SIZE (flags)) 1373 if (json->flags & F_MAXSIZE && SvCUR (string) > DEC_SIZE (json->flags))
1179 croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu", 1374 croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu",
1180 (unsigned long)SvCUR (string), (unsigned long)DEC_SIZE (flags)); 1375 (unsigned long)SvCUR (string), (unsigned long)DEC_SIZE (json->flags));
1181 1376
1182 if (flags & F_UTF8) 1377 if (json->flags & F_UTF8)
1183 sv_utf8_downgrade (string, 0); 1378 sv_utf8_downgrade (string, 0);
1184 else 1379 else
1185 sv_utf8_upgrade (string); 1380 sv_utf8_upgrade (string);
1186 1381
1187 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP 1382 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
1188 1383
1189 dec.flags = flags; 1384 dec.json = *json;
1190 dec.cur = SvPVX (string); 1385 dec.cur = SvPVX (string);
1191 dec.end = SvEND (string); 1386 dec.end = SvEND (string);
1192 dec.err = 0; 1387 dec.err = 0;
1193 dec.depth = 0; 1388 dec.depth = 0;
1194 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;
1195 1393
1196 *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);
1197 sv = decode_sv (&dec); 1397 sv = decode_sv (&dec);
1198 1398
1199 if (!(offset_return || !sv)) 1399 if (!(offset_return || !sv))
1200 { 1400 {
1201 // check for trailing garbage 1401 // check for trailing garbage
1209 } 1409 }
1210 } 1410 }
1211 1411
1212 if (offset_return || !sv) 1412 if (offset_return || !sv)
1213 { 1413 {
1214 offset = dec.flags & F_UTF8 1414 offset = dec.json.flags & F_UTF8
1215 ? dec.cur - SvPVX (string) 1415 ? dec.cur - SvPVX (string)
1216 : utf8_distance (dec.cur, SvPVX (string)); 1416 : utf8_distance (dec.cur, SvPVX (string));
1217 1417
1218 if (offset_return) 1418 if (offset_return)
1219 *offset_return = offset; 1419 *offset_return = offset;
1238 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); 1438 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
1239 } 1439 }
1240 1440
1241 sv = sv_2mortal (sv); 1441 sv = sv_2mortal (sv);
1242 1442
1243 if (!(dec.flags & F_ALLOW_NONREF) && !SvROK (sv)) 1443 if (!(dec.json.flags & F_ALLOW_NONREF) && !SvROK (sv))
1244 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)");
1245 1445
1246 return sv; 1446 return sv;
1247} 1447}
1248 1448
1269 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false); 1469 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1270} 1470}
1271 1471
1272PROTOTYPES: DISABLE 1472PROTOTYPES: DISABLE
1273 1473
1274SV *new (char *dummy) 1474void CLONE (...)
1275 CODE: 1475 CODE:
1276 RETVAL = sv_bless (newRV_noinc (newSVuv (F_DEFAULT)), json_stash); 1476 json_stash = 0;
1277 OUTPUT: 1477 json_boolean_stash = 0;
1278 RETVAL
1279 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
1280SV *ascii (SV *self, int enable = 1) 1492void ascii (JSON *self, int enable = 1)
1281 ALIAS: 1493 ALIAS:
1282 ascii = F_ASCII 1494 ascii = F_ASCII
1283 latin1 = F_LATIN1 1495 latin1 = F_LATIN1
1284 utf8 = F_UTF8 1496 utf8 = F_UTF8
1285 indent = F_INDENT 1497 indent = F_INDENT
1289 pretty = F_PRETTY 1501 pretty = F_PRETTY
1290 allow_nonref = F_ALLOW_NONREF 1502 allow_nonref = F_ALLOW_NONREF
1291 shrink = F_SHRINK 1503 shrink = F_SHRINK
1292 allow_blessed = F_ALLOW_BLESSED 1504 allow_blessed = F_ALLOW_BLESSED
1293 convert_blessed = F_CONV_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)
1294 CODE: 1550 CODE:
1295{ 1551 RETVAL = DEC_DEPTH (self->flags);
1296 UV *uv = SvJSON (self);
1297 if (enable)
1298 *uv |= ix;
1299 else
1300 *uv &= ~ix;
1301
1302 RETVAL = newSVsv (self);
1303}
1304 OUTPUT: 1552 OUTPUT:
1305 RETVAL 1553 RETVAL
1306 1554
1307SV *max_depth (SV *self, UV max_depth = 0x80000000UL) 1555void max_size (JSON *self, UV max_size = 0)
1556 PPCODE:
1557{
1558 UV log2 = 0;
1559
1560 if (max_size > 0x80000000UL) max_size = 0x80000000UL;
1561 if (max_size == 1) max_size = 2;
1562
1563 while ((1UL << log2) < max_size)
1564 ++log2;
1565
1566 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE);
1567
1568 XPUSHs (ST (0));
1569}
1570
1571int get_max_size (JSON *self)
1308 CODE: 1572 CODE:
1309{ 1573 RETVAL = DEC_SIZE (self->flags);
1310 UV *uv = SvJSON (self);
1311 UV log2 = 0;
1312
1313 if (max_depth > 0x80000000UL) max_depth = 0x80000000UL;
1314
1315 while ((1UL << log2) < max_depth)
1316 ++log2;
1317
1318 *uv = *uv & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1319
1320 RETVAL = newSVsv (self);
1321}
1322 OUTPUT: 1574 OUTPUT:
1323 RETVAL 1575 RETVAL
1324 1576
1325SV *max_size (SV *self, UV max_size = 0) 1577void filter_json_object (JSON *self, SV *cb = &PL_sv_undef)
1326 CODE:
1327{
1328 UV *uv = SvJSON (self);
1329 UV log2 = 0;
1330
1331 if (max_size > 0x80000000UL) max_size = 0x80000000UL;
1332 if (max_size == 1) max_size = 2;
1333
1334 while ((1UL << log2) < max_size)
1335 ++log2;
1336
1337 *uv = *uv & ~F_MAXSIZE | (log2 << S_MAXSIZE);
1338
1339 RETVAL = newSVsv (self);
1340}
1341 OUTPUT:
1342 RETVAL
1343
1344void encode (SV *self, SV *scalar)
1345 PPCODE: 1578 PPCODE:
1346 XPUSHs (encode_json (scalar, *SvJSON (self))); 1579{
1580 SvREFCNT_dec (self->cb_object);
1581 self->cb_object = SvOK (cb) ? newSVsv (cb) : 0;
1347 1582
1348void 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)
1349 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:
1350 XPUSHs (decode_json (jsonstr, *SvJSON (self), 0)); 1614 XPUSHs (decode_json (jsonstr, self, 0));
1351 1615
1352void decode_prefix (SV *self, SV *jsonstr) 1616void decode_prefix (JSON *self, SV *jsonstr)
1353 PPCODE: 1617 PPCODE:
1354{ 1618{
1355 UV offset; 1619 UV offset;
1356 EXTEND (SP, 2); 1620 EXTEND (SP, 2);
1357 PUSHs (decode_json (jsonstr, *SvJSON (self), &offset)); 1621 PUSHs (decode_json (jsonstr, self, &offset));
1358 PUSHs (sv_2mortal (newSVuv (offset))); 1622 PUSHs (sv_2mortal (newSVuv (offset)));
1359} 1623}
1360 1624
1625void DESTROY (JSON *self)
1626 CODE:
1627 SvREFCNT_dec (self->cb_sk_object);
1628 SvREFCNT_dec (self->cb_object);
1629
1361PROTOTYPES: ENABLE 1630PROTOTYPES: ENABLE
1362 1631
1363void to_json (SV *scalar) 1632void encode_json (SV *scalar)
1364 ALIAS:
1365 objToJson = 0
1366 PPCODE: 1633 PPCODE:
1634{
1635 JSON json = { F_DEFAULT | F_UTF8 };
1367 XPUSHs (encode_json (scalar, F_DEFAULT | F_UTF8)); 1636 XPUSHs (encode_json (scalar, &json));
1637}
1368 1638
1369void from_json (SV *jsonstr) 1639void decode_json (SV *jsonstr)
1370 ALIAS:
1371 jsonToObj = 0
1372 PPCODE: 1640 PPCODE:
1641{
1642 JSON json = { F_DEFAULT | F_UTF8 };
1373 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8, 0)); 1643 XPUSHs (decode_json (jsonstr, &json, 0));
1644}
1374 1645

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines