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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines