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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines