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.13 by root, Sat Mar 24 22:55:16 2007 UTC vs.
Revision 1.48 by root, Sun Jul 1 22:20:00 2007 UTC

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 9
10#if defined(__BORLANDC__) || defined(_MSC_VER)
11# define snprintf _snprintf // C compilers have this in stdio.h
12#endif
13
14// some old perls do not have this, try to make it work, no
15// guarentees, though. if it breaks, you get to keep the pieces.
16#ifndef UTF8_MAXBYTES
17# define UTF8_MAXBYTES 13
18#endif
19
9#define F_ASCII 0x00000001 20#define F_ASCII 0x00000001UL
21#define F_LATIN1 0x00000002UL
10#define F_UTF8 0x00000002 22#define F_UTF8 0x00000004UL
11#define F_INDENT 0x00000004 23#define F_INDENT 0x00000008UL
12#define F_CANONICAL 0x00000008 24#define F_CANONICAL 0x00000010UL
13#define F_SPACE_BEFORE 0x00000010 25#define F_SPACE_BEFORE 0x00000020UL
14#define F_SPACE_AFTER 0x00000020 26#define F_SPACE_AFTER 0x00000040UL
15#define F_ALLOW_NONREF 0x00000080 27#define F_ALLOW_NONREF 0x00000100UL
16#define F_SHRINK 0x00000100 28#define F_SHRINK 0x00000200UL
29#define F_ALLOW_BLESSED 0x00000400UL
30#define F_CONV_BLESSED 0x00000800UL // NYI
31#define F_MAXDEPTH 0xf8000000UL
32#define S_MAXDEPTH 27
33#define F_MAXSIZE 0x01f00000UL
34#define S_MAXSIZE 20
35
36#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH))
37#define DEC_SIZE(flags) (1UL << ((flags & F_MAXSIZE ) >> S_MAXSIZE ))
17 38
18#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER 39#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER
19#define F_DEFAULT 0 40#define F_DEFAULT (9UL << S_MAXDEPTH)
20 41
21#define INIT_SIZE 32 // initial scalar size to be allocated 42#define INIT_SIZE 32 // initial scalar size to be allocated
22#define INDENT_STEP 3 // spaces per indentation level 43#define INDENT_STEP 3 // spaces per indentation level
23 44
24#define UTF8_MAX_LEN 11 // for perls UTF-X: max. number of octets per character
25#define SHORT_STRING_LEN 256 // special-case strings of up to this size 45#define SHORT_STRING_LEN 16384 // special-case strings of up to this size
26 46
27#define SB do { 47#define SB do {
28#define SE } while (0) 48#define SE } while (0)
29 49
50#if __GNUC__ >= 3
51# define expect(expr,value) __builtin_expect ((expr),(value))
52# define inline inline
53#else
54# define expect(expr,value) (expr)
55# define inline static
56#endif
57
58#define expect_false(expr) expect ((expr) != 0, 0)
59#define expect_true(expr) expect ((expr) != 0, 1)
60
30static HV *json_stash; // JSON::XS:: 61static HV *json_stash, *json_boolean_stash; // JSON::XS::
62static SV *json_true, *json_false;
63
64typedef struct {
65 U32 flags;
66} JSON;
31 67
32///////////////////////////////////////////////////////////////////////////// 68/////////////////////////////////////////////////////////////////////////////
33// utility functions 69// utility functions
34 70
35static UV * 71inline void
36SvJSON (SV *sv)
37{
38 if (!(SvROK (sv) && SvOBJECT (SvRV (sv)) && SvSTASH (SvRV (sv)) == json_stash))
39 croak ("object is not of type JSON::XS");
40
41 return &SvUVX (SvRV (sv));
42}
43
44static void
45shrink (SV *sv) 72shrink (SV *sv)
46{ 73{
47 sv_utf8_downgrade (sv, 1); 74 sv_utf8_downgrade (sv, 1);
48 if (SvLEN (sv) > SvCUR (sv) + 1) 75 if (SvLEN (sv) > SvCUR (sv) + 1)
49 { 76 {
58// decode an utf-8 character and return it, or (UV)-1 in 85// decode an utf-8 character and return it, or (UV)-1 in
59// case of an error. 86// case of an error.
60// we special-case "safe" characters from U+80 .. U+7FF, 87// we special-case "safe" characters from U+80 .. U+7FF,
61// but use the very good perl function to parse anything else. 88// but use the very good perl function to parse anything else.
62// note that we never call this function for a ascii codepoints 89// note that we never call this function for a ascii codepoints
63static UV 90inline UV
64decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen) 91decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
65{ 92{
66 if (s[0] > 0xdf || s[0] < 0xc2) 93 if (expect_false (s[0] > 0xdf || s[0] < 0xc2))
67 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY); 94 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY);
68 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf) 95 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf)
69 { 96 {
70 *clen = 2; 97 *clen = 2;
71 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f); 98 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
72 } 99 }
73 else 100 else
101 {
102 *clen = (STRLEN)-1;
74 return (UV)-1; 103 return (UV)-1;
104 }
75} 105}
76 106
77///////////////////////////////////////////////////////////////////////////// 107/////////////////////////////////////////////////////////////////////////////
78// encoder 108// encoder
79 109
81typedef struct 111typedef struct
82{ 112{
83 char *cur; // SvPVX (sv) + current output position 113 char *cur; // SvPVX (sv) + current output position
84 char *end; // SvEND (sv) 114 char *end; // SvEND (sv)
85 SV *sv; // result scalar 115 SV *sv; // result scalar
86 UV flags; // F_* 116 JSON json;
87 int indent; // indentation level 117 U32 indent; // indentation level
88 int max_depth; // max. recursion level 118 U32 maxdepth; // max. indentation/recursion level
89} enc_t; 119} enc_t;
90 120
91static void 121inline void
92need (enc_t *enc, STRLEN len) 122need (enc_t *enc, STRLEN len)
93{ 123{
94 if (enc->cur + len >= enc->end) 124 if (expect_false (enc->cur + len >= enc->end))
95 { 125 {
96 STRLEN cur = enc->cur - SvPVX (enc->sv); 126 STRLEN cur = enc->cur - SvPVX (enc->sv);
97 SvGROW (enc->sv, cur + len + 1); 127 SvGROW (enc->sv, cur + len + 1);
98 enc->cur = SvPVX (enc->sv) + cur; 128 enc->cur = SvPVX (enc->sv) + cur;
99 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv); 129 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
100 } 130 }
101} 131}
102 132
103static void 133inline void
104encode_ch (enc_t *enc, char ch) 134encode_ch (enc_t *enc, char ch)
105{ 135{
106 need (enc, 1); 136 need (enc, 1);
107 *enc->cur++ = ch; 137 *enc->cur++ = ch;
108} 138}
116 146
117 while (str < end) 147 while (str < end)
118 { 148 {
119 unsigned char ch = *(unsigned char *)str; 149 unsigned char ch = *(unsigned char *)str;
120 150
121 if (ch >= 0x20 && ch < 0x80) // most common case 151 if (expect_true (ch >= 0x20 && ch < 0x80)) // most common case
122 { 152 {
123 if (ch == '"') // but with slow exceptions 153 if (expect_false (ch == '"')) // but with slow exceptions
124 { 154 {
125 need (enc, len += 1); 155 need (enc, len += 1);
126 *enc->cur++ = '\\'; 156 *enc->cur++ = '\\';
127 *enc->cur++ = '"'; 157 *enc->cur++ = '"';
128 } 158 }
129 else if (ch == '\\') 159 else if (expect_false (ch == '\\'))
130 { 160 {
131 need (enc, len += 1); 161 need (enc, len += 1);
132 *enc->cur++ = '\\'; 162 *enc->cur++ = '\\';
133 *enc->cur++ = '\\'; 163 *enc->cur++ = '\\';
134 } 164 }
152 STRLEN clen; 182 STRLEN clen;
153 UV uch; 183 UV uch;
154 184
155 if (is_utf8) 185 if (is_utf8)
156 { 186 {
157 //uch = utf8n_to_uvuni (str, end - str, &clen, UTF8_CHECK_ONLY);
158 uch = decode_utf8 (str, end - str, &clen); 187 uch = decode_utf8 (str, end - str, &clen);
159 if (clen == (STRLEN)-1) 188 if (clen == (STRLEN)-1)
160 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str); 189 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str);
161 } 190 }
162 else 191 else
166 } 195 }
167 196
168 if (uch > 0x10FFFFUL) 197 if (uch > 0x10FFFFUL)
169 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch); 198 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
170 199
171 if (uch < 0x80 || enc->flags & F_ASCII) 200 if (uch < 0x80 || enc->json.flags & F_ASCII || (enc->json.flags & F_LATIN1 && uch > 0xFF))
172 { 201 {
173 if (uch > 0xFFFFUL) 202 if (uch > 0xFFFFUL)
174 { 203 {
175 need (enc, len += 11); 204 need (enc, len += 11);
176 sprintf (enc->cur, "\\u%04x\\u%04x", 205 sprintf (enc->cur, "\\u%04x\\u%04x",
190 *enc->cur++ = hexdigit [(uch >> 0) & 15]; 219 *enc->cur++ = hexdigit [(uch >> 0) & 15];
191 } 220 }
192 221
193 str += clen; 222 str += clen;
194 } 223 }
224 else if (enc->json.flags & F_LATIN1)
225 {
226 *enc->cur++ = uch;
227 str += clen;
228 }
195 else if (is_utf8) 229 else if (is_utf8)
196 { 230 {
197 need (enc, len += clen); 231 need (enc, len += clen);
198 do 232 do
199 { 233 {
201 } 235 }
202 while (--clen); 236 while (--clen);
203 } 237 }
204 else 238 else
205 { 239 {
206 need (enc, len += UTF8_MAX_LEN - 1); // never more than 11 bytes needed 240 need (enc, len += UTF8_MAXBYTES - 1); // never more than 11 bytes needed
207 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); 241 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0);
208 ++str; 242 ++str;
209 } 243 }
210 } 244 }
211 } 245 }
213 247
214 --len; 248 --len;
215 } 249 }
216} 250}
217 251
218static void 252inline void
219encode_indent (enc_t *enc) 253encode_indent (enc_t *enc)
220{ 254{
221 if (enc->flags & F_INDENT) 255 if (enc->json.flags & F_INDENT)
222 { 256 {
223 int spaces = enc->indent * INDENT_STEP; 257 int spaces = enc->indent * INDENT_STEP;
224 258
225 need (enc, spaces); 259 need (enc, spaces);
226 memset (enc->cur, ' ', spaces); 260 memset (enc->cur, ' ', spaces);
227 enc->cur += spaces; 261 enc->cur += spaces;
228 } 262 }
229} 263}
230 264
231static void 265inline void
232encode_space (enc_t *enc) 266encode_space (enc_t *enc)
233{ 267{
234 need (enc, 1); 268 need (enc, 1);
235 encode_ch (enc, ' '); 269 encode_ch (enc, ' ');
236} 270}
237 271
238static void 272inline void
239encode_nl (enc_t *enc) 273encode_nl (enc_t *enc)
240{ 274{
241 if (enc->flags & F_INDENT) 275 if (enc->json.flags & F_INDENT)
242 { 276 {
243 need (enc, 1); 277 need (enc, 1);
244 encode_ch (enc, '\n'); 278 encode_ch (enc, '\n');
245 } 279 }
246} 280}
247 281
248static void 282inline void
249encode_comma (enc_t *enc) 283encode_comma (enc_t *enc)
250{ 284{
251 encode_ch (enc, ','); 285 encode_ch (enc, ',');
252 286
253 if (enc->flags & F_INDENT) 287 if (enc->json.flags & F_INDENT)
254 encode_nl (enc); 288 encode_nl (enc);
255 else if (enc->flags & F_SPACE_AFTER) 289 else if (enc->json.flags & F_SPACE_AFTER)
256 encode_space (enc); 290 encode_space (enc);
257} 291}
258 292
259static void encode_sv (enc_t *enc, SV *sv); 293static void encode_sv (enc_t *enc, SV *sv);
260 294
261static void 295static void
262encode_av (enc_t *enc, AV *av) 296encode_av (enc_t *enc, AV *av)
263{ 297{
264 int i, len = av_len (av); 298 int i, len = av_len (av);
299
300 if (enc->indent >= enc->maxdepth)
301 croak ("data structure too deep (hit recursion limit)");
265 302
266 encode_ch (enc, '['); encode_nl (enc); 303 encode_ch (enc, '['); encode_nl (enc);
267 ++enc->indent; 304 ++enc->indent;
268 305
269 for (i = 0; i <= len; ++i) 306 for (i = 0; i <= len; ++i)
300 else 337 else
301 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he)); 338 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he));
302 339
303 encode_ch (enc, '"'); 340 encode_ch (enc, '"');
304 341
305 if (enc->flags & F_SPACE_BEFORE) encode_space (enc); 342 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc);
306 encode_ch (enc, ':'); 343 encode_ch (enc, ':');
307 if (enc->flags & F_SPACE_AFTER ) encode_space (enc); 344 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc);
308 encode_sv (enc, HeVAL (he)); 345 encode_sv (enc, HeVAL (he));
309} 346}
310 347
311// compare hash entries, used when all keys are bytestrings 348// compare hash entries, used when all keys are bytestrings
312static int 349static int
335 372
336static void 373static void
337encode_hv (enc_t *enc, HV *hv) 374encode_hv (enc_t *enc, HV *hv)
338{ 375{
339 int count, i; 376 int count, i;
377
378 if (enc->indent >= enc->maxdepth)
379 croak ("data structure too deep (hit recursion limit)");
340 380
341 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent; 381 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent;
342 382
343 if ((count = hv_iterinit (hv))) 383 if ((count = hv_iterinit (hv)))
344 { 384 {
345 // for canonical output we have to sort by keys first 385 // for canonical output we have to sort by keys first
346 // actually, this is mostly due to the stupid so-called 386 // actually, this is mostly due to the stupid so-called
347 // security workaround added somewhere in 5.8.x. 387 // security workaround added somewhere in 5.8.x.
348 // that randomises hash orderings 388 // that randomises hash orderings
349 if (enc->flags & F_CANONICAL) 389 if (enc->json.flags & F_CANONICAL)
350 { 390 {
351 HE *he, *hes [count]; // if your compiler dies here, you need to enable C99 mode
352 int fast = 1; 391 int fast = 1;
392 HE *he;
393#if defined(__BORLANDC__) || defined(_MSC_VER)
394 HE **hes = _alloca (count * sizeof (HE));
395#else
396 HE *hes [count]; // if your compiler dies here, you need to enable C99 mode
397#endif
353 398
354 i = 0; 399 i = 0;
355 while ((he = hv_iternext (hv))) 400 while ((he = hv_iternext (hv)))
356 { 401 {
357 hes [i++] = he; 402 hes [i++] = he;
392 437
393 encode_nl (enc); 438 encode_nl (enc);
394 } 439 }
395 else 440 else
396 { 441 {
397 SV *sv;
398 HE *he = hv_iternext (hv); 442 HE *he = hv_iternext (hv);
399 443
400 for (;;) 444 for (;;)
401 { 445 {
402 encode_indent (enc); 446 encode_indent (enc);
411 encode_nl (enc); 455 encode_nl (enc);
412 } 456 }
413 } 457 }
414 458
415 --enc->indent; encode_indent (enc); encode_ch (enc, '}'); 459 --enc->indent; encode_indent (enc); encode_ch (enc, '}');
460}
461
462// encode objects, arrays and special \0=false and \1=true values.
463static void
464encode_rv (enc_t *enc, SV *sv)
465{
466 svtype svt;
467
468 SvGETMAGIC (sv);
469 svt = SvTYPE (sv);
470
471 if (expect_false (SvOBJECT (sv)))
472 {
473 if (SvSTASH (sv) == json_boolean_stash)
474 {
475 if (SvIV (sv) == 0)
476 encode_str (enc, "false", 5, 0);
477 else
478 encode_str (enc, "true", 4, 0);
479 }
480 else
481 {
482#if 0
483 if (0 && sv_derived_from (rv, "JSON::Literal"))
484 {
485 // not yet
486 }
487#endif
488 if (enc->json.flags & F_CONV_BLESSED)
489 {
490 // we re-bless the reference to get overload and other niceties right
491 GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 1);
492
493 if (to_json)
494 {
495 dSP;
496 ENTER;
497 SAVETMPS;
498 PUSHMARK (SP);
499 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv)));
500
501 // calling with G_SCALAR ensures that we always get a 1 reutrn value
502 // check anyways.
503 PUTBACK;
504 assert (1 == call_sv ((SV *)GvCV (to_json), G_SCALAR));
505 SPAGAIN;
506
507 encode_sv (enc, POPs);
508
509 FREETMPS;
510 LEAVE;
511 }
512 else if (enc->json.flags & F_ALLOW_BLESSED)
513 encode_str (enc, "null", 4, 0);
514 else
515 croak ("encountered object '%s', but neither allow_blessed enabled nor TO_JSON method available on it",
516 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
517 }
518 else if (enc->json.flags & F_ALLOW_BLESSED)
519 encode_str (enc, "null", 4, 0);
520 else
521 croak ("encountered object '%s', but neither allow_blessed nor convert_blessed settings are enabled",
522 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
523 }
524 }
525 else if (svt == SVt_PVHV)
526 encode_hv (enc, (HV *)sv);
527 else if (svt == SVt_PVAV)
528 encode_av (enc, (AV *)sv);
529 else if (svt < SVt_PVAV)
530 {
531 if (SvNIOK (sv) && SvIV (sv) == 0)
532 encode_str (enc, "false", 5, 0);
533 else if (SvNIOK (sv) && SvIV (sv) == 1)
534 encode_str (enc, "true", 4, 0);
535 else
536 croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1",
537 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
538 }
539 else
540 croak ("encountered %s, but JSON can only represent references to arrays or hashes",
541 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
416} 542}
417 543
418static void 544static void
419encode_sv (enc_t *enc, SV *sv) 545encode_sv (enc_t *enc, SV *sv)
420{ 546{
428 encode_str (enc, str, len, SvUTF8 (sv)); 554 encode_str (enc, str, len, SvUTF8 (sv));
429 encode_ch (enc, '"'); 555 encode_ch (enc, '"');
430 } 556 }
431 else if (SvNOKp (sv)) 557 else if (SvNOKp (sv))
432 { 558 {
559 // trust that perl will do the right thing w.r.t. JSON syntax.
433 need (enc, NV_DIG + 32); 560 need (enc, NV_DIG + 32);
434 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur); 561 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
435 enc->cur += strlen (enc->cur); 562 enc->cur += strlen (enc->cur);
436 } 563 }
437 else if (SvIOKp (sv)) 564 else if (SvIOKp (sv))
438 { 565 {
439 need (enc, 64); 566 // we assume we can always read an IV as a UV
567 if (SvUV (sv) & ~(UV)0x7fff)
568 {
569 // large integer, use the (rather slow) snprintf way.
570 need (enc, sizeof (UV) * 3);
440 enc->cur += 571 enc->cur +=
441 SvIsUV(sv) 572 SvIsUV(sv)
442 ? snprintf (enc->cur, 64, "%"UVuf, (UV)SvUVX (sv)) 573 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv))
443 : snprintf (enc->cur, 64, "%"IVdf, (IV)SvIVX (sv)); 574 : snprintf (enc->cur, sizeof (UV) * 3, "%"IVdf, (IV)SvIVX (sv));
575 }
576 else
577 {
578 // optimise the "small number case"
579 // code will likely be branchless and use only a single multiplication
580 I32 i = SvIV (sv);
581 U32 u;
582 char digit, nz = 0;
583
584 need (enc, 6);
585
586 *enc->cur = '-'; enc->cur += i < 0 ? 1 : 0;
587 u = i < 0 ? -i : i;
588
589 // convert to 4.28 fixed-point representation
590 u = u * ((0xfffffff + 10000) / 10000); // 10**5, 5 fractional digits
591
592 // now output digit by digit, each time masking out the integer part
593 // and multiplying by 5 while moving the decimal point one to the right,
594 // resulting in a net multiplication by 10.
595 // we always write the digit to memory but conditionally increment
596 // the pointer, to ease the usage of conditional move instructions.
597 digit = u >> 28; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0xfffffff) * 5;
598 digit = u >> 27; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x7ffffff) * 5;
599 digit = u >> 26; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x3ffffff) * 5;
600 digit = u >> 25; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x1ffffff) * 5;
601 digit = u >> 24; *enc->cur = digit + '0'; enc->cur += 1; // correctly generate '0'
602 }
444 } 603 }
445 else if (SvROK (sv)) 604 else if (SvROK (sv))
446 { 605 encode_rv (enc, SvRV (sv));
447 SV *rv = SvRV (sv);
448
449 if (enc->indent >= enc->max_depth)
450 croak ("data structure too deep (hit recursion limit)");
451
452 switch (SvTYPE (rv))
453 {
454 case SVt_PVAV: encode_av (enc, (AV *)rv); break;
455 case SVt_PVHV: encode_hv (enc, (HV *)rv); break;
456
457 default:
458 croak ("encountered %s, but JSON can only represent references to arrays or hashes",
459 SvPV_nolen (sv));
460 }
461 }
462 else if (!SvOK (sv)) 606 else if (!SvOK (sv))
463 encode_str (enc, "null", 4, 0); 607 encode_str (enc, "null", 4, 0);
464 else 608 else
465 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this", 609 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this",
466 SvPV_nolen (sv), SvFLAGS (sv)); 610 SvPV_nolen (sv), SvFLAGS (sv));
467} 611}
468 612
469static SV * 613static SV *
470encode_json (SV *scalar, UV flags) 614encode_json (SV *scalar, JSON *json)
471{ 615{
616 enc_t enc;
617
472 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar)) 618 if (!(json->flags & F_ALLOW_NONREF) && !SvROK (scalar))
473 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)"); 619 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)");
474 620
475 enc_t enc; 621 enc.json = *json;
476 enc.flags = flags;
477 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 622 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
478 enc.cur = SvPVX (enc.sv); 623 enc.cur = SvPVX (enc.sv);
479 enc.end = SvEND (enc.sv); 624 enc.end = SvEND (enc.sv);
480 enc.indent = 0; 625 enc.indent = 0;
481 enc.max_depth = 0x7fffffffUL; 626 enc.maxdepth = DEC_DEPTH (enc.json.flags);
482 627
483 SvPOK_only (enc.sv); 628 SvPOK_only (enc.sv);
484 encode_sv (&enc, scalar); 629 encode_sv (&enc, scalar);
485 630
631 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
632 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings
633
486 if (!(flags & (F_ASCII | F_UTF8))) 634 if (!(enc.json.flags & (F_ASCII | F_LATIN1 | F_UTF8)))
487 SvUTF8_on (enc.sv); 635 SvUTF8_on (enc.sv);
488 636
489 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
490
491 if (enc.flags & F_SHRINK) 637 if (enc.json.flags & F_SHRINK)
492 shrink (enc.sv); 638 shrink (enc.sv);
493 639
494 return enc.sv; 640 return enc.sv;
495} 641}
496 642
501typedef struct 647typedef struct
502{ 648{
503 char *cur; // current parser pointer 649 char *cur; // current parser pointer
504 char *end; // end of input string 650 char *end; // end of input string
505 const char *err; // parse error, if != 0 651 const char *err; // parse error, if != 0
506 UV flags; // F_* 652 JSON json;
653 U32 depth; // recursion depth
654 U32 maxdepth; // recursion depth limit
507} dec_t; 655} dec_t;
508 656
509static void 657inline void
510decode_ws (dec_t *dec) 658decode_ws (dec_t *dec)
511{ 659{
512 for (;;) 660 for (;;)
513 { 661 {
514 char ch = *dec->cur; 662 char ch = *dec->cur;
520 ++dec->cur; 668 ++dec->cur;
521 } 669 }
522} 670}
523 671
524#define ERR(reason) SB dec->err = reason; goto fail; SE 672#define ERR(reason) SB dec->err = reason; goto fail; SE
673
525#define EXPECT_CH(ch) SB \ 674#define EXPECT_CH(ch) SB \
526 if (*dec->cur != ch) \ 675 if (*dec->cur != ch) \
527 ERR (# ch " expected"); \ 676 ERR (# ch " expected"); \
528 ++dec->cur; \ 677 ++dec->cur; \
529 SE 678 SE
530 679
680#define DEC_INC_DEPTH if (++dec->depth > dec->maxdepth) ERR ("json datastructure exceeds maximum nesting level (set a higher max_depth)")
681#define DEC_DEC_DEPTH --dec->depth
682
531static SV *decode_sv (dec_t *dec); 683static SV *decode_sv (dec_t *dec);
532 684
533static signed char decode_hexdigit[256]; 685static signed char decode_hexdigit[256];
534 686
535static UV 687static UV
536decode_4hex (dec_t *dec) 688decode_4hex (dec_t *dec)
537{ 689{
538 signed char d1, d2, d3, d4; 690 signed char d1, d2, d3, d4;
539 unsigned char *cur = (unsigned char *)dec->cur; 691 unsigned char *cur = (unsigned char *)dec->cur;
540 692
541 d1 = decode_hexdigit [cur [0]]; if (d1 < 0) ERR ("four hexadecimal digits expected"); 693 d1 = decode_hexdigit [cur [0]]; if (expect_false (d1 < 0)) ERR ("exactly four hexadecimal digits expected");
542 d2 = decode_hexdigit [cur [1]]; if (d2 < 0) ERR ("four hexadecimal digits expected"); 694 d2 = decode_hexdigit [cur [1]]; if (expect_false (d2 < 0)) ERR ("exactly four hexadecimal digits expected");
543 d3 = decode_hexdigit [cur [2]]; if (d3 < 0) ERR ("four hexadecimal digits expected"); 695 d3 = decode_hexdigit [cur [2]]; if (expect_false (d3 < 0)) ERR ("exactly four hexadecimal digits expected");
544 d4 = decode_hexdigit [cur [3]]; if (d4 < 0) ERR ("four hexadecimal digits expected"); 696 d4 = decode_hexdigit [cur [3]]; if (expect_false (d4 < 0)) ERR ("exactly four hexadecimal digits expected");
545 697
546 dec->cur += 4; 698 dec->cur += 4;
547 699
548 return ((UV)d1) << 12 700 return ((UV)d1) << 12
549 | ((UV)d2) << 8 701 | ((UV)d2) << 8
557static SV * 709static SV *
558decode_str (dec_t *dec) 710decode_str (dec_t *dec)
559{ 711{
560 SV *sv = 0; 712 SV *sv = 0;
561 int utf8 = 0; 713 int utf8 = 0;
714 char *dec_cur = dec->cur;
562 715
563 do 716 do
564 { 717 {
565 char buf [SHORT_STRING_LEN + UTF8_MAX_LEN]; 718 char buf [SHORT_STRING_LEN + UTF8_MAXBYTES];
566 char *cur = buf; 719 char *cur = buf;
567 720
568 do 721 do
569 { 722 {
570 unsigned char ch = *(unsigned char *)dec->cur++; 723 unsigned char ch = *(unsigned char *)dec_cur++;
571 724
572 if (ch == '"') 725 if (expect_false (ch == '"'))
573 { 726 {
574 --dec->cur; 727 --dec_cur;
575 break; 728 break;
576 } 729 }
577 else if (ch == '\\') 730 else if (expect_false (ch == '\\'))
578 { 731 {
579 switch (*dec->cur) 732 switch (*dec_cur)
580 { 733 {
581 case '\\': 734 case '\\':
582 case '/': 735 case '/':
583 case '"': *cur++ = *dec->cur++; break; 736 case '"': *cur++ = *dec_cur++; break;
584 737
585 case 'b': ++dec->cur; *cur++ = '\010'; break; 738 case 'b': ++dec_cur; *cur++ = '\010'; break;
586 case 't': ++dec->cur; *cur++ = '\011'; break; 739 case 't': ++dec_cur; *cur++ = '\011'; break;
587 case 'n': ++dec->cur; *cur++ = '\012'; break; 740 case 'n': ++dec_cur; *cur++ = '\012'; break;
588 case 'f': ++dec->cur; *cur++ = '\014'; break; 741 case 'f': ++dec_cur; *cur++ = '\014'; break;
589 case 'r': ++dec->cur; *cur++ = '\015'; break; 742 case 'r': ++dec_cur; *cur++ = '\015'; break;
590 743
591 case 'u': 744 case 'u':
592 { 745 {
593 UV lo, hi; 746 UV lo, hi;
594 ++dec->cur; 747 ++dec_cur;
595 748
749 dec->cur = dec_cur;
596 hi = decode_4hex (dec); 750 hi = decode_4hex (dec);
751 dec_cur = dec->cur;
597 if (hi == (UV)-1) 752 if (hi == (UV)-1)
598 goto fail; 753 goto fail;
599 754
600 // possibly a surrogate pair 755 // possibly a surrogate pair
601 if (hi >= 0xd800) 756 if (hi >= 0xd800)
602 if (hi < 0xdc00) 757 if (hi < 0xdc00)
603 { 758 {
604 if (dec->cur [0] != '\\' || dec->cur [1] != 'u') 759 if (dec_cur [0] != '\\' || dec_cur [1] != 'u')
605 ERR ("missing low surrogate character in surrogate pair"); 760 ERR ("missing low surrogate character in surrogate pair");
606 761
607 dec->cur += 2; 762 dec_cur += 2;
608 763
764 dec->cur = dec_cur;
609 lo = decode_4hex (dec); 765 lo = decode_4hex (dec);
766 dec_cur = dec->cur;
610 if (lo == (UV)-1) 767 if (lo == (UV)-1)
611 goto fail; 768 goto fail;
612 769
613 if (lo < 0xdc00 || lo >= 0xe000) 770 if (lo < 0xdc00 || lo >= 0xe000)
614 ERR ("surrogate pair expected"); 771 ERR ("surrogate pair expected");
628 *cur++ = hi; 785 *cur++ = hi;
629 } 786 }
630 break; 787 break;
631 788
632 default: 789 default:
633 --dec->cur; 790 --dec_cur;
634 ERR ("illegal backslash escape sequence in string"); 791 ERR ("illegal backslash escape sequence in string");
635 } 792 }
636 } 793 }
637 else if (ch >= 0x20 && ch <= 0x7f) 794 else if (expect_true (ch >= 0x20 && ch <= 0x7f))
638 *cur++ = ch; 795 *cur++ = ch;
639 else if (ch >= 0x80) 796 else if (ch >= 0x80)
640 { 797 {
641 --dec->cur;
642
643 STRLEN clen; 798 STRLEN clen;
799 UV uch;
800
801 --dec_cur;
802
644 UV uch = decode_utf8 (dec->cur, dec->end - dec->cur, &clen); 803 uch = decode_utf8 (dec_cur, dec->end - dec_cur, &clen);
645 if (clen == (STRLEN)-1) 804 if (clen == (STRLEN)-1)
646 ERR ("malformed UTF-8 character in JSON string"); 805 ERR ("malformed UTF-8 character in JSON string");
647 806
648 do 807 do
649 {
650 *cur++ = *dec->cur++; 808 *cur++ = *dec_cur++;
651 }
652 while (--clen); 809 while (--clen);
653 810
654 utf8 = 1; 811 utf8 = 1;
655 } 812 }
656 else if (!ch)
657 ERR ("unexpected end of string while parsing json string");
658 else 813 else
814 {
815 --dec_cur;
816
817 if (!ch)
818 ERR ("unexpected end of string while parsing JSON string");
819 else
659 ERR ("invalid character encountered"); 820 ERR ("invalid character encountered while parsing JSON string");
660 821 }
661 } 822 }
662 while (cur < buf + SHORT_STRING_LEN); 823 while (cur < buf + SHORT_STRING_LEN);
663 824
825 {
664 STRLEN len = cur - buf; 826 STRLEN len = cur - buf;
665 827
666 if (sv) 828 if (sv)
667 { 829 {
668 SvGROW (sv, SvCUR (sv) + len + 1); 830 SvGROW (sv, SvCUR (sv) + len + 1);
669 memcpy (SvPVX (sv) + SvCUR (sv), buf, len); 831 memcpy (SvPVX (sv) + SvCUR (sv), buf, len);
670 SvCUR_set (sv, SvCUR (sv) + len); 832 SvCUR_set (sv, SvCUR (sv) + len);
671 } 833 }
672 else 834 else
673 sv = newSVpvn (buf, len); 835 sv = newSVpvn (buf, len);
674 } 836 }
837 }
675 while (*dec->cur != '"'); 838 while (*dec_cur != '"');
676 839
677 ++dec->cur; 840 ++dec_cur;
678 841
679 if (sv) 842 if (sv)
680 { 843 {
681 SvPOK_only (sv); 844 SvPOK_only (sv);
682 *SvEND (sv) = 0; 845 *SvEND (sv) = 0;
685 SvUTF8_on (sv); 848 SvUTF8_on (sv);
686 } 849 }
687 else 850 else
688 sv = newSVpvn ("", 0); 851 sv = newSVpvn ("", 0);
689 852
853 dec->cur = dec_cur;
690 return sv; 854 return sv;
691 855
692fail: 856fail:
857 dec->cur = dec_cur;
693 return 0; 858 return 0;
694} 859}
695 860
696static SV * 861static SV *
697decode_num (dec_t *dec) 862decode_num (dec_t *dec)
755 is_nv = 1; 920 is_nv = 1;
756 } 921 }
757 922
758 if (!is_nv) 923 if (!is_nv)
759 { 924 {
760 UV uv; 925 // special case the rather common 1..4-digit-int case, assumes 32 bit ints or so
761 int numtype = grok_number (start, dec->cur - start, &uv); 926 if (*start == '-')
762 if (numtype & IS_NUMBER_IN_UV) 927 switch (dec->cur - start)
763 if (numtype & IS_NUMBER_NEG)
764 { 928 {
765 if (uv < (UV)IV_MIN) 929 case 2: return newSViv (-( start [1] - '0' * 1));
766 return newSViv (-(IV)uv); 930 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11));
931 case 4: return newSViv (-( start [1] * 100 + start [2] * 10 + start [3] - '0' * 111));
932 case 5: return newSViv (-(start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111));
767 } 933 }
934 else
935 switch (dec->cur - start)
936 {
937 case 1: return newSViv ( start [0] - '0' * 1);
938 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11);
939 case 3: return newSViv ( start [0] * 100 + start [1] * 10 + start [2] - '0' * 111);
940 case 4: return newSViv ( start [0] * 1000 + start [1] * 100 + start [2] * 10 + start [3] - '0' * 1111);
941 }
942
943 {
944 UV uv;
945 int numtype = grok_number (start, dec->cur - start, &uv);
946 if (numtype & IS_NUMBER_IN_UV)
947 if (numtype & IS_NUMBER_NEG)
948 {
949 if (uv < (UV)IV_MIN)
950 return newSViv (-(IV)uv);
951 }
768 else 952 else
769 return newSVuv (uv); 953 return newSVuv (uv);
954
955 // here would likely be the place for bigint support
770 } 956 }
957 }
771 958
959 // if we ever support bigint or bigfloat, this is the place for bigfloat
772 return newSVnv (Atof (start)); 960 return newSVnv (Atof (start));
773 961
774fail: 962fail:
775 return 0; 963 return 0;
776} 964}
778static SV * 966static SV *
779decode_av (dec_t *dec) 967decode_av (dec_t *dec)
780{ 968{
781 AV *av = newAV (); 969 AV *av = newAV ();
782 970
971 DEC_INC_DEPTH;
783 decode_ws (dec); 972 decode_ws (dec);
973
784 if (*dec->cur == ']') 974 if (*dec->cur == ']')
785 ++dec->cur; 975 ++dec->cur;
786 else 976 else
787 for (;;) 977 for (;;)
788 { 978 {
806 ERR (", or ] expected while parsing array"); 996 ERR (", or ] expected while parsing array");
807 997
808 ++dec->cur; 998 ++dec->cur;
809 } 999 }
810 1000
1001 DEC_DEC_DEPTH;
811 return newRV_noinc ((SV *)av); 1002 return newRV_noinc ((SV *)av);
812 1003
813fail: 1004fail:
814 SvREFCNT_dec (av); 1005 SvREFCNT_dec (av);
1006 DEC_DEC_DEPTH;
815 return 0; 1007 return 0;
816} 1008}
817 1009
818static SV * 1010static SV *
819decode_hv (dec_t *dec) 1011decode_hv (dec_t *dec)
820{ 1012{
821 HV *hv = newHV (); 1013 HV *hv = newHV ();
822 1014
1015 DEC_INC_DEPTH;
823 decode_ws (dec); 1016 decode_ws (dec);
1017
824 if (*dec->cur == '}') 1018 if (*dec->cur == '}')
825 ++dec->cur; 1019 ++dec->cur;
826 else 1020 else
827 for (;;) 1021 for (;;)
828 { 1022 {
829 SV *key, *value;
830
831 decode_ws (dec); EXPECT_CH ('"'); 1023 decode_ws (dec); EXPECT_CH ('"');
832 1024
833 key = decode_str (dec); 1025 // heuristic: assume that
834 if (!key) 1026 // a) decode_str + hv_store_ent are abysmally slow.
835 goto fail; 1027 // b) most hash keys are short, simple ascii text.
1028 // => try to "fast-match" such strings to avoid
1029 // the overhead of decode_str + hv_store_ent.
1030 {
1031 SV *value;
1032 char *p = dec->cur;
1033 char *e = p + 24; // only try up to 24 bytes
836 1034
837 decode_ws (dec); EXPECT_CH (':'); 1035 for (;;)
838
839 value = decode_sv (dec);
840 if (!value)
841 { 1036 {
1037 // the >= 0x80 is true on most architectures
1038 if (p == e || *p < 0x20 || *p >= 0x80 || *p == '\\')
1039 {
1040 // slow path, back up and use decode_str
1041 SV *key = decode_str (dec);
1042 if (!key)
1043 goto fail;
1044
1045 decode_ws (dec); EXPECT_CH (':');
1046
1047 value = decode_sv (dec);
1048 if (!value)
1049 {
1050 SvREFCNT_dec (key);
1051 goto fail;
1052 }
1053
1054 hv_store_ent (hv, key, value, 0);
842 SvREFCNT_dec (key); 1055 SvREFCNT_dec (key);
1056
1057 break;
1058 }
1059 else if (*p == '"')
1060 {
1061 // fast path, got a simple key
1062 char *key = dec->cur;
1063 int len = p - key;
1064 dec->cur = p + 1;
1065
1066 decode_ws (dec); EXPECT_CH (':');
1067
1068 value = decode_sv (dec);
1069 if (!value)
843 goto fail; 1070 goto fail;
1071
1072 hv_store (hv, key, len, value, 0);
1073
1074 break;
1075 }
1076
1077 ++p;
844 } 1078 }
845 1079 }
846 //TODO: optimise
847 hv_store_ent (hv, key, value, 0);
848 1080
849 decode_ws (dec); 1081 decode_ws (dec);
850 1082
851 if (*dec->cur == '}') 1083 if (*dec->cur == '}')
852 { 1084 {
858 ERR (", or } expected while parsing object/hash"); 1090 ERR (", or } expected while parsing object/hash");
859 1091
860 ++dec->cur; 1092 ++dec->cur;
861 } 1093 }
862 1094
1095 DEC_DEC_DEPTH;
863 return newRV_noinc ((SV *)hv); 1096 return newRV_noinc ((SV *)hv);
864 1097
865fail: 1098fail:
866 SvREFCNT_dec (hv); 1099 SvREFCNT_dec (hv);
1100 DEC_DEC_DEPTH;
867 return 0; 1101 return 0;
868} 1102}
869 1103
870static SV * 1104static SV *
871decode_sv (dec_t *dec) 1105decode_sv (dec_t *dec)
872{ 1106{
873 decode_ws (dec); 1107 decode_ws (dec);
1108
1109 // the beauty of JSON: you need exactly one character lookahead
1110 // to parse anything.
874 switch (*dec->cur) 1111 switch (*dec->cur)
875 { 1112 {
876 case '"': ++dec->cur; return decode_str (dec); 1113 case '"': ++dec->cur; return decode_str (dec);
877 case '[': ++dec->cur; return decode_av (dec); 1114 case '[': ++dec->cur; return decode_av (dec);
878 case '{': ++dec->cur; return decode_hv (dec); 1115 case '{': ++dec->cur; return decode_hv (dec);
884 1121
885 case 't': 1122 case 't':
886 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1123 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
887 { 1124 {
888 dec->cur += 4; 1125 dec->cur += 4;
889 return newSViv (1); 1126 return SvREFCNT_inc (json_true);
890 } 1127 }
891 else 1128 else
892 ERR ("'true' expected"); 1129 ERR ("'true' expected");
893 1130
894 break; 1131 break;
895 1132
896 case 'f': 1133 case 'f':
897 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1134 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
898 { 1135 {
899 dec->cur += 5; 1136 dec->cur += 5;
900 return newSViv (0); 1137 return SvREFCNT_inc (json_false);
901 } 1138 }
902 else 1139 else
903 ERR ("'false' expected"); 1140 ERR ("'false' expected");
904 1141
905 break; 1142 break;
914 ERR ("'null' expected"); 1151 ERR ("'null' expected");
915 1152
916 break; 1153 break;
917 1154
918 default: 1155 default:
919 ERR ("malformed json string, neither array, object, number, string or atom"); 1156 ERR ("malformed JSON string, neither array, object, number, string or atom");
920 break; 1157 break;
921 } 1158 }
922 1159
923fail: 1160fail:
924 return 0; 1161 return 0;
925} 1162}
926 1163
927static SV * 1164static SV *
928decode_json (SV *string, UV flags) 1165decode_json (SV *string, JSON *json, UV *offset_return)
929{ 1166{
1167 dec_t dec;
1168 UV offset;
930 SV *sv; 1169 SV *sv;
931 1170
1171 SvGETMAGIC (string);
1172 SvUPGRADE (string, SVt_PV);
1173
1174 if (json->flags & F_MAXSIZE && SvCUR (string) > DEC_SIZE (json->flags))
1175 croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu",
1176 (unsigned long)SvCUR (string), (unsigned long)DEC_SIZE (json->flags));
1177
932 if (flags & F_UTF8) 1178 if (json->flags & F_UTF8)
933 sv_utf8_downgrade (string, 0); 1179 sv_utf8_downgrade (string, 0);
934 else 1180 else
935 sv_utf8_upgrade (string); 1181 sv_utf8_upgrade (string);
936 1182
937 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP 1183 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
938 1184
939 dec_t dec; 1185 dec.json = *json;
940 dec.flags = flags;
941 dec.cur = SvPVX (string); 1186 dec.cur = SvPVX (string);
942 dec.end = SvEND (string); 1187 dec.end = SvEND (string);
943 dec.err = 0; 1188 dec.err = 0;
1189 dec.depth = 0;
1190 dec.maxdepth = DEC_DEPTH (dec.json.flags);
944 1191
1192 *dec.end = 0; // this should basically be a nop, too, but make sure it's there
945 sv = decode_sv (&dec); 1193 sv = decode_sv (&dec);
946 1194
1195 if (!(offset_return || !sv))
1196 {
1197 // check for trailing garbage
1198 decode_ws (&dec);
1199
1200 if (*dec.cur)
1201 {
1202 dec.err = "garbage after JSON object";
1203 SvREFCNT_dec (sv);
1204 sv = 0;
1205 }
1206 }
1207
1208 if (offset_return || !sv)
1209 {
1210 offset = dec.json.flags & F_UTF8
1211 ? dec.cur - SvPVX (string)
1212 : utf8_distance (dec.cur, SvPVX (string));
1213
1214 if (offset_return)
1215 *offset_return = offset;
1216 }
1217
947 if (!sv) 1218 if (!sv)
948 { 1219 {
949 IV offset = dec.flags & F_UTF8
950 ? dec.cur - SvPVX (string)
951 : utf8_distance (dec.cur, SvPVX (string));
952 SV *uni = sv_newmortal (); 1220 SV *uni = sv_newmortal ();
953 1221
954 // horrible hack to silence warning inside pv_uni_display 1222 // horrible hack to silence warning inside pv_uni_display
955 COP cop = *PL_curcop; 1223 COP cop = *PL_curcop;
956 cop.cop_warnings = pWARN_NONE; 1224 cop.cop_warnings = pWARN_NONE;
958 SAVEVPTR (PL_curcop); 1226 SAVEVPTR (PL_curcop);
959 PL_curcop = &cop; 1227 PL_curcop = &cop;
960 pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ); 1228 pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ);
961 LEAVE; 1229 LEAVE;
962 1230
963 croak ("%s, at character offset %d (%s)", 1231 croak ("%s, at character offset %d [\"%s\"]",
964 dec.err, 1232 dec.err,
965 (int)offset, 1233 (int)offset,
966 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); 1234 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
967 } 1235 }
968 1236
969 sv = sv_2mortal (sv); 1237 sv = sv_2mortal (sv);
970 1238
971 if (!(dec.flags & F_ALLOW_NONREF) && !SvROK (sv)) 1239 if (!(dec.json.flags & F_ALLOW_NONREF) && !SvROK (sv))
972 croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)"); 1240 croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)");
973 1241
974 return sv; 1242 return sv;
975} 1243}
976 1244
981 1249
982BOOT: 1250BOOT:
983{ 1251{
984 int i; 1252 int i;
985 1253
986 memset (decode_hexdigit, 0xff, 256);
987 for (i = 10; i--; ) 1254 for (i = 0; i < 256; ++i)
988 decode_hexdigit ['0' + i] = i; 1255 decode_hexdigit [i] =
1256 i >= '0' && i <= '9' ? i - '0'
1257 : i >= 'a' && i <= 'f' ? i - 'a' + 10
1258 : i >= 'A' && i <= 'F' ? i - 'A' + 10
1259 : -1;
989 1260
990 for (i = 7; i--; )
991 {
992 decode_hexdigit ['a' + i] = 10 + i;
993 decode_hexdigit ['A' + i] = 10 + i;
994 }
995
996 json_stash = gv_stashpv ("JSON::XS", 1); 1261 json_stash = gv_stashpv ("JSON::XS" , 1);
1262 json_boolean_stash = gv_stashpv ("JSON::XS::Boolean", 1);
1263
1264 json_true = get_sv ("JSON::XS::true" , 1); SvREADONLY_on (json_true );
1265 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
997} 1266}
998 1267
999PROTOTYPES: DISABLE 1268PROTOTYPES: DISABLE
1000 1269
1001SV *new (char *dummy) 1270void new (char *klass)
1002 CODE: 1271 PPCODE:
1003 RETVAL = sv_bless (newRV_noinc (newSVuv (F_DEFAULT)), json_stash); 1272{
1004 OUTPUT: 1273 SV *pv = NEWSV (0, sizeof (JSON));
1005 RETVAL 1274 SvPOK_only (pv);
1275 Zero (SvPVX (pv), 1, sizeof (JSON));
1276 ((JSON *)SvPVX (pv))->flags = F_DEFAULT;
1277 XPUSHs (sv_2mortal (sv_bless (newRV_noinc (pv), json_stash)));
1278}
1006 1279
1007SV *ascii (SV *self, int enable = 1) 1280void ascii (JSON *self, int enable = 1)
1008 ALIAS: 1281 ALIAS:
1009 ascii = F_ASCII 1282 ascii = F_ASCII
1283 latin1 = F_LATIN1
1010 utf8 = F_UTF8 1284 utf8 = F_UTF8
1011 indent = F_INDENT 1285 indent = F_INDENT
1012 canonical = F_CANONICAL 1286 canonical = F_CANONICAL
1013 space_before = F_SPACE_BEFORE 1287 space_before = F_SPACE_BEFORE
1014 space_after = F_SPACE_AFTER 1288 space_after = F_SPACE_AFTER
1015 pretty = F_PRETTY 1289 pretty = F_PRETTY
1016 allow_nonref = F_ALLOW_NONREF 1290 allow_nonref = F_ALLOW_NONREF
1017 shrink = F_SHRINK 1291 shrink = F_SHRINK
1292 allow_blessed = F_ALLOW_BLESSED
1293 convert_blessed = F_CONV_BLESSED
1018 CODE: 1294 PPCODE:
1019{ 1295{
1020 UV *uv = SvJSON (self);
1021 if (enable) 1296 if (enable)
1022 *uv |= ix; 1297 self->flags |= ix;
1023 else 1298 else
1024 *uv &= ~ix; 1299 self->flags &= ~ix;
1025 1300
1026 RETVAL = newSVsv (self); 1301 XPUSHs (ST (0));
1027} 1302}
1028 OUTPUT:
1029 RETVAL
1030 1303
1031void encode (SV *self, SV *scalar) 1304void max_depth (JSON *self, UV max_depth = 0x80000000UL)
1032 PPCODE: 1305 PPCODE:
1033 XPUSHs (encode_json (scalar, *SvJSON (self))); 1306{
1307 UV log2 = 0;
1034 1308
1035void decode (SV *self, SV *jsonstr) 1309 if (max_depth > 0x80000000UL) max_depth = 0x80000000UL;
1310
1311 while ((1UL << log2) < max_depth)
1312 ++log2;
1313
1314 self->flags = self->flags & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1315
1316 XPUSHs (ST (0));
1317}
1318
1319void max_size (JSON *self, UV max_size = 0)
1036 PPCODE: 1320 PPCODE:
1321{
1322 UV log2 = 0;
1323
1324 if (max_size > 0x80000000UL) max_size = 0x80000000UL;
1325 if (max_size == 1) max_size = 2;
1326
1327 while ((1UL << log2) < max_size)
1328 ++log2;
1329
1330 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE);
1331
1332 XPUSHs (ST (0));
1333}
1334
1335void encode (JSON *self, SV *scalar)
1336 PPCODE:
1337 XPUSHs (encode_json (scalar, self));
1338
1339void decode (JSON *self, SV *jsonstr)
1340 PPCODE:
1037 XPUSHs (decode_json (jsonstr, *SvJSON (self))); 1341 XPUSHs (decode_json (jsonstr, self, 0));
1342
1343void decode_prefix (JSON *self, SV *jsonstr)
1344 PPCODE:
1345{
1346 UV offset;
1347 EXTEND (SP, 2);
1348 PUSHs (decode_json (jsonstr, self, &offset));
1349 PUSHs (sv_2mortal (newSVuv (offset)));
1350}
1038 1351
1039PROTOTYPES: ENABLE 1352PROTOTYPES: ENABLE
1040 1353
1041void to_json (SV *scalar) 1354void to_json (SV *scalar)
1042 PPCODE: 1355 PPCODE:
1356{
1357 JSON json = { F_DEFAULT | F_UTF8 };
1043 XPUSHs (encode_json (scalar, F_UTF8)); 1358 XPUSHs (encode_json (scalar, &json));
1359}
1044 1360
1045void from_json (SV *jsonstr) 1361void from_json (SV *jsonstr)
1046 PPCODE: 1362 PPCODE:
1363{
1364 JSON json = { F_DEFAULT | F_UTF8 };
1047 XPUSHs (decode_json (jsonstr, F_UTF8)); 1365 XPUSHs (decode_json (jsonstr, &json, 0));
1366}
1048 1367

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines