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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines