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.4 by root, Thu Mar 22 21:13:58 2007 UTC vs.
Revision 1.14 by root, Sat Mar 24 22:55:43 2007 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines