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.6 by root, Fri Mar 23 15:10:55 2007 UTC vs.
Revision 1.22 by root, Sat Mar 31 14:20:06 2007 UTC

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 8
9#define F_ASCII 0x00000001 9#define F_ASCII 0x00000001UL
10#define F_UTF8 0x00000002 10#define F_UTF8 0x00000002UL
11#define F_INDENT 0x00000004 11#define F_INDENT 0x00000004UL
12#define F_CANONICAL 0x00000008 12#define F_CANONICAL 0x00000008UL
13#define F_SPACE_BEFORE 0x00000010 13#define F_SPACE_BEFORE 0x00000010UL
14#define F_SPACE_AFTER 0x00000020 14#define F_SPACE_AFTER 0x00000020UL
15#define F_JSON_RPC 0x00000040
16#define F_ALLOW_NONREF 0x00000080 15#define F_ALLOW_NONREF 0x00000080UL
17#define F_SHRINK 0x00000100 16#define F_SHRINK 0x00000100UL
17#define F_MAXDEPTH 0xf8000000UL
18#define S_MAXDEPTH 27
19
20#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH))
21
22// F_SELFCONVERT? <=> to_json/toJson
23// F_BLESSED? <=> { $__class__$ => }
18 24
19#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER 25#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER
20#define F_DEFAULT 0 26#define F_DEFAULT (12UL << S_MAXDEPTH)
21 27
22#define INIT_SIZE 32 // initial scalar size to be allocated 28#define INIT_SIZE 32 // initial scalar size to be allocated
29#define INDENT_STEP 3 // spaces per indentation level
30
31#define UTF8_MAX_LEN 11 // for perls UTF-X: max. number of octets per character
32#define SHORT_STRING_LEN 512 // special-case strings of up to this size
23 33
24#define SB do { 34#define SB do {
25#define SE } while (0) 35#define SE } while (0)
26 36
27static HV *json_stash; 37static HV *json_stash; // JSON::XS::
38
39/////////////////////////////////////////////////////////////////////////////
40// utility functions
41
42static UV *
43SvJSON (SV *sv)
44{
45 if (!(SvROK (sv) && SvOBJECT (SvRV (sv)) && SvSTASH (SvRV (sv)) == json_stash))
46 croak ("object is not of type JSON::XS");
47
48 return &SvUVX (SvRV (sv));
49}
50
51static void
52shrink (SV *sv)
53{
54 sv_utf8_downgrade (sv, 1);
55 if (SvLEN (sv) > SvCUR (sv) + 1)
56 {
57#ifdef SvPV_shrink_to_cur
58 SvPV_shrink_to_cur (sv);
59#elif defined (SvPV_renew)
60 SvPV_renew (sv, SvCUR (sv) + 1);
61#endif
62 }
63}
64
65// decode an utf-8 character and return it, or (UV)-1 in
66// case of an error.
67// we special-case "safe" characters from U+80 .. U+7FF,
68// but use the very good perl function to parse anything else.
69// note that we never call this function for a ascii codepoints
70static UV
71decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
72{
73 if (s[0] > 0xdf || s[0] < 0xc2)
74 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY);
75 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf)
76 {
77 *clen = 2;
78 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
79 }
80 else
81 return (UV)-1;
82}
83
84/////////////////////////////////////////////////////////////////////////////
85// encoder
28 86
29// structure used for encoding JSON 87// structure used for encoding JSON
30typedef struct 88typedef struct
31{ 89{
32 char *cur; 90 char *cur; // SvPVX (sv) + current output position
33 STRLEN len; // SvLEN (sv)
34 char *end; // SvEND (sv) 91 char *end; // SvEND (sv)
35 SV *sv; 92 SV *sv; // result scalar
36 UV flags; 93 U32 flags; // F_*
37 int max_recurse; 94 U32 indent; // indentation level
38 int indent; 95 U32 maxdepth; // max. indentation/recursion level
39} enc_t; 96} enc_t;
40
41// structure used for decoding JSON
42typedef struct
43{
44 char *cur;
45 char *end;
46 const char *err;
47 UV flags;
48} dec_t;
49
50static UV *
51SvJSON (SV *sv)
52{
53 if (!(SvROK (sv) && SvOBJECT (SvRV (sv)) && SvSTASH (SvRV (sv)) == json_stash))
54 croak ("object is not of type JSON::XS");
55
56 return &SvUVX (SvRV (sv));
57}
58
59/////////////////////////////////////////////////////////////////////////////
60 97
61static void 98static void
62need (enc_t *enc, STRLEN len) 99need (enc_t *enc, STRLEN len)
63{ 100{
64 if (enc->cur + len >= enc->end) 101 if (enc->cur + len >= enc->end)
122 STRLEN clen; 159 STRLEN clen;
123 UV uch; 160 UV uch;
124 161
125 if (is_utf8) 162 if (is_utf8)
126 { 163 {
127 uch = utf8n_to_uvuni (str, end - str, &clen, UTF8_CHECK_ONLY); 164 //uch = utf8n_to_uvuni (str, end - str, &clen, UTF8_CHECK_ONLY);
165 uch = decode_utf8 (str, end - str, &clen);
128 if (clen == (STRLEN)-1) 166 if (clen == (STRLEN)-1)
129 croak ("malformed UTF-8 character in string, cannot convert to JSON"); 167 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str);
130 } 168 }
131 else 169 else
132 { 170 {
133 uch = ch; 171 uch = ch;
134 clen = 1; 172 clen = 1;
135 } 173 }
136 174
175 if (uch > 0x10FFFFUL)
176 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
177
137 if (uch < 0x80 || enc->flags & F_ASCII) 178 if (uch < 0x80 || enc->flags & F_ASCII)
138 { 179 {
139 if (uch > 0xFFFFUL) 180 if (uch > 0xFFFFUL)
140 { 181 {
141 need (enc, len += 11); 182 need (enc, len += 11);
142 sprintf (enc->cur, "\\u%04x\\u%04x", 183 sprintf (enc->cur, "\\u%04x\\u%04x",
143 (uch - 0x10000) / 0x400 + 0xD800, 184 (int)((uch - 0x10000) / 0x400 + 0xD800),
144 (uch - 0x10000) % 0x400 + 0xDC00); 185 (int)((uch - 0x10000) % 0x400 + 0xDC00));
145 enc->cur += 12; 186 enc->cur += 12;
146 } 187 }
147 else 188 else
148 { 189 {
149 static char hexdigit [16] = "0123456789abcdef"; 190 static char hexdigit [16] = "0123456789abcdef";
167 } 208 }
168 while (--clen); 209 while (--clen);
169 } 210 }
170 else 211 else
171 { 212 {
172 need (enc, 10); // never more than 11 bytes needed 213 need (enc, len += UTF8_MAX_LEN - 1); // never more than 11 bytes needed
173 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); 214 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0);
174 ++str; 215 ++str;
175 } 216 }
176 } 217 }
177 } 218 }
179 220
180 --len; 221 --len;
181 } 222 }
182} 223}
183 224
184#define INDENT SB \ 225static void
226encode_indent (enc_t *enc)
227{
185 if (enc->flags & F_INDENT) \ 228 if (enc->flags & F_INDENT)
186 { \ 229 {
187 int i_; \ 230 int spaces = enc->indent * INDENT_STEP;
188 need (enc, enc->indent); \
189 for (i_ = enc->indent * 3; i_--; )\
190 encode_ch (enc, ' '); \
191 } \
192 SE
193 231
194#define SPACE SB need (enc, 1); encode_ch (enc, ' '); SE 232 need (enc, spaces);
195#define NL SB if (enc->flags & F_INDENT) { need (enc, 1); encode_ch (enc, '\n'); } SE 233 memset (enc->cur, ' ', spaces);
196#define COMMA SB \ 234 enc->cur += spaces;
235 }
236}
237
238static void
239encode_space (enc_t *enc)
240{
241 need (enc, 1);
197 encode_ch (enc, ','); \ 242 encode_ch (enc, ' ');
243}
244
245static void
246encode_nl (enc_t *enc)
247{
198 if (enc->flags & F_INDENT) \ 248 if (enc->flags & F_INDENT)
199 NL; \ 249 {
250 need (enc, 1);
251 encode_ch (enc, '\n');
252 }
253}
254
255static void
256encode_comma (enc_t *enc)
257{
258 encode_ch (enc, ',');
259
260 if (enc->flags & F_INDENT)
261 encode_nl (enc);
200 else if (enc->flags & F_SPACE_AFTER) \ 262 else if (enc->flags & F_SPACE_AFTER)
201 SPACE; \ 263 encode_space (enc);
202 SE 264}
203 265
204static void encode_sv (enc_t *enc, SV *sv); 266static void encode_sv (enc_t *enc, SV *sv);
205 267
206static void 268static void
207encode_av (enc_t *enc, AV *av) 269encode_av (enc_t *enc, AV *av)
208{ 270{
209 int i, len = av_len (av); 271 int i, len = av_len (av);
210 272
211 encode_ch (enc, '['); NL; 273 if (enc->indent >= enc->maxdepth)
274 croak ("data structure too deep (hit recursion limit)");
275
276 encode_ch (enc, '['); encode_nl (enc);
212 ++enc->indent; 277 ++enc->indent;
213 278
214 for (i = 0; i <= len; ++i) 279 for (i = 0; i <= len; ++i)
215 { 280 {
216 INDENT; 281 encode_indent (enc);
217 encode_sv (enc, *av_fetch (av, i, 0)); 282 encode_sv (enc, *av_fetch (av, i, 0));
218 283
219 if (i < len) 284 if (i < len)
220 COMMA; 285 encode_comma (enc);
221 } 286 }
222 287
223 NL; 288 encode_nl (enc);
224 289
225 --enc->indent; 290 --enc->indent;
226 INDENT; encode_ch (enc, ']'); 291 encode_indent (enc); encode_ch (enc, ']');
227} 292}
228 293
229static void 294static void
230encode_he (enc_t *enc, HE *he) 295encode_he (enc_t *enc, HE *he)
231{ 296{
245 else 310 else
246 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he)); 311 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he));
247 312
248 encode_ch (enc, '"'); 313 encode_ch (enc, '"');
249 314
250 if (enc->flags & F_SPACE_BEFORE) SPACE; 315 if (enc->flags & F_SPACE_BEFORE) encode_space (enc);
251 encode_ch (enc, ':'); 316 encode_ch (enc, ':');
252 if (enc->flags & F_SPACE_AFTER ) SPACE; 317 if (enc->flags & F_SPACE_AFTER ) encode_space (enc);
253 encode_sv (enc, HeVAL (he)); 318 encode_sv (enc, HeVAL (he));
254} 319}
255 320
256// compare hash entries, used when all keys are bytestrings 321// compare hash entries, used when all keys are bytestrings
257static int 322static int
263 HE *b = *(HE **)b_; 328 HE *b = *(HE **)b_;
264 329
265 STRLEN la = HeKLEN (a); 330 STRLEN la = HeKLEN (a);
266 STRLEN lb = HeKLEN (b); 331 STRLEN lb = HeKLEN (b);
267 332
268 if (!(cmp == memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb))) 333 if (!(cmp = memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb)))
269 cmp = la < lb ? -1 : la == lb ? 0 : 1; 334 cmp = la - lb;
270 335
271 return cmp; 336 return cmp;
272} 337}
273 338
274// compare hash entries, used when some keys are sv's or utf-x 339// compare hash entries, used when some keys are sv's or utf-x
281static void 346static void
282encode_hv (enc_t *enc, HV *hv) 347encode_hv (enc_t *enc, HV *hv)
283{ 348{
284 int count, i; 349 int count, i;
285 350
351 if (enc->indent >= enc->maxdepth)
352 croak ("data structure too deep (hit recursion limit)");
353
286 encode_ch (enc, '{'); NL; ++enc->indent; 354 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent;
287 355
288 if ((count = hv_iterinit (hv))) 356 if ((count = hv_iterinit (hv)))
289 { 357 {
290 // for canonical output we have to sort by keys first 358 // for canonical output we have to sort by keys first
291 // actually, this is mostly due to the stupid so-called 359 // actually, this is mostly due to the stupid so-called
292 // security workaround added somewhere in 5.8.x. 360 // security workaround added somewhere in 5.8.x.
293 // that randomises hash orderings 361 // that randomises hash orderings
294 if (enc->flags & F_CANONICAL) 362 if (enc->flags & F_CANONICAL)
295 { 363 {
296 HE *he, *hes [count]; 364 HE *he, *hes [count]; // if your compiler dies here, you need to enable C99 mode
297 int fast = 1; 365 int fast = 1;
298 366
299 i = 0; 367 i = 0;
300 while ((he = hv_iternext (hv))) 368 while ((he = hv_iternext (hv)))
301 { 369 {
308 376
309 if (fast) 377 if (fast)
310 qsort (hes, count, sizeof (HE *), he_cmp_fast); 378 qsort (hes, count, sizeof (HE *), he_cmp_fast);
311 else 379 else
312 { 380 {
313 // hack to disable "use bytes" 381 // hack to forcefully disable "use bytes"
314 COP *oldcop = PL_curcop, cop; 382 COP cop = *PL_curcop;
315 cop.op_private = 0; 383 cop.op_private = 0;
384
385 ENTER;
386 SAVETMPS;
387
388 SAVEVPTR (PL_curcop);
316 PL_curcop = &cop; 389 PL_curcop = &cop;
317 390
318 SAVETMPS;
319 qsort (hes, count, sizeof (HE *), he_cmp_slow); 391 qsort (hes, count, sizeof (HE *), he_cmp_slow);
392
320 FREETMPS; 393 FREETMPS;
321 394 LEAVE;
322 PL_curcop = oldcop;
323 } 395 }
324 396
325 for (i = 0; i < count; ++i) 397 for (i = 0; i < count; ++i)
326 { 398 {
327 INDENT; 399 encode_indent (enc);
328 encode_he (enc, hes [i]); 400 encode_he (enc, hes [i]);
329 401
330 if (i < count - 1) 402 if (i < count - 1)
331 COMMA; 403 encode_comma (enc);
332 } 404 }
333 405
334 NL; 406 encode_nl (enc);
335 } 407 }
336 else 408 else
337 { 409 {
338 SV *sv; 410 SV *sv;
339 HE *he = hv_iternext (hv); 411 HE *he = hv_iternext (hv);
340 412
341 for (;;) 413 for (;;)
342 { 414 {
343 INDENT; 415 encode_indent (enc);
344 encode_he (enc, he); 416 encode_he (enc, he);
345 417
346 if (!(he = hv_iternext (hv))) 418 if (!(he = hv_iternext (hv)))
347 break; 419 break;
348 420
349 COMMA; 421 encode_comma (enc);
350 } 422 }
351 423
352 NL; 424 encode_nl (enc);
353 } 425 }
354 } 426 }
355 427
356 --enc->indent; INDENT; encode_ch (enc, '}'); 428 --enc->indent; encode_indent (enc); encode_ch (enc, '}');
429}
430
431// encode objects, arrays and special \0=false and \1=true values.
432static void
433encode_rv (enc_t *enc, SV *sv)
434{
435 SvGETMAGIC (sv);
436
437 svtype svt = SvTYPE (sv);
438
439 if (svt == SVt_PVHV)
440 encode_hv (enc, (HV *)sv);
441 else if (svt == SVt_PVAV)
442 encode_av (enc, (AV *)sv);
443 else if (svt < SVt_PVAV)
444 {
445 if (SvNIOK (sv) && SvIV (sv) == 0)
446 encode_str (enc, "false", 5, 0);
447 else if (SvNIOK (sv) && SvIV (sv) == 1)
448 encode_str (enc, "true", 4, 0);
449 else
450 croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1",
451 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
452 }
453 else
454 croak ("encountered %s, but JSON can only represent references to arrays or hashes",
455 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
357} 456}
358 457
359static void 458static void
360encode_sv (enc_t *enc, SV *sv) 459encode_sv (enc_t *enc, SV *sv)
361{ 460{
382 SvIsUV(sv) 481 SvIsUV(sv)
383 ? snprintf (enc->cur, 64, "%"UVuf, (UV)SvUVX (sv)) 482 ? snprintf (enc->cur, 64, "%"UVuf, (UV)SvUVX (sv))
384 : snprintf (enc->cur, 64, "%"IVdf, (IV)SvIVX (sv)); 483 : snprintf (enc->cur, 64, "%"IVdf, (IV)SvIVX (sv));
385 } 484 }
386 else if (SvROK (sv)) 485 else if (SvROK (sv))
387 { 486 encode_rv (enc, SvRV (sv));
388 if (!--enc->max_recurse)
389 croak ("data structure too deep (hit recursion limit)");
390
391 sv = SvRV (sv);
392
393 switch (SvTYPE (sv))
394 {
395 case SVt_PVAV: encode_av (enc, (AV *)sv); break;
396 case SVt_PVHV: encode_hv (enc, (HV *)sv); break;
397
398 default:
399 croak ("JSON can only represent references to arrays or hashes");
400 }
401 }
402 else if (!SvOK (sv)) 487 else if (!SvOK (sv))
403 encode_str (enc, "null", 4, 0); 488 encode_str (enc, "null", 4, 0);
404 else 489 else
405 croak ("encountered perl type that JSON cannot handle"); 490 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this",
491 SvPV_nolen (sv), SvFLAGS (sv));
406} 492}
407 493
408static SV * 494static SV *
409encode_json (SV *scalar, UV flags) 495encode_json (SV *scalar, U32 flags)
410{ 496{
411 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar)) 497 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar))
412 croak ("hash- or arraref required (not a simple scalar, use allow_nonref to allow this)"); 498 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)");
413 499
414 enc_t enc; 500 enc_t enc;
415 enc.flags = flags; 501 enc.flags = flags;
416 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 502 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
417 enc.cur = SvPVX (enc.sv); 503 enc.cur = SvPVX (enc.sv);
418 enc.end = SvEND (enc.sv); 504 enc.end = SvEND (enc.sv);
419 enc.max_recurse = 0;
420 enc.indent = 0; 505 enc.indent = 0;
506 enc.maxdepth = DEC_DEPTH (flags);
421 507
422 SvPOK_only (enc.sv); 508 SvPOK_only (enc.sv);
423 encode_sv (&enc, scalar); 509 encode_sv (&enc, scalar);
424 510
425 if (!(flags & (F_ASCII | F_UTF8))) 511 if (!(flags & (F_ASCII | F_UTF8)))
426 SvUTF8_on (enc.sv); 512 SvUTF8_on (enc.sv);
427 513
428 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); 514 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
429 515
430#ifdef SvPV_shrink_to_cur
431 if (enc.flags & F_SHRINK) 516 if (enc.flags & F_SHRINK)
432 SvPV_shrink_to_cur (enc.sv); 517 shrink (enc.sv);
433#endif 518
434 return enc.sv; 519 return enc.sv;
435} 520}
436 521
437///////////////////////////////////////////////////////////////////////////// 522/////////////////////////////////////////////////////////////////////////////
523// decoder
438 524
439#define WS \ 525// structure used for decoding JSON
526typedef struct
527{
528 char *cur; // current parser pointer
529 char *end; // end of input string
530 const char *err; // parse error, if != 0
531 U32 flags; // F_*
532 U32 depth; // recursion depth
533 U32 maxdepth; // recursion depth limit
534} dec_t;
535
536static void
537decode_ws (dec_t *dec)
538{
440 for (;;) \ 539 for (;;)
441 { \ 540 {
442 char ch = *dec->cur; \ 541 char ch = *dec->cur;
542
443 if (ch > 0x20 \ 543 if (ch > 0x20
444 || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)) \ 544 || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09))
445 break; \ 545 break;
546
446 ++dec->cur; \ 547 ++dec->cur;
447 } 548 }
549}
448 550
449#define ERR(reason) SB dec->err = reason; goto fail; SE 551#define ERR(reason) SB dec->err = reason; goto fail; SE
552
450#define EXPECT_CH(ch) SB \ 553#define EXPECT_CH(ch) SB \
451 if (*dec->cur != ch) \ 554 if (*dec->cur != ch) \
452 ERR (# ch " expected"); \ 555 ERR (# ch " expected"); \
453 ++dec->cur; \ 556 ++dec->cur; \
454 SE 557 SE
455 558
559#define DEC_INC_DEPTH if (++dec->depth > dec->maxdepth) ERR ("json datastructure exceeds maximum nesting level (set a higher max_depth)")
560#define DEC_DEC_DEPTH --dec->depth
561
456static SV *decode_sv (dec_t *dec); 562static SV *decode_sv (dec_t *dec);
457 563
458static signed char decode_hexdigit[256]; 564static signed char decode_hexdigit[256];
459 565
460static UV 566static UV
461decode_4hex (dec_t *dec) 567decode_4hex (dec_t *dec)
462{ 568{
463 signed char d1, d2, d3, d4; 569 signed char d1, d2, d3, d4;
570 unsigned char *cur = (unsigned char *)dec->cur;
464 571
465 d1 = decode_hexdigit [((unsigned char *)dec->cur) [0]];
466 if (d1 < 0) ERR ("four hexadecimal digits expected"); 572 d1 = decode_hexdigit [cur [0]]; if (d1 < 0) ERR ("four hexadecimal digits expected");
467 d2 = decode_hexdigit [((unsigned char *)dec->cur) [1]];
468 if (d2 < 0) ERR ("four hexadecimal digits expected"); 573 d2 = decode_hexdigit [cur [1]]; if (d2 < 0) ERR ("four hexadecimal digits expected");
469 d3 = decode_hexdigit [((unsigned char *)dec->cur) [2]];
470 if (d3 < 0) ERR ("four hexadecimal digits expected"); 574 d3 = decode_hexdigit [cur [2]]; if (d3 < 0) ERR ("four hexadecimal digits expected");
471 d4 = decode_hexdigit [((unsigned char *)dec->cur) [3]];
472 if (d4 < 0) ERR ("four hexadecimal digits expected"); 575 d4 = decode_hexdigit [cur [3]]; if (d4 < 0) ERR ("four hexadecimal digits expected");
473 576
474 dec->cur += 4; 577 dec->cur += 4;
475 578
476 return ((UV)d1) << 12 579 return ((UV)d1) << 12
477 | ((UV)d2) << 8 580 | ((UV)d2) << 8
480 583
481fail: 584fail:
482 return (UV)-1; 585 return (UV)-1;
483} 586}
484 587
485#define APPEND_GROW(n) SB \
486 if (cur + (n) >= end) \
487 { \
488 STRLEN ofs = cur - SvPVX (sv); \
489 SvGROW (sv, ofs + (n) + 1); \
490 cur = SvPVX (sv) + ofs; \
491 end = SvEND (sv); \
492 } \
493 SE
494
495#define APPEND_CH(ch) SB \
496 APPEND_GROW (1); \
497 *cur++ = (ch); \
498 SE
499
500static SV * 588static SV *
501decode_str (dec_t *dec) 589decode_str (dec_t *dec)
502{ 590{
503 SV *sv = NEWSV (0,2); 591 SV *sv = 0;
504 int utf8 = 0; 592 int utf8 = 0;
505 char *cur = SvPVX (sv);
506 char *end = SvEND (sv);
507 593
508 for (;;) 594 do
509 { 595 {
510 unsigned char ch = *(unsigned char *)dec->cur; 596 char buf [SHORT_STRING_LEN + UTF8_MAX_LEN];
597 char *cur = buf;
511 598
512 if (ch == '"') 599 do
513 break;
514 else if (ch == '\\')
515 { 600 {
516 switch (*++dec->cur) 601 unsigned char ch = *(unsigned char *)dec->cur++;
602
603 if (ch == '"')
517 { 604 {
518 case '\\': 605 --dec->cur;
519 case '/': 606 break;
520 case '"': APPEND_CH (*dec->cur++); break; 607 }
521 608 else if (ch == '\\')
522 case 'b': APPEND_CH ('\010'); ++dec->cur; break; 609 {
523 case 't': APPEND_CH ('\011'); ++dec->cur; break; 610 switch (*dec->cur)
524 case 'n': APPEND_CH ('\012'); ++dec->cur; break;
525 case 'f': APPEND_CH ('\014'); ++dec->cur; break;
526 case 'r': APPEND_CH ('\015'); ++dec->cur; break;
527
528 case 'u':
529 { 611 {
530 UV lo, hi; 612 case '\\':
531 ++dec->cur; 613 case '/':
614 case '"': *cur++ = *dec->cur++; break;
532 615
533 hi = decode_4hex (dec); 616 case 'b': ++dec->cur; *cur++ = '\010'; break;
534 if (hi == (UV)-1) 617 case 't': ++dec->cur; *cur++ = '\011'; break;
535 goto fail; 618 case 'n': ++dec->cur; *cur++ = '\012'; break;
619 case 'f': ++dec->cur; *cur++ = '\014'; break;
620 case 'r': ++dec->cur; *cur++ = '\015'; break;
536 621
537 // possibly a surrogate pair 622 case 'u':
538 if (hi >= 0xd800 && hi < 0xdc00)
539 { 623 {
540 if (dec->cur [0] != '\\' || dec->cur [1] != 'u') 624 UV lo, hi;
541 ERR ("missing low surrogate character in surrogate pair");
542
543 dec->cur += 2; 625 ++dec->cur;
544 626
545 lo = decode_4hex (dec); 627 hi = decode_4hex (dec);
546 if (lo == (UV)-1) 628 if (hi == (UV)-1)
547 goto fail; 629 goto fail;
548 630
631 // possibly a surrogate pair
632 if (hi >= 0xd800)
633 if (hi < 0xdc00)
634 {
635 if (dec->cur [0] != '\\' || dec->cur [1] != 'u')
636 ERR ("missing low surrogate character in surrogate pair");
637
638 dec->cur += 2;
639
640 lo = decode_4hex (dec);
641 if (lo == (UV)-1)
642 goto fail;
643
549 if (lo < 0xdc00 || lo >= 0xe000) 644 if (lo < 0xdc00 || lo >= 0xe000)
550 ERR ("surrogate pair expected"); 645 ERR ("surrogate pair expected");
551 646
552 hi = (hi - 0xD800) * 0x400 + (lo - 0xDC00) + 0x10000; 647 hi = (hi - 0xD800) * 0x400 + (lo - 0xDC00) + 0x10000;
648 }
649 else if (hi < 0xe000)
650 ERR ("missing high surrogate character in surrogate pair");
651
652 if (hi >= 0x80)
653 {
654 utf8 = 1;
655
656 cur = (char *)uvuni_to_utf8_flags (cur, hi, 0);
657 }
658 else
659 *cur++ = hi;
553 } 660 }
554 else if (hi >= 0xdc00 && hi < 0xe000)
555 ERR ("missing high surrogate character in surrogate pair");
556
557 if (hi >= 0x80)
558 { 661 break;
559 utf8 = 1;
560 662
561 APPEND_GROW (4); // at most 4 bytes for 21 bits
562 cur = (char *)uvuni_to_utf8_flags (cur, hi, 0);
563 }
564 else 663 default:
565 APPEND_CH (hi); 664 --dec->cur;
665 ERR ("illegal backslash escape sequence in string");
566 } 666 }
567 break;
568
569 default:
570 --dec->cur;
571 ERR ("illegal backslash escape sequence in string");
572 } 667 }
668 else if (ch >= 0x20 && ch <= 0x7f)
669 *cur++ = ch;
670 else if (ch >= 0x80)
671 {
672 --dec->cur;
673
674 STRLEN clen;
675 UV uch = decode_utf8 (dec->cur, dec->end - dec->cur, &clen);
676 if (clen == (STRLEN)-1)
677 ERR ("malformed UTF-8 character in JSON string");
678
679 do
680 {
681 *cur++ = *dec->cur++;
682 }
683 while (--clen);
684
685 utf8 = 1;
686 }
687 else if (!ch)
688 ERR ("unexpected end of string while parsing json string");
689 else
690 ERR ("invalid character encountered");
691
573 } 692 }
574 else if (ch >= 0x20 && ch <= 0x7f) 693 while (cur < buf + SHORT_STRING_LEN);
575 APPEND_CH (*dec->cur++); 694
576 else if (ch >= 0x80) 695 STRLEN len = cur - buf;
696
697 if (sv)
577 { 698 {
578 STRLEN clen; 699 SvGROW (sv, SvCUR (sv) + len + 1);
579 UV uch = utf8n_to_uvuni (dec->cur, dec->end - dec->cur, &clen, UTF8_CHECK_ONLY); 700 memcpy (SvPVX (sv) + SvCUR (sv), buf, len);
580 if (clen == (STRLEN)-1) 701 SvCUR_set (sv, SvCUR (sv) + len);
581 ERR ("malformed UTF-8 character in string, cannot convert to JSON");
582
583 APPEND_GROW (clen);
584 do
585 {
586 *cur++ = *dec->cur++;
587 }
588 while (--clen);
589
590 utf8 = 1;
591 } 702 }
592 else if (dec->cur == dec->end)
593 ERR ("unexpected end of string while parsing json string");
594 else 703 else
595 ERR ("invalid character encountered"); 704 sv = newSVpvn (buf, len);
596 } 705 }
706 while (*dec->cur != '"');
597 707
598 ++dec->cur; 708 ++dec->cur;
599 709
600 SvCUR_set (sv, cur - SvPVX (sv)); 710 if (sv)
601 711 {
602 SvPOK_only (sv); 712 SvPOK_only (sv);
603 *SvEND (sv) = 0; 713 *SvEND (sv) = 0;
604 714
605 if (utf8) 715 if (utf8)
606 SvUTF8_on (sv); 716 SvUTF8_on (sv);
607 717 }
608#ifdef SvPV_shrink_to_cur 718 else
609 if (dec->flags & F_SHRINK) 719 sv = newSVpvn ("", 0);
610 SvPV_shrink_to_cur (sv);
611#endif
612 720
613 return sv; 721 return sv;
614 722
615fail: 723fail:
616 SvREFCNT_dec (sv);
617 return 0; 724 return 0;
618} 725}
619 726
620static SV * 727static SV *
621decode_num (dec_t *dec) 728decode_num (dec_t *dec)
702static SV * 809static SV *
703decode_av (dec_t *dec) 810decode_av (dec_t *dec)
704{ 811{
705 AV *av = newAV (); 812 AV *av = newAV ();
706 813
707 WS; 814 DEC_INC_DEPTH;
815 decode_ws (dec);
816
708 if (*dec->cur == ']') 817 if (*dec->cur == ']')
709 ++dec->cur; 818 ++dec->cur;
710 else 819 else
711 for (;;) 820 for (;;)
712 { 821 {
716 if (!value) 825 if (!value)
717 goto fail; 826 goto fail;
718 827
719 av_push (av, value); 828 av_push (av, value);
720 829
721 WS; 830 decode_ws (dec);
722 831
723 if (*dec->cur == ']') 832 if (*dec->cur == ']')
724 { 833 {
725 ++dec->cur; 834 ++dec->cur;
726 break; 835 break;
730 ERR (", or ] expected while parsing array"); 839 ERR (", or ] expected while parsing array");
731 840
732 ++dec->cur; 841 ++dec->cur;
733 } 842 }
734 843
844 DEC_DEC_DEPTH;
735 return newRV_noinc ((SV *)av); 845 return newRV_noinc ((SV *)av);
736 846
737fail: 847fail:
738 SvREFCNT_dec (av); 848 SvREFCNT_dec (av);
849 DEC_DEC_DEPTH;
739 return 0; 850 return 0;
740} 851}
741 852
742static SV * 853static SV *
743decode_hv (dec_t *dec) 854decode_hv (dec_t *dec)
744{ 855{
745 HV *hv = newHV (); 856 HV *hv = newHV ();
746 857
747 WS; 858 DEC_INC_DEPTH;
859 decode_ws (dec);
860
748 if (*dec->cur == '}') 861 if (*dec->cur == '}')
749 ++dec->cur; 862 ++dec->cur;
750 else 863 else
751 for (;;) 864 for (;;)
752 { 865 {
753 SV *key, *value; 866 SV *key, *value;
754 867
755 WS; EXPECT_CH ('"'); 868 decode_ws (dec); EXPECT_CH ('"');
756 869
757 key = decode_str (dec); 870 key = decode_str (dec);
758 if (!key) 871 if (!key)
759 goto fail; 872 goto fail;
760 873
761 WS; EXPECT_CH (':'); 874 decode_ws (dec); EXPECT_CH (':');
762 875
763 value = decode_sv (dec); 876 value = decode_sv (dec);
764 if (!value) 877 if (!value)
765 { 878 {
766 SvREFCNT_dec (key); 879 SvREFCNT_dec (key);
767 goto fail; 880 goto fail;
768 } 881 }
769 882
770 //TODO: optimise
771 hv_store_ent (hv, key, value, 0); 883 hv_store_ent (hv, key, value, 0);
884 SvREFCNT_dec (key);
772 885
773 WS; 886 decode_ws (dec);
774 887
775 if (*dec->cur == '}') 888 if (*dec->cur == '}')
776 { 889 {
777 ++dec->cur; 890 ++dec->cur;
778 break; 891 break;
782 ERR (", or } expected while parsing object/hash"); 895 ERR (", or } expected while parsing object/hash");
783 896
784 ++dec->cur; 897 ++dec->cur;
785 } 898 }
786 899
900 DEC_DEC_DEPTH;
787 return newRV_noinc ((SV *)hv); 901 return newRV_noinc ((SV *)hv);
788 902
789fail: 903fail:
790 SvREFCNT_dec (hv); 904 SvREFCNT_dec (hv);
905 DEC_DEC_DEPTH;
791 return 0; 906 return 0;
792} 907}
793 908
794static SV * 909static SV *
795decode_sv (dec_t *dec) 910decode_sv (dec_t *dec)
796{ 911{
797 WS; 912 decode_ws (dec);
798 switch (*dec->cur) 913 switch (*dec->cur)
799 { 914 {
800 case '"': ++dec->cur; return decode_str (dec); 915 case '"': ++dec->cur; return decode_str (dec);
801 case '[': ++dec->cur; return decode_av (dec); 916 case '[': ++dec->cur; return decode_av (dec);
802 case '{': ++dec->cur; return decode_hv (dec); 917 case '{': ++dec->cur; return decode_hv (dec);
838 ERR ("'null' expected"); 953 ERR ("'null' expected");
839 954
840 break; 955 break;
841 956
842 default: 957 default:
843 ERR ("malformed json string"); 958 ERR ("malformed json string, neither array, object, number, string or atom");
844 break; 959 break;
845 } 960 }
846 961
847fail: 962fail:
848 return 0; 963 return 0;
849} 964}
850 965
851static SV * 966static SV *
852decode_json (SV *string, UV flags) 967decode_json (SV *string, U32 flags)
853{ 968{
854 SV *sv; 969 SV *sv;
970
971 SvUPGRADE (string, SVt_PV);
855 972
856 if (flags & F_UTF8) 973 if (flags & F_UTF8)
857 sv_utf8_downgrade (string, 0); 974 sv_utf8_downgrade (string, 0);
858 else 975 else
859 sv_utf8_upgrade (string); 976 sv_utf8_upgrade (string);
860 977
861 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP 978 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
862 979
863 dec_t dec; 980 dec_t dec;
864 dec.flags = flags; 981 dec.flags = flags;
865 dec.cur = SvPVX (string); 982 dec.cur = SvPVX (string);
866 dec.end = SvEND (string); 983 dec.end = SvEND (string);
867 dec.err = 0; 984 dec.err = 0;
985 dec.depth = 0;
986 dec.maxdepth = DEC_DEPTH (dec.flags);
868 987
988 *dec.end = 0; // this should basically be a nop, too, but make sure its there
869 sv = decode_sv (&dec); 989 sv = decode_sv (&dec);
870 990
871 if (!sv) 991 if (!sv)
872 { 992 {
993 IV offset = dec.flags & F_UTF8
994 ? dec.cur - SvPVX (string)
873 IV offset = utf8_distance (dec.cur, SvPVX (string)); 995 : utf8_distance (dec.cur, SvPVX (string));
874 SV *uni = sv_newmortal (); 996 SV *uni = sv_newmortal ();
997
875 // horrible hack to silence warning inside pv_uni_display 998 // horrible hack to silence warning inside pv_uni_display
876 COP cop; 999 COP cop = *PL_curcop;
877 memset (&cop, 0, sizeof (cop));
878 cop.cop_warnings = pWARN_NONE; 1000 cop.cop_warnings = pWARN_NONE;
1001 ENTER;
879 SAVEVPTR (PL_curcop); 1002 SAVEVPTR (PL_curcop);
880 PL_curcop = &cop; 1003 PL_curcop = &cop;
881
882 pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ); 1004 pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ);
1005 LEAVE;
1006
883 croak ("%s, at character offset %d (%s)", 1007 croak ("%s, at character offset %d (%s)",
884 dec.err, 1008 dec.err,
885 (int)offset, 1009 (int)offset,
886 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); 1010 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
887 } 1011 }
888 1012
889 sv = sv_2mortal (sv); 1013 sv = sv_2mortal (sv);
890 1014
891 if (!(dec.flags & F_ALLOW_NONREF) && !SvROK (sv)) 1015 if (!(dec.flags & F_ALLOW_NONREF) && !SvROK (sv))
892 croak ("JSON object or array expected (but number, string, true, false or null found, use allow_nonref to allow this)"); 1016 croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)");
893 1017
894 return sv; 1018 return sv;
895} 1019}
896 1020
1021/////////////////////////////////////////////////////////////////////////////
1022// XS interface functions
1023
897MODULE = JSON::XS PACKAGE = JSON::XS 1024MODULE = JSON::XS PACKAGE = JSON::XS
898 1025
899BOOT: 1026BOOT:
900{ 1027{
901 int i; 1028 int i;
902 1029
903 memset (decode_hexdigit, 0xff, 256); 1030 memset (decode_hexdigit, 0xff, 256);
1031
904 for (i = 10; i--; ) 1032 for (i = 0; i < 256; ++i)
905 decode_hexdigit ['0' + i] = i; 1033 decode_hexdigit [i] =
906 1034 i >= '0' && i <= '9' ? i - '0'
907 for (i = 7; i--; ) 1035 : i >= 'a' && i <= 'f' ? i - 'a' + 10
908 { 1036 : i >= 'A' && i <= 'F' ? i - 'A' + 10
909 decode_hexdigit ['a' + i] = 10 + i; 1037 : -1;
910 decode_hexdigit ['A' + i] = 10 + i;
911 }
912 1038
913 json_stash = gv_stashpv ("JSON::XS", 1); 1039 json_stash = gv_stashpv ("JSON::XS", 1);
914} 1040}
915 1041
916PROTOTYPES: DISABLE 1042PROTOTYPES: DISABLE
927 utf8 = F_UTF8 1053 utf8 = F_UTF8
928 indent = F_INDENT 1054 indent = F_INDENT
929 canonical = F_CANONICAL 1055 canonical = F_CANONICAL
930 space_before = F_SPACE_BEFORE 1056 space_before = F_SPACE_BEFORE
931 space_after = F_SPACE_AFTER 1057 space_after = F_SPACE_AFTER
932 json_rpc = F_JSON_RPC
933 pretty = F_PRETTY 1058 pretty = F_PRETTY
934 allow_nonref = F_ALLOW_NONREF 1059 allow_nonref = F_ALLOW_NONREF
935 shrink = F_SHRINK 1060 shrink = F_SHRINK
936 CODE: 1061 CODE:
937{ 1062{
944 RETVAL = newSVsv (self); 1069 RETVAL = newSVsv (self);
945} 1070}
946 OUTPUT: 1071 OUTPUT:
947 RETVAL 1072 RETVAL
948 1073
1074SV *max_depth (SV *self, int max_depth = 0x80000000UL)
1075 CODE:
1076{
1077 UV *uv = SvJSON (self);
1078 UV log2 = 0;
1079
1080 if (max_depth > 0x80000000UL) max_depth = 0x80000000UL;
1081
1082 while ((1UL << log2) < max_depth)
1083 ++log2;
1084
1085 *uv = *uv & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1086
1087 RETVAL = newSVsv (self);
1088}
1089 OUTPUT:
1090 RETVAL
1091
949void encode (SV *self, SV *scalar) 1092void encode (SV *self, SV *scalar)
950 PPCODE: 1093 PPCODE:
951 XPUSHs (encode_json (scalar, *SvJSON (self))); 1094 XPUSHs (encode_json (scalar, *SvJSON (self)));
952 1095
953void decode (SV *self, SV *jsonstr) 1096void decode (SV *self, SV *jsonstr)
955 XPUSHs (decode_json (jsonstr, *SvJSON (self))); 1098 XPUSHs (decode_json (jsonstr, *SvJSON (self)));
956 1099
957PROTOTYPES: ENABLE 1100PROTOTYPES: ENABLE
958 1101
959void to_json (SV *scalar) 1102void to_json (SV *scalar)
1103 ALIAS:
1104 objToJson = 0
960 PPCODE: 1105 PPCODE:
961 XPUSHs (encode_json (scalar, F_UTF8)); 1106 XPUSHs (encode_json (scalar, F_DEFAULT | F_UTF8));
962 1107
963void from_json (SV *jsonstr) 1108void from_json (SV *jsonstr)
1109 ALIAS:
1110 jsonToObj = 0
964 PPCODE: 1111 PPCODE:
965 XPUSHs (decode_json (jsonstr, F_UTF8)); 1112 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8));
966 1113

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines