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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines