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.28 by root, Wed Apr 11 12:23:02 2007 UTC vs.
Revision 1.60 by root, Mon Aug 13 16:19:13 2007 UTC

1#include "EXTERN.h" 1#include "EXTERN.h"
2#include "perl.h" 2#include "perl.h"
3#include "XSUB.h" 3#include "XSUB.h"
4 4
5#include "assert.h" 5#include <assert.h>
6#include "string.h" 6#include <string.h>
7#include "stdlib.h" 7#include <stdlib.h>
8#include "stdio.h" 8#include <stdio.h>
9#include <float.h>
9 10
10#if defined(__BORLANDC__) || defined(_MSC_VER) 11#if defined(__BORLANDC__) || defined(_MSC_VER)
11# define snprintf _snprintf // C compilers have this in stdio.h 12# define snprintf _snprintf // C compilers have this in stdio.h
12#endif 13#endif
13 14
15// some old perls do not have this, try to make it work, no
16// guarentees, though. if it breaks, you get to keep the pieces.
17#ifndef UTF8_MAXBYTES
18# define UTF8_MAXBYTES 13
19#endif
20
14#define F_ASCII 0x00000001UL 21#define F_ASCII 0x00000001UL
22#define F_LATIN1 0x00000002UL
15#define F_UTF8 0x00000002UL 23#define F_UTF8 0x00000004UL
16#define F_INDENT 0x00000004UL 24#define F_INDENT 0x00000008UL
17#define F_CANONICAL 0x00000008UL 25#define F_CANONICAL 0x00000010UL
18#define F_SPACE_BEFORE 0x00000010UL 26#define F_SPACE_BEFORE 0x00000020UL
19#define F_SPACE_AFTER 0x00000020UL 27#define F_SPACE_AFTER 0x00000040UL
20#define F_ALLOW_NONREF 0x00000080UL 28#define F_ALLOW_NONREF 0x00000100UL
21#define F_SHRINK 0x00000100UL 29#define F_SHRINK 0x00000200UL
30#define F_ALLOW_BLESSED 0x00000400UL
31#define F_CONV_BLESSED 0x00000800UL
22#define F_MAXDEPTH 0xf8000000UL 32#define F_MAXDEPTH 0xf8000000UL
23#define S_MAXDEPTH 27 33#define S_MAXDEPTH 27
34#define F_MAXSIZE 0x01f00000UL
35#define S_MAXSIZE 20
36#define F_HOOK 0x00080000UL // some hooks exist, so slow-path processing
24 37
25#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH)) 38#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH))
26 39#define DEC_SIZE(flags) (1UL << ((flags & F_MAXSIZE ) >> S_MAXSIZE ))
27// F_SELFCONVERT? <=> to_json/toJson
28// F_BLESSED? <=> { $__class__$ => }
29 40
30#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER 41#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER
31#define F_DEFAULT (9UL << S_MAXDEPTH) 42#define F_DEFAULT (9UL << S_MAXDEPTH)
32 43
33#define INIT_SIZE 32 // initial scalar size to be allocated 44#define INIT_SIZE 32 // initial scalar size to be allocated
34#define INDENT_STEP 3 // spaces per indentation level 45#define INDENT_STEP 3 // spaces per indentation level
35 46
36#define SHORT_STRING_LEN 512 // special-case strings of up to this size 47#define SHORT_STRING_LEN 16384 // special-case strings of up to this size
37 48
38#define SB do { 49#define SB do {
39#define SE } while (0) 50#define SE } while (0)
40 51
52#if __GNUC__ >= 3
53# define expect(expr,value) __builtin_expect ((expr),(value))
54# define inline inline
55#else
56# define expect(expr,value) (expr)
57# define inline static
58#endif
59
60#define expect_false(expr) expect ((expr) != 0, 0)
61#define expect_true(expr) expect ((expr) != 0, 1)
62
63#ifdef USE_ITHREADS
64# define JSON_SLOW 1
65# define JSON_STASH (json_stash ? json_stash : gv_stashpv ("JSON::XS", 1))
66#else
67# define JSON_SLOW 0
68# define JSON_STASH json_stash
69#endif
70
41static HV *json_stash; // JSON::XS:: 71static HV *json_stash, *json_boolean_stash; // JSON::XS::
72static SV *json_true, *json_false;
73
74typedef struct {
75 U32 flags;
76 SV *cb_object;
77 HV *cb_sk_object;
78} JSON;
42 79
43///////////////////////////////////////////////////////////////////////////// 80/////////////////////////////////////////////////////////////////////////////
44// utility functions 81// utility functions
45 82
46static UV * 83inline void
47SvJSON (SV *sv)
48{
49 if (!(SvROK (sv) && SvOBJECT (SvRV (sv)) && SvSTASH (SvRV (sv)) == json_stash))
50 croak ("object is not of type JSON::XS");
51
52 return &SvUVX (SvRV (sv));
53}
54
55static void
56shrink (SV *sv) 84shrink (SV *sv)
57{ 85{
58 sv_utf8_downgrade (sv, 1); 86 sv_utf8_downgrade (sv, 1);
59 if (SvLEN (sv) > SvCUR (sv) + 1) 87 if (SvLEN (sv) > SvCUR (sv) + 1)
60 { 88 {
69// decode an utf-8 character and return it, or (UV)-1 in 97// decode an utf-8 character and return it, or (UV)-1 in
70// case of an error. 98// case of an error.
71// we special-case "safe" characters from U+80 .. U+7FF, 99// we special-case "safe" characters from U+80 .. U+7FF,
72// but use the very good perl function to parse anything else. 100// but use the very good perl function to parse anything else.
73// note that we never call this function for a ascii codepoints 101// note that we never call this function for a ascii codepoints
74static UV 102inline UV
75decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen) 103decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
76{ 104{
77 if (s[0] > 0xdf || s[0] < 0xc2) 105 if (expect_false (s[0] > 0xdf || s[0] < 0xc2))
78 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY); 106 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY);
79 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf) 107 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf)
80 { 108 {
81 *clen = 2; 109 *clen = 2;
82 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f); 110 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
95typedef struct 123typedef struct
96{ 124{
97 char *cur; // SvPVX (sv) + current output position 125 char *cur; // SvPVX (sv) + current output position
98 char *end; // SvEND (sv) 126 char *end; // SvEND (sv)
99 SV *sv; // result scalar 127 SV *sv; // result scalar
100 U32 flags; // F_* 128 JSON json;
101 U32 indent; // indentation level 129 U32 indent; // indentation level
102 U32 maxdepth; // max. indentation/recursion level 130 U32 maxdepth; // max. indentation/recursion level
103} enc_t; 131} enc_t;
104 132
105static void 133inline void
106need (enc_t *enc, STRLEN len) 134need (enc_t *enc, STRLEN len)
107{ 135{
108 if (enc->cur + len >= enc->end) 136 if (expect_false (enc->cur + len >= enc->end))
109 { 137 {
110 STRLEN cur = enc->cur - SvPVX (enc->sv); 138 STRLEN cur = enc->cur - SvPVX (enc->sv);
111 SvGROW (enc->sv, cur + len + 1); 139 SvGROW (enc->sv, cur + len + 1);
112 enc->cur = SvPVX (enc->sv) + cur; 140 enc->cur = SvPVX (enc->sv) + cur;
113 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1; 141 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
114 } 142 }
115} 143}
116 144
117static void 145inline void
118encode_ch (enc_t *enc, char ch) 146encode_ch (enc_t *enc, char ch)
119{ 147{
120 need (enc, 1); 148 need (enc, 1);
121 *enc->cur++ = ch; 149 *enc->cur++ = ch;
122} 150}
130 158
131 while (str < end) 159 while (str < end)
132 { 160 {
133 unsigned char ch = *(unsigned char *)str; 161 unsigned char ch = *(unsigned char *)str;
134 162
135 if (ch >= 0x20 && ch < 0x80) // most common case 163 if (expect_true (ch >= 0x20 && ch < 0x80)) // most common case
136 { 164 {
137 if (ch == '"') // but with slow exceptions 165 if (expect_false (ch == '"')) // but with slow exceptions
138 { 166 {
139 need (enc, len += 1); 167 need (enc, len += 1);
140 *enc->cur++ = '\\'; 168 *enc->cur++ = '\\';
141 *enc->cur++ = '"'; 169 *enc->cur++ = '"';
142 } 170 }
143 else if (ch == '\\') 171 else if (expect_false (ch == '\\'))
144 { 172 {
145 need (enc, len += 1); 173 need (enc, len += 1);
146 *enc->cur++ = '\\'; 174 *enc->cur++ = '\\';
147 *enc->cur++ = '\\'; 175 *enc->cur++ = '\\';
148 } 176 }
166 STRLEN clen; 194 STRLEN clen;
167 UV uch; 195 UV uch;
168 196
169 if (is_utf8) 197 if (is_utf8)
170 { 198 {
171 //uch = utf8n_to_uvuni (str, end - str, &clen, UTF8_CHECK_ONLY);
172 uch = decode_utf8 (str, end - str, &clen); 199 uch = decode_utf8 (str, end - str, &clen);
173 if (clen == (STRLEN)-1) 200 if (clen == (STRLEN)-1)
174 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str); 201 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str);
175 } 202 }
176 else 203 else
180 } 207 }
181 208
182 if (uch > 0x10FFFFUL) 209 if (uch > 0x10FFFFUL)
183 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch); 210 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
184 211
185 if (uch < 0x80 || enc->flags & F_ASCII) 212 if (uch < 0x80 || enc->json.flags & F_ASCII || (enc->json.flags & F_LATIN1 && uch > 0xFF))
186 { 213 {
187 if (uch > 0xFFFFUL) 214 if (uch > 0xFFFFUL)
188 { 215 {
189 need (enc, len += 11); 216 need (enc, len += 11);
190 sprintf (enc->cur, "\\u%04x\\u%04x", 217 sprintf (enc->cur, "\\u%04x\\u%04x",
204 *enc->cur++ = hexdigit [(uch >> 0) & 15]; 231 *enc->cur++ = hexdigit [(uch >> 0) & 15];
205 } 232 }
206 233
207 str += clen; 234 str += clen;
208 } 235 }
236 else if (enc->json.flags & F_LATIN1)
237 {
238 *enc->cur++ = uch;
239 str += clen;
240 }
209 else if (is_utf8) 241 else if (is_utf8)
210 { 242 {
211 need (enc, len += clen); 243 need (enc, len += clen);
212 do 244 do
213 { 245 {
227 259
228 --len; 260 --len;
229 } 261 }
230} 262}
231 263
232static void 264inline void
233encode_indent (enc_t *enc) 265encode_indent (enc_t *enc)
234{ 266{
235 if (enc->flags & F_INDENT) 267 if (enc->json.flags & F_INDENT)
236 { 268 {
237 int spaces = enc->indent * INDENT_STEP; 269 int spaces = enc->indent * INDENT_STEP;
238 270
239 need (enc, spaces); 271 need (enc, spaces);
240 memset (enc->cur, ' ', spaces); 272 memset (enc->cur, ' ', spaces);
241 enc->cur += spaces; 273 enc->cur += spaces;
242 } 274 }
243} 275}
244 276
245static void 277inline void
246encode_space (enc_t *enc) 278encode_space (enc_t *enc)
247{ 279{
248 need (enc, 1); 280 need (enc, 1);
249 encode_ch (enc, ' '); 281 encode_ch (enc, ' ');
250} 282}
251 283
252static void 284inline void
253encode_nl (enc_t *enc) 285encode_nl (enc_t *enc)
254{ 286{
255 if (enc->flags & F_INDENT) 287 if (enc->json.flags & F_INDENT)
256 { 288 {
257 need (enc, 1); 289 need (enc, 1);
258 encode_ch (enc, '\n'); 290 encode_ch (enc, '\n');
259 } 291 }
260} 292}
261 293
262static void 294inline void
263encode_comma (enc_t *enc) 295encode_comma (enc_t *enc)
264{ 296{
265 encode_ch (enc, ','); 297 encode_ch (enc, ',');
266 298
267 if (enc->flags & F_INDENT) 299 if (enc->json.flags & F_INDENT)
268 encode_nl (enc); 300 encode_nl (enc);
269 else if (enc->flags & F_SPACE_AFTER) 301 else if (enc->json.flags & F_SPACE_AFTER)
270 encode_space (enc); 302 encode_space (enc);
271} 303}
272 304
273static void encode_sv (enc_t *enc, SV *sv); 305static void encode_sv (enc_t *enc, SV *sv);
274 306
283 encode_ch (enc, '['); encode_nl (enc); 315 encode_ch (enc, '['); encode_nl (enc);
284 ++enc->indent; 316 ++enc->indent;
285 317
286 for (i = 0; i <= len; ++i) 318 for (i = 0; i <= len; ++i)
287 { 319 {
320 SV **svp = av_fetch (av, i, 0);
321
288 encode_indent (enc); 322 encode_indent (enc);
289 encode_sv (enc, *av_fetch (av, i, 0)); 323
324 if (svp)
325 encode_sv (enc, *svp);
326 else
327 encode_str (enc, "null", 4, 0);
290 328
291 if (i < len) 329 if (i < len)
292 encode_comma (enc); 330 encode_comma (enc);
293 } 331 }
294 332
317 else 355 else
318 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he)); 356 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he));
319 357
320 encode_ch (enc, '"'); 358 encode_ch (enc, '"');
321 359
322 if (enc->flags & F_SPACE_BEFORE) encode_space (enc); 360 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc);
323 encode_ch (enc, ':'); 361 encode_ch (enc, ':');
324 if (enc->flags & F_SPACE_AFTER ) encode_space (enc); 362 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc);
325 encode_sv (enc, HeVAL (he)); 363 encode_sv (enc, HeVAL (he));
326} 364}
327 365
328// compare hash entries, used when all keys are bytestrings 366// compare hash entries, used when all keys are bytestrings
329static int 367static int
364 { 402 {
365 // for canonical output we have to sort by keys first 403 // for canonical output we have to sort by keys first
366 // actually, this is mostly due to the stupid so-called 404 // actually, this is mostly due to the stupid so-called
367 // security workaround added somewhere in 5.8.x. 405 // security workaround added somewhere in 5.8.x.
368 // that randomises hash orderings 406 // that randomises hash orderings
369 if (enc->flags & F_CANONICAL) 407 if (enc->json.flags & F_CANONICAL)
370 { 408 {
371 HE *he, *hes [count]; // if your compiler dies here, you need to enable C99 mode
372 int fast = 1; 409 int fast = 1;
410 HE *he;
411#if defined(__BORLANDC__) || defined(_MSC_VER)
412 HE **hes = _alloca (count * sizeof (HE));
413#else
414 HE *hes [count]; // if your compiler dies here, you need to enable C99 mode
415#endif
373 416
374 i = 0; 417 i = 0;
375 while ((he = hv_iternext (hv))) 418 while ((he = hv_iternext (hv)))
376 { 419 {
377 hes [i++] = he; 420 hes [i++] = he;
441 svtype svt; 484 svtype svt;
442 485
443 SvGETMAGIC (sv); 486 SvGETMAGIC (sv);
444 svt = SvTYPE (sv); 487 svt = SvTYPE (sv);
445 488
489 if (expect_false (SvOBJECT (sv)))
490 {
491 HV *stash = !JSON_SLOW || json_boolean_stash
492 ? json_boolean_stash
493 : gv_stashpv ("JSON::XS::Boolean", 1);
494
495 if (SvSTASH (sv) == stash)
496 {
497 if (SvIV (sv))
498 encode_str (enc, "true", 4, 0);
499 else
500 encode_str (enc, "false", 5, 0);
501 }
502 else
503 {
504#if 0
505 if (0 && sv_derived_from (rv, "JSON::Literal"))
506 {
507 // not yet
508 }
509#endif
510 if (enc->json.flags & F_CONV_BLESSED)
511 {
512 // we re-bless the reference to get overload and other niceties right
513 GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 0);
514
515 if (to_json)
516 {
517 dSP;
518
519 ENTER; SAVETMPS; PUSHMARK (SP);
520 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv)));
521
522 // calling with G_SCALAR ensures that we always get a 1 return value
523 PUTBACK;
524 call_sv ((SV *)GvCV (to_json), G_SCALAR);
525 SPAGAIN;
526
527 // catch this surprisingly common error
528 if (SvROK (TOPs) && SvRV (TOPs) == sv)
529 croak ("%s::TO_JSON method returned same object as was passed instead of a new one", HvNAME (SvSTASH (sv)));
530
531 sv = POPs;
532 PUTBACK;
533
534 encode_sv (enc, sv);
535
536 FREETMPS; LEAVE;
537 }
538 else if (enc->json.flags & F_ALLOW_BLESSED)
539 encode_str (enc, "null", 4, 0);
540 else
541 croak ("encountered object '%s', but neither allow_blessed enabled nor TO_JSON method available on it",
542 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
543 }
544 else if (enc->json.flags & F_ALLOW_BLESSED)
545 encode_str (enc, "null", 4, 0);
546 else
547 croak ("encountered object '%s', but neither allow_blessed nor convert_blessed settings are enabled",
548 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
549 }
550 }
446 if (svt == SVt_PVHV) 551 else if (svt == SVt_PVHV)
447 encode_hv (enc, (HV *)sv); 552 encode_hv (enc, (HV *)sv);
448 else if (svt == SVt_PVAV) 553 else if (svt == SVt_PVAV)
449 encode_av (enc, (AV *)sv); 554 encode_av (enc, (AV *)sv);
450 else if (svt < SVt_PVAV) 555 else if (svt < SVt_PVAV)
451 { 556 {
452 if (SvNIOK (sv) && SvIV (sv) == 0) 557 STRLEN len = 0;
558 char *pv = svt ? SvPV (sv, len) : 0;
559
560 if (len == 1 && *pv == '1')
561 encode_str (enc, "true", 4, 0);
562 else if (len == 1 && *pv == '0')
453 encode_str (enc, "false", 5, 0); 563 encode_str (enc, "false", 5, 0);
454 else if (SvNIOK (sv) && SvIV (sv) == 1)
455 encode_str (enc, "true", 4, 0);
456 else 564 else
457 croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1", 565 croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1",
458 SvPV_nolen (sv_2mortal (newRV_inc (sv)))); 566 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
459 } 567 }
460 else 568 else
475 encode_str (enc, str, len, SvUTF8 (sv)); 583 encode_str (enc, str, len, SvUTF8 (sv));
476 encode_ch (enc, '"'); 584 encode_ch (enc, '"');
477 } 585 }
478 else if (SvNOKp (sv)) 586 else if (SvNOKp (sv))
479 { 587 {
588 // trust that perl will do the right thing w.r.t. JSON syntax.
480 need (enc, NV_DIG + 32); 589 need (enc, NV_DIG + 32);
481 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur); 590 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
482 enc->cur += strlen (enc->cur); 591 enc->cur += strlen (enc->cur);
483 } 592 }
484 else if (SvIOKp (sv)) 593 else if (SvIOKp (sv))
485 { 594 {
486 need (enc, 64); 595 // we assume we can always read an IV as a UV
596 if (SvUV (sv) & ~(UV)0x7fff)
597 {
598 // large integer, use the (rather slow) snprintf way.
599 need (enc, sizeof (UV) * 3);
487 enc->cur += 600 enc->cur +=
488 SvIsUV(sv) 601 SvIsUV(sv)
489 ? snprintf (enc->cur, 64, "%"UVuf, (UV)SvUVX (sv)) 602 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv))
490 : snprintf (enc->cur, 64, "%"IVdf, (IV)SvIVX (sv)); 603 : snprintf (enc->cur, sizeof (UV) * 3, "%"IVdf, (IV)SvIVX (sv));
604 }
605 else
606 {
607 // optimise the "small number case"
608 // code will likely be branchless and use only a single multiplication
609 I32 i = SvIV (sv);
610 U32 u;
611 char digit, nz = 0;
612
613 need (enc, 6);
614
615 *enc->cur = '-'; enc->cur += i < 0 ? 1 : 0;
616 u = i < 0 ? -i : i;
617
618 // convert to 4.28 fixed-point representation
619 u = u * ((0xfffffff + 10000) / 10000); // 10**5, 5 fractional digits
620
621 // now output digit by digit, each time masking out the integer part
622 // and multiplying by 5 while moving the decimal point one to the right,
623 // resulting in a net multiplication by 10.
624 // we always write the digit to memory but conditionally increment
625 // the pointer, to ease the usage of conditional move instructions.
626 digit = u >> 28; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0xfffffff) * 5;
627 digit = u >> 27; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x7ffffff) * 5;
628 digit = u >> 26; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x3ffffff) * 5;
629 digit = u >> 25; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x1ffffff) * 5;
630 digit = u >> 24; *enc->cur = digit + '0'; enc->cur += 1; // correctly generate '0'
631 }
491 } 632 }
492 else if (SvROK (sv)) 633 else if (SvROK (sv))
493 encode_rv (enc, SvRV (sv)); 634 encode_rv (enc, SvRV (sv));
494 else if (!SvOK (sv)) 635 else if (!SvOK (sv))
495 encode_str (enc, "null", 4, 0); 636 encode_str (enc, "null", 4, 0);
497 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this", 638 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this",
498 SvPV_nolen (sv), SvFLAGS (sv)); 639 SvPV_nolen (sv), SvFLAGS (sv));
499} 640}
500 641
501static SV * 642static SV *
502encode_json (SV *scalar, U32 flags) 643encode_json (SV *scalar, JSON *json)
503{ 644{
504 enc_t enc; 645 enc_t enc;
505 646
506 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar)) 647 if (!(json->flags & F_ALLOW_NONREF) && !SvROK (scalar))
507 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)"); 648 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)");
508 649
509 enc.flags = flags; 650 enc.json = *json;
510 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 651 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
511 enc.cur = SvPVX (enc.sv); 652 enc.cur = SvPVX (enc.sv);
512 enc.end = SvEND (enc.sv); 653 enc.end = SvEND (enc.sv);
513 enc.indent = 0; 654 enc.indent = 0;
514 enc.maxdepth = DEC_DEPTH (flags); 655 enc.maxdepth = DEC_DEPTH (enc.json.flags);
515 656
516 SvPOK_only (enc.sv); 657 SvPOK_only (enc.sv);
517 encode_sv (&enc, scalar); 658 encode_sv (&enc, scalar);
518 659
519 if (!(flags & (F_ASCII | F_UTF8)))
520 SvUTF8_on (enc.sv);
521
522 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); 660 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
523 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings 661 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings
524 662
663 if (!(enc.json.flags & (F_ASCII | F_LATIN1 | F_UTF8)))
664 SvUTF8_on (enc.sv);
665
525 if (enc.flags & F_SHRINK) 666 if (enc.json.flags & F_SHRINK)
526 shrink (enc.sv); 667 shrink (enc.sv);
527 668
528 return enc.sv; 669 return enc.sv;
529} 670}
530 671
535typedef struct 676typedef struct
536{ 677{
537 char *cur; // current parser pointer 678 char *cur; // current parser pointer
538 char *end; // end of input string 679 char *end; // end of input string
539 const char *err; // parse error, if != 0 680 const char *err; // parse error, if != 0
540 U32 flags; // F_* 681 JSON json;
541 U32 depth; // recursion depth 682 U32 depth; // recursion depth
542 U32 maxdepth; // recursion depth limit 683 U32 maxdepth; // recursion depth limit
543} dec_t; 684} dec_t;
544 685
545static void 686inline void
546decode_ws (dec_t *dec) 687decode_ws (dec_t *dec)
547{ 688{
548 for (;;) 689 for (;;)
549 { 690 {
550 char ch = *dec->cur; 691 char ch = *dec->cur;
576decode_4hex (dec_t *dec) 717decode_4hex (dec_t *dec)
577{ 718{
578 signed char d1, d2, d3, d4; 719 signed char d1, d2, d3, d4;
579 unsigned char *cur = (unsigned char *)dec->cur; 720 unsigned char *cur = (unsigned char *)dec->cur;
580 721
581 d1 = decode_hexdigit [cur [0]]; if (d1 < 0) ERR ("four hexadecimal digits expected"); 722 d1 = decode_hexdigit [cur [0]]; if (expect_false (d1 < 0)) ERR ("exactly four hexadecimal digits expected");
582 d2 = decode_hexdigit [cur [1]]; if (d2 < 0) ERR ("four hexadecimal digits expected"); 723 d2 = decode_hexdigit [cur [1]]; if (expect_false (d2 < 0)) ERR ("exactly four hexadecimal digits expected");
583 d3 = decode_hexdigit [cur [2]]; if (d3 < 0) ERR ("four hexadecimal digits expected"); 724 d3 = decode_hexdigit [cur [2]]; if (expect_false (d3 < 0)) ERR ("exactly four hexadecimal digits expected");
584 d4 = decode_hexdigit [cur [3]]; if (d4 < 0) ERR ("four hexadecimal digits expected"); 725 d4 = decode_hexdigit [cur [3]]; if (expect_false (d4 < 0)) ERR ("exactly four hexadecimal digits expected");
585 726
586 dec->cur += 4; 727 dec->cur += 4;
587 728
588 return ((UV)d1) << 12 729 return ((UV)d1) << 12
589 | ((UV)d2) << 8 730 | ((UV)d2) << 8
597static SV * 738static SV *
598decode_str (dec_t *dec) 739decode_str (dec_t *dec)
599{ 740{
600 SV *sv = 0; 741 SV *sv = 0;
601 int utf8 = 0; 742 int utf8 = 0;
743 char *dec_cur = dec->cur;
602 744
603 do 745 do
604 { 746 {
605 char buf [SHORT_STRING_LEN + UTF8_MAXBYTES]; 747 char buf [SHORT_STRING_LEN + UTF8_MAXBYTES];
606 char *cur = buf; 748 char *cur = buf;
607 749
608 do 750 do
609 { 751 {
610 unsigned char ch = *(unsigned char *)dec->cur++; 752 unsigned char ch = *(unsigned char *)dec_cur++;
611 753
612 if (ch == '"') 754 if (expect_false (ch == '"'))
613 { 755 {
614 --dec->cur; 756 --dec_cur;
615 break; 757 break;
616 } 758 }
617 else if (ch == '\\') 759 else if (expect_false (ch == '\\'))
618 { 760 {
619 switch (*dec->cur) 761 switch (*dec_cur)
620 { 762 {
621 case '\\': 763 case '\\':
622 case '/': 764 case '/':
623 case '"': *cur++ = *dec->cur++; break; 765 case '"': *cur++ = *dec_cur++; break;
624 766
625 case 'b': ++dec->cur; *cur++ = '\010'; break; 767 case 'b': ++dec_cur; *cur++ = '\010'; break;
626 case 't': ++dec->cur; *cur++ = '\011'; break; 768 case 't': ++dec_cur; *cur++ = '\011'; break;
627 case 'n': ++dec->cur; *cur++ = '\012'; break; 769 case 'n': ++dec_cur; *cur++ = '\012'; break;
628 case 'f': ++dec->cur; *cur++ = '\014'; break; 770 case 'f': ++dec_cur; *cur++ = '\014'; break;
629 case 'r': ++dec->cur; *cur++ = '\015'; break; 771 case 'r': ++dec_cur; *cur++ = '\015'; break;
630 772
631 case 'u': 773 case 'u':
632 { 774 {
633 UV lo, hi; 775 UV lo, hi;
634 ++dec->cur; 776 ++dec_cur;
635 777
778 dec->cur = dec_cur;
636 hi = decode_4hex (dec); 779 hi = decode_4hex (dec);
780 dec_cur = dec->cur;
637 if (hi == (UV)-1) 781 if (hi == (UV)-1)
638 goto fail; 782 goto fail;
639 783
640 // possibly a surrogate pair 784 // possibly a surrogate pair
641 if (hi >= 0xd800) 785 if (hi >= 0xd800)
642 if (hi < 0xdc00) 786 if (hi < 0xdc00)
643 { 787 {
644 if (dec->cur [0] != '\\' || dec->cur [1] != 'u') 788 if (dec_cur [0] != '\\' || dec_cur [1] != 'u')
645 ERR ("missing low surrogate character in surrogate pair"); 789 ERR ("missing low surrogate character in surrogate pair");
646 790
647 dec->cur += 2; 791 dec_cur += 2;
648 792
793 dec->cur = dec_cur;
649 lo = decode_4hex (dec); 794 lo = decode_4hex (dec);
795 dec_cur = dec->cur;
650 if (lo == (UV)-1) 796 if (lo == (UV)-1)
651 goto fail; 797 goto fail;
652 798
653 if (lo < 0xdc00 || lo >= 0xe000) 799 if (lo < 0xdc00 || lo >= 0xe000)
654 ERR ("surrogate pair expected"); 800 ERR ("surrogate pair expected");
668 *cur++ = hi; 814 *cur++ = hi;
669 } 815 }
670 break; 816 break;
671 817
672 default: 818 default:
673 --dec->cur; 819 --dec_cur;
674 ERR ("illegal backslash escape sequence in string"); 820 ERR ("illegal backslash escape sequence in string");
675 } 821 }
676 } 822 }
677 else if (ch >= 0x20 && ch <= 0x7f) 823 else if (expect_true (ch >= 0x20 && ch <= 0x7f))
678 *cur++ = ch; 824 *cur++ = ch;
679 else if (ch >= 0x80) 825 else if (ch >= 0x80)
680 { 826 {
681 STRLEN clen; 827 STRLEN clen;
682 UV uch; 828 UV uch;
683 829
684 --dec->cur; 830 --dec_cur;
685 831
686 uch = decode_utf8 (dec->cur, dec->end - dec->cur, &clen); 832 uch = decode_utf8 (dec_cur, dec->end - dec_cur, &clen);
687 if (clen == (STRLEN)-1) 833 if (clen == (STRLEN)-1)
688 ERR ("malformed UTF-8 character in JSON string"); 834 ERR ("malformed UTF-8 character in JSON string");
689 835
690 do 836 do
691 *cur++ = *dec->cur++; 837 *cur++ = *dec_cur++;
692 while (--clen); 838 while (--clen);
693 839
694 utf8 = 1; 840 utf8 = 1;
695 } 841 }
696 else 842 else
697 { 843 {
698 --dec->cur; 844 --dec_cur;
699 845
700 if (!ch) 846 if (!ch)
701 ERR ("unexpected end of string while parsing JSON string"); 847 ERR ("unexpected end of string while parsing JSON string");
702 else 848 else
703 ERR ("invalid character encountered while parsing JSON string"); 849 ERR ("invalid character encountered while parsing JSON string");
716 } 862 }
717 else 863 else
718 sv = newSVpvn (buf, len); 864 sv = newSVpvn (buf, len);
719 } 865 }
720 } 866 }
721 while (*dec->cur != '"'); 867 while (*dec_cur != '"');
722 868
723 ++dec->cur; 869 ++dec_cur;
724 870
725 if (sv) 871 if (sv)
726 { 872 {
727 SvPOK_only (sv); 873 SvPOK_only (sv);
728 *SvEND (sv) = 0; 874 *SvEND (sv) = 0;
731 SvUTF8_on (sv); 877 SvUTF8_on (sv);
732 } 878 }
733 else 879 else
734 sv = newSVpvn ("", 0); 880 sv = newSVpvn ("", 0);
735 881
882 dec->cur = dec_cur;
736 return sv; 883 return sv;
737 884
738fail: 885fail:
886 dec->cur = dec_cur;
739 return 0; 887 return 0;
740} 888}
741 889
742static SV * 890static SV *
743decode_num (dec_t *dec) 891decode_num (dec_t *dec)
801 is_nv = 1; 949 is_nv = 1;
802 } 950 }
803 951
804 if (!is_nv) 952 if (!is_nv)
805 { 953 {
806 UV uv; 954 int len = dec->cur - start;
807 int numtype = grok_number (start, dec->cur - start, &uv); 955
808 if (numtype & IS_NUMBER_IN_UV) 956 // special case the rather common 1..4-digit-int case, assumes 32 bit ints or so
809 if (numtype & IS_NUMBER_NEG) 957 if (*start == '-')
958 switch (len)
810 { 959 {
811 if (uv < (UV)IV_MIN) 960 case 2: return newSViv (-( start [1] - '0' * 1));
812 return newSViv (-(IV)uv); 961 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11));
962 case 4: return newSViv (-( start [1] * 100 + start [2] * 10 + start [3] - '0' * 111));
963 case 5: return newSViv (-(start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111));
813 } 964 }
965 else
966 switch (len)
967 {
968 case 1: return newSViv ( start [0] - '0' * 1);
969 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11);
970 case 3: return newSViv ( start [0] * 100 + start [1] * 10 + start [2] - '0' * 111);
971 case 4: return newSViv ( start [0] * 1000 + start [1] * 100 + start [2] * 10 + start [3] - '0' * 1111);
972 }
973
974 {
975 UV uv;
976 int numtype = grok_number (start, len, &uv);
977 if (numtype & IS_NUMBER_IN_UV)
978 if (numtype & IS_NUMBER_NEG)
979 {
980 if (uv < (UV)IV_MIN)
981 return newSViv (-(IV)uv);
982 }
814 else 983 else
815 return newSVuv (uv); 984 return newSVuv (uv);
816 } 985 }
817 986
987 len -= *start == '-' ? 1 : 0;
988
989 // does not fit into IV or UV, try NV
990 if ((sizeof (NV) == sizeof (double) && DBL_DIG >= len)
991 #if defined (LDBL_DIG)
992 || (sizeof (NV) == sizeof (long double) && LDBL_DIG >= len)
993 #endif
994 )
995 // fits into NV without loss of precision
996 return newSVnv (Atof (start));
997
998 // everything else fails, convert it to a string
999 return newSVpvn (start, dec->cur - start);
1000 }
1001
1002 // loss of precision here
818 return newSVnv (Atof (start)); 1003 return newSVnv (Atof (start));
819 1004
820fail: 1005fail:
821 return 0; 1006 return 0;
822} 1007}
866} 1051}
867 1052
868static SV * 1053static SV *
869decode_hv (dec_t *dec) 1054decode_hv (dec_t *dec)
870{ 1055{
1056 SV *sv;
871 HV *hv = newHV (); 1057 HV *hv = newHV ();
872 1058
873 DEC_INC_DEPTH; 1059 DEC_INC_DEPTH;
874 decode_ws (dec); 1060 decode_ws (dec);
875 1061
876 if (*dec->cur == '}') 1062 if (*dec->cur == '}')
877 ++dec->cur; 1063 ++dec->cur;
878 else 1064 else
879 for (;;) 1065 for (;;)
880 { 1066 {
881 SV *key, *value;
882
883 decode_ws (dec); EXPECT_CH ('"'); 1067 decode_ws (dec); EXPECT_CH ('"');
884 1068
885 key = decode_str (dec); 1069 // heuristic: assume that
886 if (!key) 1070 // a) decode_str + hv_store_ent are abysmally slow.
887 goto fail; 1071 // b) most hash keys are short, simple ascii text.
1072 // => try to "fast-match" such strings to avoid
1073 // the overhead of decode_str + hv_store_ent.
1074 {
1075 SV *value;
1076 char *p = dec->cur;
1077 char *e = p + 24; // only try up to 24 bytes
888 1078
889 decode_ws (dec); EXPECT_CH (':'); 1079 for (;;)
890
891 value = decode_sv (dec);
892 if (!value)
893 { 1080 {
1081 // the >= 0x80 is true on most architectures
1082 if (p == e || *p < 0x20 || *p >= 0x80 || *p == '\\')
1083 {
1084 // slow path, back up and use decode_str
1085 SV *key = decode_str (dec);
1086 if (!key)
1087 goto fail;
1088
1089 decode_ws (dec); EXPECT_CH (':');
1090
1091 value = decode_sv (dec);
1092 if (!value)
1093 {
1094 SvREFCNT_dec (key);
1095 goto fail;
1096 }
1097
1098 hv_store_ent (hv, key, value, 0);
894 SvREFCNT_dec (key); 1099 SvREFCNT_dec (key);
1100
1101 break;
1102 }
1103 else if (*p == '"')
1104 {
1105 // fast path, got a simple key
1106 char *key = dec->cur;
1107 int len = p - key;
1108 dec->cur = p + 1;
1109
1110 decode_ws (dec); EXPECT_CH (':');
1111
1112 value = decode_sv (dec);
1113 if (!value)
895 goto fail; 1114 goto fail;
1115
1116 hv_store (hv, key, len, value, 0);
1117
1118 break;
1119 }
1120
1121 ++p;
896 } 1122 }
897 1123 }
898 hv_store_ent (hv, key, value, 0);
899 SvREFCNT_dec (key);
900 1124
901 decode_ws (dec); 1125 decode_ws (dec);
902 1126
903 if (*dec->cur == '}') 1127 if (*dec->cur == '}')
904 { 1128 {
911 1135
912 ++dec->cur; 1136 ++dec->cur;
913 } 1137 }
914 1138
915 DEC_DEC_DEPTH; 1139 DEC_DEC_DEPTH;
916 return newRV_noinc ((SV *)hv); 1140 sv = newRV_noinc ((SV *)hv);
1141
1142 // check filter callbacks
1143 if (dec->json.flags & F_HOOK)
1144 {
1145 if (dec->json.cb_sk_object && HvKEYS (hv) == 1)
1146 {
1147 HE *cb, *he;
1148
1149 hv_iterinit (hv);
1150 he = hv_iternext (hv);
1151 hv_iterinit (hv);
1152
1153 // the next line creates a mortal sv each time its called.
1154 // might want to optimise this for common cases.
1155 cb = hv_fetch_ent (dec->json.cb_sk_object, hv_iterkeysv (he), 0, 0);
1156
1157 if (cb)
1158 {
1159 dSP;
1160 int count;
1161
1162 ENTER; SAVETMPS; PUSHMARK (SP);
1163 XPUSHs (HeVAL (he));
1164
1165 PUTBACK; count = call_sv (HeVAL (cb), G_ARRAY); SPAGAIN;
1166
1167 if (count == 1)
1168 {
1169 sv = newSVsv (POPs);
1170 FREETMPS; LEAVE;
1171 return sv;
1172 }
1173
1174 FREETMPS; LEAVE;
1175 }
1176 }
1177
1178 if (dec->json.cb_object)
1179 {
1180 dSP;
1181 int count;
1182
1183 ENTER; SAVETMPS; PUSHMARK (SP);
1184 XPUSHs (sv_2mortal (sv));
1185
1186 PUTBACK; count = call_sv (dec->json.cb_object, G_ARRAY); SPAGAIN;
1187
1188 if (count == 1)
1189 {
1190 sv = newSVsv (POPs);
1191 FREETMPS; LEAVE;
1192 return sv;
1193 }
1194
1195 SvREFCNT_inc (sv);
1196 FREETMPS; LEAVE;
1197 }
1198 }
1199
1200 return sv;
917 1201
918fail: 1202fail:
919 SvREFCNT_dec (hv); 1203 SvREFCNT_dec (hv);
920 DEC_DEC_DEPTH; 1204 DEC_DEC_DEPTH;
921 return 0; 1205 return 0;
923 1207
924static SV * 1208static SV *
925decode_sv (dec_t *dec) 1209decode_sv (dec_t *dec)
926{ 1210{
927 decode_ws (dec); 1211 decode_ws (dec);
1212
1213 // the beauty of JSON: you need exactly one character lookahead
1214 // to parse anything.
928 switch (*dec->cur) 1215 switch (*dec->cur)
929 { 1216 {
930 case '"': ++dec->cur; return decode_str (dec); 1217 case '"': ++dec->cur; return decode_str (dec);
931 case '[': ++dec->cur; return decode_av (dec); 1218 case '[': ++dec->cur; return decode_av (dec);
932 case '{': ++dec->cur; return decode_hv (dec); 1219 case '{': ++dec->cur; return decode_hv (dec);
938 1225
939 case 't': 1226 case 't':
940 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1227 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
941 { 1228 {
942 dec->cur += 4; 1229 dec->cur += 4;
943 return newSViv (1); 1230#if JSON_SLOW
1231 json_true = get_sv ("JSON::XS::true", 1); SvREADONLY_on (json_true);
1232#endif
1233 return SvREFCNT_inc (json_true);
944 } 1234 }
945 else 1235 else
946 ERR ("'true' expected"); 1236 ERR ("'true' expected");
947 1237
948 break; 1238 break;
949 1239
950 case 'f': 1240 case 'f':
951 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1241 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
952 { 1242 {
953 dec->cur += 5; 1243 dec->cur += 5;
954 return newSViv (0); 1244#if JSON_SLOW
1245 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1246#endif
1247 return SvREFCNT_inc (json_false);
955 } 1248 }
956 else 1249 else
957 ERR ("'false' expected"); 1250 ERR ("'false' expected");
958 1251
959 break; 1252 break;
977fail: 1270fail:
978 return 0; 1271 return 0;
979} 1272}
980 1273
981static SV * 1274static SV *
982decode_json (SV *string, U32 flags) 1275decode_json (SV *string, JSON *json, UV *offset_return)
983{ 1276{
984 dec_t dec; 1277 dec_t dec;
1278 UV offset;
985 SV *sv; 1279 SV *sv;
986 1280
1281 SvGETMAGIC (string);
987 SvUPGRADE (string, SVt_PV); 1282 SvUPGRADE (string, SVt_PV);
988 1283
1284 if (json->flags & F_MAXSIZE && SvCUR (string) > DEC_SIZE (json->flags))
1285 croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu",
1286 (unsigned long)SvCUR (string), (unsigned long)DEC_SIZE (json->flags));
1287
989 if (flags & F_UTF8) 1288 if (json->flags & F_UTF8)
990 sv_utf8_downgrade (string, 0); 1289 sv_utf8_downgrade (string, 0);
991 else 1290 else
992 sv_utf8_upgrade (string); 1291 sv_utf8_upgrade (string);
993 1292
994 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP 1293 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
995 1294
996 dec.flags = flags; 1295 dec.json = *json;
997 dec.cur = SvPVX (string); 1296 dec.cur = SvPVX (string);
998 dec.end = SvEND (string); 1297 dec.end = SvEND (string);
999 dec.err = 0; 1298 dec.err = 0;
1000 dec.depth = 0; 1299 dec.depth = 0;
1001 dec.maxdepth = DEC_DEPTH (dec.flags); 1300 dec.maxdepth = DEC_DEPTH (dec.json.flags);
1002 1301
1302 if (dec.json.cb_object || dec.json.cb_sk_object)
1303 dec.json.flags |= F_HOOK;
1304
1003 *dec.end = 0; // this should basically be a nop, too, but make sure its there 1305 *dec.end = 0; // this should basically be a nop, too, but make sure it's there
1004 sv = decode_sv (&dec); 1306 sv = decode_sv (&dec);
1005 1307
1308 if (!(offset_return || !sv))
1309 {
1310 // check for trailing garbage
1311 decode_ws (&dec);
1312
1313 if (*dec.cur)
1314 {
1315 dec.err = "garbage after JSON object";
1316 SvREFCNT_dec (sv);
1317 sv = 0;
1318 }
1319 }
1320
1321 if (offset_return || !sv)
1322 {
1323 offset = dec.json.flags & F_UTF8
1324 ? dec.cur - SvPVX (string)
1325 : utf8_distance (dec.cur, SvPVX (string));
1326
1327 if (offset_return)
1328 *offset_return = offset;
1329 }
1330
1006 if (!sv) 1331 if (!sv)
1007 { 1332 {
1008 IV offset = dec.flags & F_UTF8
1009 ? dec.cur - SvPVX (string)
1010 : utf8_distance (dec.cur, SvPVX (string));
1011 SV *uni = sv_newmortal (); 1333 SV *uni = sv_newmortal ();
1012 1334
1013 // horrible hack to silence warning inside pv_uni_display 1335 // horrible hack to silence warning inside pv_uni_display
1014 COP cop = *PL_curcop; 1336 COP cop = *PL_curcop;
1015 cop.cop_warnings = pWARN_NONE; 1337 cop.cop_warnings = pWARN_NONE;
1025 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); 1347 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
1026 } 1348 }
1027 1349
1028 sv = sv_2mortal (sv); 1350 sv = sv_2mortal (sv);
1029 1351
1030 if (!(dec.flags & F_ALLOW_NONREF) && !SvROK (sv)) 1352 if (!(dec.json.flags & F_ALLOW_NONREF) && !SvROK (sv))
1031 croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)"); 1353 croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)");
1032 1354
1033 return sv; 1355 return sv;
1034} 1356}
1035 1357
1039MODULE = JSON::XS PACKAGE = JSON::XS 1361MODULE = JSON::XS PACKAGE = JSON::XS
1040 1362
1041BOOT: 1363BOOT:
1042{ 1364{
1043 int i; 1365 int i;
1044
1045 memset (decode_hexdigit, 0xff, 256);
1046 1366
1047 for (i = 0; i < 256; ++i) 1367 for (i = 0; i < 256; ++i)
1048 decode_hexdigit [i] = 1368 decode_hexdigit [i] =
1049 i >= '0' && i <= '9' ? i - '0' 1369 i >= '0' && i <= '9' ? i - '0'
1050 : i >= 'a' && i <= 'f' ? i - 'a' + 10 1370 : i >= 'a' && i <= 'f' ? i - 'a' + 10
1051 : i >= 'A' && i <= 'F' ? i - 'A' + 10 1371 : i >= 'A' && i <= 'F' ? i - 'A' + 10
1052 : -1; 1372 : -1;
1053 1373
1054 json_stash = gv_stashpv ("JSON::XS", 1); 1374 json_stash = gv_stashpv ("JSON::XS" , 1);
1375 json_boolean_stash = gv_stashpv ("JSON::XS::Boolean", 1);
1376
1377 json_true = get_sv ("JSON::XS::true" , 1); SvREADONLY_on (json_true );
1378 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1055} 1379}
1056 1380
1057PROTOTYPES: DISABLE 1381PROTOTYPES: DISABLE
1058 1382
1059SV *new (char *dummy) 1383void CLONE (...)
1060 CODE: 1384 CODE:
1061 RETVAL = sv_bless (newRV_noinc (newSVuv (F_DEFAULT)), json_stash); 1385 json_stash = 0;
1062 OUTPUT: 1386 json_boolean_stash = 0;
1063 RETVAL
1064 1387
1388void new (char *klass)
1389 PPCODE:
1390{
1391 SV *pv = NEWSV (0, sizeof (JSON));
1392 SvPOK_only (pv);
1393 Zero (SvPVX (pv), 1, JSON);
1394 ((JSON *)SvPVX (pv))->flags = F_DEFAULT;
1395 XPUSHs (sv_2mortal (sv_bless (newRV_noinc (pv), JSON_STASH)));
1396}
1397
1065SV *ascii (SV *self, int enable = 1) 1398void ascii (JSON *self, int enable = 1)
1066 ALIAS: 1399 ALIAS:
1067 ascii = F_ASCII 1400 ascii = F_ASCII
1401 latin1 = F_LATIN1
1068 utf8 = F_UTF8 1402 utf8 = F_UTF8
1069 indent = F_INDENT 1403 indent = F_INDENT
1070 canonical = F_CANONICAL 1404 canonical = F_CANONICAL
1071 space_before = F_SPACE_BEFORE 1405 space_before = F_SPACE_BEFORE
1072 space_after = F_SPACE_AFTER 1406 space_after = F_SPACE_AFTER
1073 pretty = F_PRETTY 1407 pretty = F_PRETTY
1074 allow_nonref = F_ALLOW_NONREF 1408 allow_nonref = F_ALLOW_NONREF
1075 shrink = F_SHRINK 1409 shrink = F_SHRINK
1410 allow_blessed = F_ALLOW_BLESSED
1411 convert_blessed = F_CONV_BLESSED
1076 CODE: 1412 PPCODE:
1077{ 1413{
1078 UV *uv = SvJSON (self);
1079 if (enable) 1414 if (enable)
1080 *uv |= ix; 1415 self->flags |= ix;
1081 else 1416 else
1082 *uv &= ~ix; 1417 self->flags &= ~ix;
1083 1418
1084 RETVAL = newSVsv (self); 1419 XPUSHs (ST (0));
1085} 1420}
1086 OUTPUT:
1087 RETVAL
1088 1421
1089SV *max_depth (SV *self, UV max_depth = 0x80000000UL) 1422void max_depth (JSON *self, UV max_depth = 0x80000000UL)
1090 CODE: 1423 PPCODE:
1091{ 1424{
1092 UV *uv = SvJSON (self);
1093 UV log2 = 0; 1425 UV log2 = 0;
1094 1426
1095 if (max_depth > 0x80000000UL) max_depth = 0x80000000UL; 1427 if (max_depth > 0x80000000UL) max_depth = 0x80000000UL;
1096 1428
1097 while ((1UL << log2) < max_depth) 1429 while ((1UL << log2) < max_depth)
1098 ++log2; 1430 ++log2;
1099 1431
1100 *uv = *uv & ~F_MAXDEPTH | (log2 << S_MAXDEPTH); 1432 self->flags = self->flags & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1101 1433
1102 RETVAL = newSVsv (self); 1434 XPUSHs (ST (0));
1103} 1435}
1104 OUTPUT:
1105 RETVAL
1106 1436
1107void encode (SV *self, SV *scalar) 1437void max_size (JSON *self, UV max_size = 0)
1108 PPCODE: 1438 PPCODE:
1109 XPUSHs (encode_json (scalar, *SvJSON (self))); 1439{
1440 UV log2 = 0;
1110 1441
1111void decode (SV *self, SV *jsonstr) 1442 if (max_size > 0x80000000UL) max_size = 0x80000000UL;
1443 if (max_size == 1) max_size = 2;
1444
1445 while ((1UL << log2) < max_size)
1446 ++log2;
1447
1448 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE);
1449
1450 XPUSHs (ST (0));
1451}
1452
1453void filter_json_object (JSON *self, SV *cb = &PL_sv_undef)
1112 PPCODE: 1454 PPCODE:
1455{
1456 SvREFCNT_dec (self->cb_object);
1457 self->cb_object = SvOK (cb) ? newSVsv (cb) : 0;
1458
1459 XPUSHs (ST (0));
1460}
1461
1462void filter_json_single_key_object (JSON *self, SV *key, SV *cb = &PL_sv_undef)
1463 PPCODE:
1464{
1465 if (!self->cb_sk_object)
1466 self->cb_sk_object = newHV ();
1467
1468 if (SvOK (cb))
1469 hv_store_ent (self->cb_sk_object, key, newSVsv (cb), 0);
1470 else
1471 {
1472 hv_delete_ent (self->cb_sk_object, key, G_DISCARD, 0);
1473
1474 if (!HvKEYS (self->cb_sk_object))
1475 {
1476 SvREFCNT_dec (self->cb_sk_object);
1477 self->cb_sk_object = 0;
1478 }
1479 }
1480
1481 XPUSHs (ST (0));
1482}
1483
1484void encode (JSON *self, SV *scalar)
1485 PPCODE:
1486 XPUSHs (encode_json (scalar, self));
1487
1488void decode (JSON *self, SV *jsonstr)
1489 PPCODE:
1113 XPUSHs (decode_json (jsonstr, *SvJSON (self))); 1490 XPUSHs (decode_json (jsonstr, self, 0));
1491
1492void decode_prefix (JSON *self, SV *jsonstr)
1493 PPCODE:
1494{
1495 UV offset;
1496 EXTEND (SP, 2);
1497 PUSHs (decode_json (jsonstr, self, &offset));
1498 PUSHs (sv_2mortal (newSVuv (offset)));
1499}
1500
1501void DESTROY (JSON *self)
1502 CODE:
1503 SvREFCNT_dec (self->cb_sk_object);
1504 SvREFCNT_dec (self->cb_object);
1114 1505
1115PROTOTYPES: ENABLE 1506PROTOTYPES: ENABLE
1116 1507
1117void to_json (SV *scalar) 1508void to_json (SV *scalar)
1118 ALIAS:
1119 objToJson = 0
1120 PPCODE: 1509 PPCODE:
1510{
1511 JSON json = { F_DEFAULT | F_UTF8 };
1121 XPUSHs (encode_json (scalar, F_DEFAULT | F_UTF8)); 1512 XPUSHs (encode_json (scalar, &json));
1513}
1122 1514
1123void from_json (SV *jsonstr) 1515void from_json (SV *jsonstr)
1124 ALIAS:
1125 jsonToObj = 0
1126 PPCODE: 1516 PPCODE:
1517{
1518 JSON json = { F_DEFAULT | F_UTF8 };
1127 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8)); 1519 XPUSHs (decode_json (jsonstr, &json, 0));
1520}
1128 1521

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines