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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines