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.16 by root, Sun Mar 25 02:37:00 2007 UTC vs.
Revision 1.71 by root, Wed Mar 19 03:17:38 2008 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines