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.12 by root, Sat Mar 24 22:10:08 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
22#define INDENT_STEP 3 // spaces per indentation level 50#define INDENT_STEP 3 // spaces per indentation level
23 51
24#define UTF8_MAX_LEN 11 // for perls UTF-X: max. number of octets per character
25#define SHORT_STRING_LEN 256 // special-case strings of up to this size 52#define SHORT_STRING_LEN 16384 // special-case strings of up to this size
26 53
27#define SB do { 54#define SB do {
28#define SE } while (0) 55#define SE } while (0)
29 56
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
30static HV *json_stash; // JSON::XS:: 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;
31 88
32///////////////////////////////////////////////////////////////////////////// 89/////////////////////////////////////////////////////////////////////////////
33// utility functions 90// utility functions
34 91
35static UV * 92INLINE void
36SvJSON (SV *sv)
37{
38 if (!(SvROK (sv) && SvOBJECT (SvRV (sv)) && SvSTASH (SvRV (sv)) == json_stash))
39 croak ("object is not of type JSON::XS");
40
41 return &SvUVX (SvRV (sv));
42}
43
44static void
45shrink (SV *sv) 93shrink (SV *sv)
46{ 94{
47 sv_utf8_downgrade (sv, 1); 95 sv_utf8_downgrade (sv, 1);
48 if (SvLEN (sv) > SvCUR (sv) + 1) 96 if (SvLEN (sv) > SvCUR (sv) + 1)
49 { 97 {
53 SvPV_renew (sv, SvCUR (sv) + 1); 101 SvPV_renew (sv, SvCUR (sv) + 1);
54#endif 102#endif
55 } 103 }
56} 104}
57 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
58///////////////////////////////////////////////////////////////////////////// 149/////////////////////////////////////////////////////////////////////////////
59// encoder 150// encoder
60 151
61// structure used for encoding JSON 152// structure used for encoding JSON
62typedef struct 153typedef struct
63{ 154{
64 char *cur; // SvPVX (sv) + current output position 155 char *cur; // SvPVX (sv) + current output position
65 char *end; // SvEND (sv) 156 char *end; // SvEND (sv)
66 SV *sv; // result scalar 157 SV *sv; // result scalar
67 UV flags; // F_* 158 JSON json;
68 int indent; // indentation level 159 U32 indent; // indentation level
69 int max_depth; // max. recursion level 160 U32 maxdepth; // max. indentation/recursion level
161 UV limit; // escape character values >= this value when encoding
70} enc_t; 162} enc_t;
71 163
72static void 164INLINE void
73need (enc_t *enc, STRLEN len) 165need (enc_t *enc, STRLEN len)
74{ 166{
75 if (enc->cur + len >= enc->end) 167 if (expect_false (enc->cur + len >= enc->end))
76 { 168 {
77 STRLEN cur = enc->cur - SvPVX (enc->sv); 169 STRLEN cur = enc->cur - SvPVX (enc->sv);
78 SvGROW (enc->sv, cur + len + 1); 170 SvGROW (enc->sv, cur + len + 1);
79 enc->cur = SvPVX (enc->sv) + cur; 171 enc->cur = SvPVX (enc->sv) + cur;
80 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv); 172 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
81 } 173 }
82} 174}
83 175
84static void 176INLINE void
85encode_ch (enc_t *enc, char ch) 177encode_ch (enc_t *enc, char ch)
86{ 178{
87 need (enc, 1); 179 need (enc, 1);
88 *enc->cur++ = ch; 180 *enc->cur++ = ch;
89} 181}
97 189
98 while (str < end) 190 while (str < end)
99 { 191 {
100 unsigned char ch = *(unsigned char *)str; 192 unsigned char ch = *(unsigned char *)str;
101 193
102 if (ch >= 0x20 && ch < 0x80) // most common case 194 if (expect_true (ch >= 0x20 && ch < 0x80)) // most common case
103 { 195 {
104 if (ch == '"') // but with slow exceptions 196 if (expect_false (ch == '"')) // but with slow exceptions
105 { 197 {
106 need (enc, len += 1); 198 need (enc, len += 1);
107 *enc->cur++ = '\\'; 199 *enc->cur++ = '\\';
108 *enc->cur++ = '"'; 200 *enc->cur++ = '"';
109 } 201 }
110 else if (ch == '\\') 202 else if (expect_false (ch == '\\'))
111 { 203 {
112 need (enc, len += 1); 204 need (enc, len += 1);
113 *enc->cur++ = '\\'; 205 *enc->cur++ = '\\';
114 *enc->cur++ = '\\'; 206 *enc->cur++ = '\\';
115 } 207 }
133 STRLEN clen; 225 STRLEN clen;
134 UV uch; 226 UV uch;
135 227
136 if (is_utf8) 228 if (is_utf8)
137 { 229 {
138 uch = utf8n_to_uvuni (str, end - str, &clen, UTF8_CHECK_ONLY); 230 uch = decode_utf8 (str, end - str, &clen);
139 if (clen == (STRLEN)-1) 231 if (clen == (STRLEN)-1)
140 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);
141 } 233 }
142 else 234 else
143 { 235 {
144 uch = ch; 236 uch = ch;
145 clen = 1; 237 clen = 1;
146 } 238 }
147 239
148 if (uch > 0x10FFFFUL) 240 if (uch < 0x80/*0x20*/ || uch >= enc->limit)
149 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
150
151 if (uch < 0x80 || enc->flags & F_ASCII)
152 { 241 {
153 if (uch > 0xFFFFUL) 242 if (uch >= 0x10000UL)
154 { 243 {
244 if (uch >= 0x110000UL)
245 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
246
155 need (enc, len += 11); 247 need (enc, len += 11);
156 sprintf (enc->cur, "\\u%04x\\u%04x", 248 sprintf (enc->cur, "\\u%04x\\u%04x",
157 (int)((uch - 0x10000) / 0x400 + 0xD800), 249 (int)((uch - 0x10000) / 0x400 + 0xD800),
158 (int)((uch - 0x10000) % 0x400 + 0xDC00)); 250 (int)((uch - 0x10000) % 0x400 + 0xDC00));
159 enc->cur += 12; 251 enc->cur += 12;
170 *enc->cur++ = hexdigit [(uch >> 0) & 15]; 262 *enc->cur++ = hexdigit [(uch >> 0) & 15];
171 } 263 }
172 264
173 str += clen; 265 str += clen;
174 } 266 }
267 else if (enc->json.flags & F_LATIN1)
268 {
269 *enc->cur++ = uch;
270 str += clen;
271 }
175 else if (is_utf8) 272 else if (is_utf8)
176 { 273 {
177 need (enc, len += clen); 274 need (enc, len += clen);
178 do 275 do
179 { 276 {
181 } 278 }
182 while (--clen); 279 while (--clen);
183 } 280 }
184 else 281 else
185 { 282 {
186 need (enc, len += UTF8_MAX_LEN - 1); // never more than 11 bytes needed 283 need (enc, len += UTF8_MAXBYTES - 1); // never more than 11 bytes needed
187 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0); 284 enc->cur = encode_utf8 (enc->cur, uch);
188 ++str; 285 ++str;
189 } 286 }
190 } 287 }
191 } 288 }
192 } 289 }
193 290
194 --len; 291 --len;
195 } 292 }
196} 293}
197 294
198static void 295INLINE void
199encode_indent (enc_t *enc) 296encode_indent (enc_t *enc)
200{ 297{
201 if (enc->flags & F_INDENT) 298 if (enc->json.flags & F_INDENT)
202 { 299 {
203 int spaces = enc->indent * INDENT_STEP; 300 int spaces = enc->indent * INDENT_STEP;
204 301
205 need (enc, spaces); 302 need (enc, spaces);
206 memset (enc->cur, ' ', spaces); 303 memset (enc->cur, ' ', spaces);
207 enc->cur += spaces; 304 enc->cur += spaces;
208 } 305 }
209} 306}
210 307
211static void 308INLINE void
212encode_space (enc_t *enc) 309encode_space (enc_t *enc)
213{ 310{
214 need (enc, 1); 311 need (enc, 1);
215 encode_ch (enc, ' '); 312 encode_ch (enc, ' ');
216} 313}
217 314
218static void 315INLINE void
219encode_nl (enc_t *enc) 316encode_nl (enc_t *enc)
220{ 317{
221 if (enc->flags & F_INDENT) 318 if (enc->json.flags & F_INDENT)
222 { 319 {
223 need (enc, 1); 320 need (enc, 1);
224 encode_ch (enc, '\n'); 321 encode_ch (enc, '\n');
225 } 322 }
226} 323}
227 324
228static void 325INLINE void
229encode_comma (enc_t *enc) 326encode_comma (enc_t *enc)
230{ 327{
231 encode_ch (enc, ','); 328 encode_ch (enc, ',');
232 329
233 if (enc->flags & F_INDENT) 330 if (enc->json.flags & F_INDENT)
234 encode_nl (enc); 331 encode_nl (enc);
235 else if (enc->flags & F_SPACE_AFTER) 332 else if (enc->json.flags & F_SPACE_AFTER)
236 encode_space (enc); 333 encode_space (enc);
237} 334}
238 335
239static void encode_sv (enc_t *enc, SV *sv); 336static void encode_sv (enc_t *enc, SV *sv);
240 337
241static void 338static void
242encode_av (enc_t *enc, AV *av) 339encode_av (enc_t *enc, AV *av)
243{ 340{
244 int i, len = av_len (av); 341 int i, len = av_len (av);
245 342
246 encode_ch (enc, '['); encode_nl (enc); 343 if (enc->indent >= enc->maxdepth)
247 ++enc->indent; 344 croak ("data structure too deep (hit recursion limit)");
248 345
346 encode_ch (enc, '[');
347
348 if (len >= 0)
349 {
350 encode_nl (enc); ++enc->indent;
351
249 for (i = 0; i <= len; ++i) 352 for (i = 0; i <= len; ++i)
250 { 353 {
354 SV **svp = av_fetch (av, i, 0);
355
251 encode_indent (enc); 356 encode_indent (enc);
252 encode_sv (enc, *av_fetch (av, i, 0));
253 357
358 if (svp)
359 encode_sv (enc, *svp);
360 else
361 encode_str (enc, "null", 4, 0);
362
254 if (i < len) 363 if (i < len)
255 encode_comma (enc); 364 encode_comma (enc);
256 } 365 }
257 366
367 encode_nl (enc); --enc->indent; encode_indent (enc);
368 }
369
258 encode_nl (enc); 370 encode_ch (enc, ']');
259
260 --enc->indent;
261 encode_indent (enc); encode_ch (enc, ']');
262} 371}
263 372
264static void 373static void
265encode_he (enc_t *enc, HE *he) 374encode_hk (enc_t *enc, HE *he)
266{ 375{
267 encode_ch (enc, '"'); 376 encode_ch (enc, '"');
268 377
269 if (HeKLEN (he) == HEf_SVKEY) 378 if (HeKLEN (he) == HEf_SVKEY)
270 { 379 {
280 else 389 else
281 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he)); 390 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he));
282 391
283 encode_ch (enc, '"'); 392 encode_ch (enc, '"');
284 393
285 if (enc->flags & F_SPACE_BEFORE) encode_space (enc); 394 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc);
286 encode_ch (enc, ':'); 395 encode_ch (enc, ':');
287 if (enc->flags & F_SPACE_AFTER ) encode_space (enc); 396 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc);
288 encode_sv (enc, HeVAL (he));
289} 397}
290 398
291// compare hash entries, used when all keys are bytestrings 399// compare hash entries, used when all keys are bytestrings
292static int 400static int
293he_cmp_fast (const void *a_, const void *b_) 401he_cmp_fast (const void *a_, const void *b_)
298 HE *b = *(HE **)b_; 406 HE *b = *(HE **)b_;
299 407
300 STRLEN la = HeKLEN (a); 408 STRLEN la = HeKLEN (a);
301 STRLEN lb = HeKLEN (b); 409 STRLEN lb = HeKLEN (b);
302 410
303 if (!(cmp = memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb))) 411 if (!(cmp = memcmp (HeKEY (b), HeKEY (a), lb < la ? lb : la)))
304 cmp = la - lb; 412 cmp = lb - la;
305 413
306 return cmp; 414 return cmp;
307} 415}
308 416
309// 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
310static int 418static int
311he_cmp_slow (const void *a, const void *b) 419he_cmp_slow (const void *a, const void *b)
312{ 420{
313 return sv_cmp (HeSVKEY_force (*(HE **)a), HeSVKEY_force (*(HE **)b)); 421 return sv_cmp (HeSVKEY_force (*(HE **)b), HeSVKEY_force (*(HE **)a));
314} 422}
315 423
316static void 424static void
317encode_hv (enc_t *enc, HV *hv) 425encode_hv (enc_t *enc, HV *hv)
318{ 426{
427 HE *he;
319 int count, i; 428 int count;
320 429
321 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent; 430 if (enc->indent >= enc->maxdepth)
431 croak ("data structure too deep (hit recursion limit)");
322 432
323 if ((count = hv_iterinit (hv))) 433 encode_ch (enc, '{');
324 { 434
325 // for canonical output we have to sort by keys first 435 // for canonical output we have to sort by keys first
326 // actually, this is mostly due to the stupid so-called 436 // actually, this is mostly due to the stupid so-called
327 // security workaround added somewhere in 5.8.x. 437 // security workaround added somewhere in 5.8.x.
328 // that randomises hash orderings 438 // that randomises hash orderings
329 if (enc->flags & F_CANONICAL) 439 if (enc->json.flags & F_CANONICAL)
440 {
441 int count = hv_iterinit (hv);
442
443 if (SvMAGICAL (hv))
330 { 444 {
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 {
459 int i, fast = 1;
460#if defined(__BORLANDC__) || defined(_MSC_VER)
461 HE **hes = _alloca (count * sizeof (HE));
462#else
331 HE *he, *hes [count]; // if your compiler dies here, you need to enable C99 mode 463 HE *hes [count]; // if your compiler dies here, you need to enable C99 mode
332 int fast = 1; 464#endif
333 465
334 i = 0; 466 i = 0;
335 while ((he = hv_iternext (hv))) 467 while ((he = hv_iternext (hv)))
336 { 468 {
337 hes [i++] = he; 469 hes [i++] = he;
359 491
360 FREETMPS; 492 FREETMPS;
361 LEAVE; 493 LEAVE;
362 } 494 }
363 495
364 for (i = 0; i < count; ++i) 496 encode_nl (enc); ++enc->indent;
497
498 while (count--)
365 { 499 {
366 encode_indent (enc); 500 encode_indent (enc);
501 he = hes [count];
367 encode_he (enc, hes [i]); 502 encode_hk (enc, he);
503 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
368 504
369 if (i < count - 1) 505 if (count)
370 encode_comma (enc); 506 encode_comma (enc);
371 } 507 }
372 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)))
516 {
517 encode_nl (enc); ++enc->indent;
518
519 for (;;)
520 {
373 encode_nl (enc); 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);
374 } 559 }
375 else 560 else
376 { 561 {
377 SV *sv; 562#if 0
378 HE *he = hv_iternext (hv); 563 if (0 && sv_derived_from (rv, "JSON::Literal"))
379
380 for (;;)
381 { 564 {
382 encode_indent (enc); 565 // not yet
383 encode_he (enc, he);
384
385 if (!(he = hv_iternext (hv)))
386 break;
387
388 encode_comma (enc);
389 } 566 }
567#endif
568 if (enc->json.flags & F_CONV_BLESSED)
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);
390 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
391 encode_nl (enc); 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))));
392 } 607 }
393 } 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;
394 617
395 --enc->indent; encode_indent (enc); 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))));
396} 629}
397 630
398static void 631static void
399encode_sv (enc_t *enc, SV *sv) 632encode_sv (enc_t *enc, SV *sv)
400{ 633{
408 encode_str (enc, str, len, SvUTF8 (sv)); 641 encode_str (enc, str, len, SvUTF8 (sv));
409 encode_ch (enc, '"'); 642 encode_ch (enc, '"');
410 } 643 }
411 else if (SvNOKp (sv)) 644 else if (SvNOKp (sv))
412 { 645 {
646 // trust that perl will do the right thing w.r.t. JSON syntax.
413 need (enc, NV_DIG + 32); 647 need (enc, NV_DIG + 32);
414 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur); 648 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
415 enc->cur += strlen (enc->cur); 649 enc->cur += strlen (enc->cur);
416 } 650 }
417 else if (SvIOKp (sv)) 651 else if (SvIOKp (sv))
418 { 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
419 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);
420 enc->cur += 689 enc->cur +=
421 SvIsUV(sv) 690 SvIsUV(sv)
422 ? snprintf (enc->cur, 64, "%"UVuf, (UV)SvUVX (sv)) 691 ? snprintf (enc->cur, IVUV_MAXCHARS, "%"UVuf, (UV)SvUVX (sv))
423 : snprintf (enc->cur, 64, "%"IVdf, (IV)SvIVX (sv)); 692 : snprintf (enc->cur, IVUV_MAXCHARS, "%"IVdf, (IV)SvIVX (sv));
693 }
424 } 694 }
425 else if (SvROK (sv)) 695 else if (SvROK (sv))
426 { 696 encode_rv (enc, SvRV (sv));
427 SV *rv = SvRV (sv);
428
429 if (enc->indent >= enc->max_depth)
430 croak ("data structure too deep (hit recursion limit)");
431
432 switch (SvTYPE (rv))
433 {
434 case SVt_PVAV: encode_av (enc, (AV *)rv); break;
435 case SVt_PVHV: encode_hv (enc, (HV *)rv); break;
436
437 default:
438 croak ("encountered %s, but JSON can only represent references to arrays or hashes",
439 SvPV_nolen (sv));
440 }
441 }
442 else if (!SvOK (sv)) 697 else if (!SvOK (sv))
443 encode_str (enc, "null", 4, 0); 698 encode_str (enc, "null", 4, 0);
444 else 699 else
445 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",
446 SvPV_nolen (sv), SvFLAGS (sv)); 701 SvPV_nolen (sv), SvFLAGS (sv));
447} 702}
448 703
449static SV * 704static SV *
450encode_json (SV *scalar, UV flags) 705encode_json (SV *scalar, JSON *json)
451{ 706{
707 enc_t enc;
708
452 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar)) 709 if (!(json->flags & F_ALLOW_NONREF) && !SvROK (scalar))
453 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)");
454 711
455 enc_t enc; 712 enc.json = *json;
456 enc.flags = flags;
457 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 713 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
458 enc.cur = SvPVX (enc.sv); 714 enc.cur = SvPVX (enc.sv);
459 enc.end = SvEND (enc.sv); 715 enc.end = SvEND (enc.sv);
460 enc.indent = 0; 716 enc.indent = 0;
461 enc.max_depth = 0x7fffffffUL; 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;
462 721
463 SvPOK_only (enc.sv); 722 SvPOK_only (enc.sv);
464 encode_sv (&enc, scalar); 723 encode_sv (&enc, scalar);
465 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
466 if (!(flags & (F_ASCII | F_UTF8))) 728 if (!(enc.json.flags & (F_ASCII | F_LATIN1 | F_UTF8)))
467 SvUTF8_on (enc.sv); 729 SvUTF8_on (enc.sv);
468 730
469 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
470
471 if (enc.flags & F_SHRINK) 731 if (enc.json.flags & F_SHRINK)
472 shrink (enc.sv); 732 shrink (enc.sv);
473 733
474 return enc.sv; 734 return enc.sv;
475} 735}
476 736
481typedef struct 741typedef struct
482{ 742{
483 char *cur; // current parser pointer 743 char *cur; // current parser pointer
484 char *end; // end of input string 744 char *end; // end of input string
485 const char *err; // parse error, if != 0 745 const char *err; // parse error, if != 0
486 UV flags; // F_* 746 JSON json;
747 U32 depth; // recursion depth
748 U32 maxdepth; // recursion depth limit
487} dec_t; 749} dec_t;
488 750
489static void 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
490decode_ws (dec_t *dec) 761decode_ws (dec_t *dec)
491{ 762{
492 for (;;) 763 for (;;)
493 { 764 {
494 char ch = *dec->cur; 765 char ch = *dec->cur;
495 766
496 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 }
497 || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)) 779 else if (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)
498 break; 780 break; // parse error, but let higher level handle it, gives better error messages
499 781
500 ++dec->cur; 782 ++dec->cur;
501 } 783 }
502} 784}
503 785
504#define ERR(reason) SB dec->err = reason; goto fail; SE 786#define ERR(reason) SB dec->err = reason; goto fail; SE
787
505#define EXPECT_CH(ch) SB \ 788#define EXPECT_CH(ch) SB \
506 if (*dec->cur != ch) \ 789 if (*dec->cur != ch) \
507 ERR (# ch " expected"); \ 790 ERR (# ch " expected"); \
508 ++dec->cur; \ 791 ++dec->cur; \
509 SE 792 SE
510 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
511static SV *decode_sv (dec_t *dec); 797static SV *decode_sv (dec_t *dec);
512 798
513static signed char decode_hexdigit[256]; 799static signed char decode_hexdigit[256];
514 800
515static UV 801static UV
516decode_4hex (dec_t *dec) 802decode_4hex (dec_t *dec)
517{ 803{
518 signed char d1, d2, d3, d4; 804 signed char d1, d2, d3, d4;
519 unsigned char *cur = (unsigned char *)dec->cur; 805 unsigned char *cur = (unsigned char *)dec->cur;
520 806
521 d1 = decode_hexdigit [cur [0]]; if (d1 < 0) ERR ("four hexadecimal digits expected"); 807 d1 = decode_hexdigit [cur [0]]; if (expect_false (d1 < 0)) ERR ("exactly four hexadecimal digits expected");
522 d2 = decode_hexdigit [cur [1]]; if (d2 < 0) ERR ("four hexadecimal digits expected"); 808 d2 = decode_hexdigit [cur [1]]; if (expect_false (d2 < 0)) ERR ("exactly four hexadecimal digits expected");
523 d3 = decode_hexdigit [cur [2]]; if (d3 < 0) ERR ("four hexadecimal digits expected"); 809 d3 = decode_hexdigit [cur [2]]; if (expect_false (d3 < 0)) ERR ("exactly four hexadecimal digits expected");
524 d4 = decode_hexdigit [cur [3]]; if (d4 < 0) ERR ("four hexadecimal digits expected"); 810 d4 = decode_hexdigit [cur [3]]; if (expect_false (d4 < 0)) ERR ("exactly four hexadecimal digits expected");
525 811
526 dec->cur += 4; 812 dec->cur += 4;
527 813
528 return ((UV)d1) << 12 814 return ((UV)d1) << 12
529 | ((UV)d2) << 8 815 | ((UV)d2) << 8
537static SV * 823static SV *
538decode_str (dec_t *dec) 824decode_str (dec_t *dec)
539{ 825{
540 SV *sv = 0; 826 SV *sv = 0;
541 int utf8 = 0; 827 int utf8 = 0;
828 char *dec_cur = dec->cur;
542 829
543 do 830 do
544 { 831 {
545 char buf [SHORT_STRING_LEN + UTF8_MAX_LEN]; 832 char buf [SHORT_STRING_LEN + UTF8_MAXBYTES];
546 char *cur = buf; 833 char *cur = buf;
547 834
548 do 835 do
549 { 836 {
550 unsigned char ch = *(unsigned char *)dec->cur++; 837 unsigned char ch = *(unsigned char *)dec_cur++;
551 838
552 if (ch == '"') 839 if (expect_false (ch == '"'))
553 { 840 {
554 --dec->cur; 841 --dec_cur;
555 break; 842 break;
556 } 843 }
557 else if (ch == '\\') 844 else if (expect_false (ch == '\\'))
558 { 845 {
559 switch (*dec->cur) 846 switch (*dec_cur)
560 { 847 {
561 case '\\': 848 case '\\':
562 case '/': 849 case '/':
563 case '"': *cur++ = *dec->cur++; break; 850 case '"': *cur++ = *dec_cur++; break;
564 851
565 case 'b': ++dec->cur; *cur++ = '\010'; break; 852 case 'b': ++dec_cur; *cur++ = '\010'; break;
566 case 't': ++dec->cur; *cur++ = '\011'; break; 853 case 't': ++dec_cur; *cur++ = '\011'; break;
567 case 'n': ++dec->cur; *cur++ = '\012'; break; 854 case 'n': ++dec_cur; *cur++ = '\012'; break;
568 case 'f': ++dec->cur; *cur++ = '\014'; break; 855 case 'f': ++dec_cur; *cur++ = '\014'; break;
569 case 'r': ++dec->cur; *cur++ = '\015'; break; 856 case 'r': ++dec_cur; *cur++ = '\015'; break;
570 857
571 case 'u': 858 case 'u':
572 { 859 {
573 UV lo, hi; 860 UV lo, hi;
574 ++dec->cur; 861 ++dec_cur;
575 862
863 dec->cur = dec_cur;
576 hi = decode_4hex (dec); 864 hi = decode_4hex (dec);
865 dec_cur = dec->cur;
577 if (hi == (UV)-1) 866 if (hi == (UV)-1)
578 goto fail; 867 goto fail;
579 868
580 // possibly a surrogate pair 869 // possibly a surrogate pair
581 if (hi >= 0xd800) 870 if (hi >= 0xd800)
582 if (hi < 0xdc00) 871 if (hi < 0xdc00)
583 { 872 {
584 if (dec->cur [0] != '\\' || dec->cur [1] != 'u') 873 if (dec_cur [0] != '\\' || dec_cur [1] != 'u')
585 ERR ("missing low surrogate character in surrogate pair"); 874 ERR ("missing low surrogate character in surrogate pair");
586 875
587 dec->cur += 2; 876 dec_cur += 2;
588 877
878 dec->cur = dec_cur;
589 lo = decode_4hex (dec); 879 lo = decode_4hex (dec);
880 dec_cur = dec->cur;
590 if (lo == (UV)-1) 881 if (lo == (UV)-1)
591 goto fail; 882 goto fail;
592 883
593 if (lo < 0xdc00 || lo >= 0xe000) 884 if (lo < 0xdc00 || lo >= 0xe000)
594 ERR ("surrogate pair expected"); 885 ERR ("surrogate pair expected");
600 891
601 if (hi >= 0x80) 892 if (hi >= 0x80)
602 { 893 {
603 utf8 = 1; 894 utf8 = 1;
604 895
605 cur = (char *)uvuni_to_utf8_flags (cur, hi, 0); 896 cur = encode_utf8 (cur, hi);
606 } 897 }
607 else 898 else
608 *cur++ = hi; 899 *cur++ = hi;
609 } 900 }
610 break; 901 break;
611 902
612 default: 903 default:
613 --dec->cur; 904 --dec_cur;
614 ERR ("illegal backslash escape sequence in string"); 905 ERR ("illegal backslash escape sequence in string");
615 } 906 }
616 } 907 }
617 else if (ch >= 0x20 && ch <= 0x7f) 908 else if (expect_true (ch >= 0x20 && ch < 0x80))
618 *cur++ = ch; 909 *cur++ = ch;
619 else if (ch >= 0x80) 910 else if (ch >= 0x80)
620 { 911 {
621 --dec->cur;
622
623 STRLEN clen; 912 STRLEN clen;
624 UV uch = utf8n_to_uvuni (dec->cur, dec->end - dec->cur, &clen, UTF8_CHECK_ONLY); 913 UV uch;
914
915 --dec_cur;
916
917 uch = decode_utf8 (dec_cur, dec->end - dec_cur, &clen);
625 if (clen == (STRLEN)-1) 918 if (clen == (STRLEN)-1)
626 ERR ("malformed UTF-8 character in JSON string"); 919 ERR ("malformed UTF-8 character in JSON string");
627 920
628 do 921 do
629 {
630 *cur++ = *dec->cur++; 922 *cur++ = *dec_cur++;
631 }
632 while (--clen); 923 while (--clen);
633 924
634 utf8 = 1; 925 utf8 = 1;
635 } 926 }
636 else if (!ch)
637 ERR ("unexpected end of string while parsing json string");
638 else 927 else
928 {
929 --dec_cur;
930
931 if (!ch)
932 ERR ("unexpected end of string while parsing JSON string");
933 else
639 ERR ("invalid character encountered"); 934 ERR ("invalid character encountered while parsing JSON string");
640 935 }
641 } 936 }
642 while (cur < buf + SHORT_STRING_LEN); 937 while (cur < buf + SHORT_STRING_LEN);
643 938
939 {
644 STRLEN len = cur - buf; 940 STRLEN len = cur - buf;
645 941
646 if (sv) 942 if (sv)
647 { 943 {
648 SvGROW (sv, SvCUR (sv) + len + 1); 944 SvGROW (sv, SvCUR (sv) + len + 1);
649 memcpy (SvPVX (sv) + SvCUR (sv), buf, len); 945 memcpy (SvPVX (sv) + SvCUR (sv), buf, len);
650 SvCUR_set (sv, SvCUR (sv) + len); 946 SvCUR_set (sv, SvCUR (sv) + len);
651 } 947 }
652 else 948 else
653 sv = newSVpvn (buf, len); 949 sv = newSVpvn (buf, len);
654 } 950 }
951 }
655 while (*dec->cur != '"'); 952 while (*dec_cur != '"');
656 953
657 ++dec->cur; 954 ++dec_cur;
658 955
659 if (sv) 956 if (sv)
660 { 957 {
661 SvPOK_only (sv); 958 SvPOK_only (sv);
662 *SvEND (sv) = 0; 959 *SvEND (sv) = 0;
665 SvUTF8_on (sv); 962 SvUTF8_on (sv);
666 } 963 }
667 else 964 else
668 sv = newSVpvn ("", 0); 965 sv = newSVpvn ("", 0);
669 966
967 dec->cur = dec_cur;
670 return sv; 968 return sv;
671 969
672fail: 970fail:
971 dec->cur = dec_cur;
673 return 0; 972 return 0;
674} 973}
675 974
676static SV * 975static SV *
677decode_num (dec_t *dec) 976decode_num (dec_t *dec)
735 is_nv = 1; 1034 is_nv = 1;
736 } 1035 }
737 1036
738 if (!is_nv) 1037 if (!is_nv)
739 { 1038 {
740 UV uv; 1039 int len = dec->cur - start;
741 int numtype = grok_number (start, dec->cur - start, &uv); 1040
742 if (numtype & IS_NUMBER_IN_UV) 1041 // special case the rather common 1..5-digit-int case
743 if (numtype & IS_NUMBER_NEG) 1042 if (*start == '-')
1043 switch (len)
744 { 1044 {
745 if (uv < (UV)IV_MIN) 1045 case 2: return newSViv (-( start [1] - '0' * 1));
746 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));
747 } 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 }
748 else 1070 else
749 return newSVuv (uv); 1071 return newSVuv (uv);
750 } 1072 }
751 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
752 return newSVnv (Atof (start)); 1090 return newSVnv (Atof (start));
753 1091
754fail: 1092fail:
755 return 0; 1093 return 0;
756} 1094}
758static SV * 1096static SV *
759decode_av (dec_t *dec) 1097decode_av (dec_t *dec)
760{ 1098{
761 AV *av = newAV (); 1099 AV *av = newAV ();
762 1100
1101 DEC_INC_DEPTH;
763 decode_ws (dec); 1102 decode_ws (dec);
1103
764 if (*dec->cur == ']') 1104 if (*dec->cur == ']')
765 ++dec->cur; 1105 ++dec->cur;
766 else 1106 else
767 for (;;) 1107 for (;;)
768 { 1108 {
784 1124
785 if (*dec->cur != ',') 1125 if (*dec->cur != ',')
786 ERR (", or ] expected while parsing array"); 1126 ERR (", or ] expected while parsing array");
787 1127
788 ++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 }
789 } 1137 }
790 1138
1139 DEC_DEC_DEPTH;
791 return newRV_noinc ((SV *)av); 1140 return newRV_noinc ((SV *)av);
792 1141
793fail: 1142fail:
794 SvREFCNT_dec (av); 1143 SvREFCNT_dec (av);
1144 DEC_DEC_DEPTH;
795 return 0; 1145 return 0;
796} 1146}
797 1147
798static SV * 1148static SV *
799decode_hv (dec_t *dec) 1149decode_hv (dec_t *dec)
800{ 1150{
1151 SV *sv;
801 HV *hv = newHV (); 1152 HV *hv = newHV ();
802 1153
1154 DEC_INC_DEPTH;
803 decode_ws (dec); 1155 decode_ws (dec);
1156
804 if (*dec->cur == '}') 1157 if (*dec->cur == '}')
805 ++dec->cur; 1158 ++dec->cur;
806 else 1159 else
807 for (;;) 1160 for (;;)
808 { 1161 {
1162 EXPECT_CH ('"');
1163
1164 // heuristic: assume that
1165 // a) decode_str + hv_store_ent are abysmally slow.
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 {
809 SV *key, *value; 1170 SV *value;
1171 char *p = dec->cur;
1172 char *e = p + 24; // only try up to 24 bytes
810 1173
811 decode_ws (dec); EXPECT_CH ('"'); 1174 for (;;)
812
813 key = decode_str (dec);
814 if (!key)
815 goto fail;
816
817 decode_ws (dec); EXPECT_CH (':');
818
819 value = decode_sv (dec);
820 if (!value)
821 { 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);
822 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)
823 goto fail; 1211 goto fail;
1212
1213 hv_store (hv, key, len, value, 0);
1214
1215 break;
1216 }
1217
1218 ++p;
824 } 1219 }
825 1220 }
826 //TODO: optimise
827 hv_store_ent (hv, key, value, 0);
828 1221
829 decode_ws (dec); 1222 decode_ws (dec);
830 1223
831 if (*dec->cur == '}') 1224 if (*dec->cur == '}')
832 { 1225 {
836 1229
837 if (*dec->cur != ',') 1230 if (*dec->cur != ',')
838 ERR (", or } expected while parsing object/hash"); 1231 ERR (", or } expected while parsing object/hash");
839 1232
840 ++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 }
841 } 1242 }
842 1243
1244 DEC_DEC_DEPTH;
843 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;
844 1306
845fail: 1307fail:
846 SvREFCNT_dec (hv); 1308 SvREFCNT_dec (hv);
1309 DEC_DEC_DEPTH;
847 return 0; 1310 return 0;
848} 1311}
849 1312
850static SV * 1313static SV *
851decode_sv (dec_t *dec) 1314decode_sv (dec_t *dec)
852{ 1315{
853 decode_ws (dec); 1316 // the beauty of JSON: you need exactly one character lookahead
1317 // to parse everything.
854 switch (*dec->cur) 1318 switch (*dec->cur)
855 { 1319 {
856 case '"': ++dec->cur; return decode_str (dec); 1320 case '"': ++dec->cur; return decode_str (dec);
857 case '[': ++dec->cur; return decode_av (dec); 1321 case '[': ++dec->cur; return decode_av (dec);
858 case '{': ++dec->cur; return decode_hv (dec); 1322 case '{': ++dec->cur; return decode_hv (dec);
859 1323
860 case '-': 1324 case '-':
861 case '0': case '1': case '2': case '3': case '4': 1325 case '0': case '1': case '2': case '3': case '4':
862 case '5': case '6': case '7': case '8': case '9': 1326 case '5': case '6': case '7': case '8': case '9':
863 return decode_num (dec); 1327 return decode_num (dec);
864 1328
865 case 't': 1329 case 't':
866 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1330 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
867 { 1331 {
868 dec->cur += 4; 1332 dec->cur += 4;
869 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);
870 } 1337 }
871 else 1338 else
872 ERR ("'true' expected"); 1339 ERR ("'true' expected");
873 1340
874 break; 1341 break;
875 1342
876 case 'f': 1343 case 'f':
877 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1344 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
878 { 1345 {
879 dec->cur += 5; 1346 dec->cur += 5;
880 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);
881 } 1351 }
882 else 1352 else
883 ERR ("'false' expected"); 1353 ERR ("'false' expected");
884 1354
885 break; 1355 break;
894 ERR ("'null' expected"); 1364 ERR ("'null' expected");
895 1365
896 break; 1366 break;
897 1367
898 default: 1368 default:
899 ERR ("malformed json string, neither array, object, number, string or atom"); 1369 ERR ("malformed JSON string, neither array, object, number, string or atom");
900 break; 1370 break;
901 } 1371 }
902 1372
903fail: 1373fail:
904 return 0; 1374 return 0;
905} 1375}
906 1376
907static SV * 1377static SV *
908decode_json (SV *string, UV flags) 1378decode_json (SV *string, JSON *json, UV *offset_return)
909{ 1379{
1380 dec_t dec;
1381 UV offset;
910 SV *sv; 1382 SV *sv;
911 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
912 if (flags & F_UTF8) 1391 if (json->flags & F_UTF8)
913 sv_utf8_downgrade (string, 0); 1392 sv_utf8_downgrade (string, 0);
914 else 1393 else
915 sv_utf8_upgrade (string); 1394 sv_utf8_upgrade (string);
916 1395
917 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP 1396 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
918 1397
919 dec_t dec; 1398 dec.json = *json;
920 dec.flags = flags;
921 dec.cur = SvPVX (string); 1399 dec.cur = SvPVX (string);
922 dec.end = SvEND (string); 1400 dec.end = SvEND (string);
923 dec.err = 0; 1401 dec.err = 0;
1402 dec.depth = 0;
1403 dec.maxdepth = DEC_DEPTH (dec.json.flags);
924 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);
925 sv = decode_sv (&dec); 1411 sv = decode_sv (&dec);
926 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
927 if (!sv) 1436 if (!sv)
928 { 1437 {
929 IV offset = dec.flags & F_UTF8
930 ? dec.cur - SvPVX (string)
931 : utf8_distance (dec.cur, SvPVX (string));
932 SV *uni = sv_newmortal (); 1438 SV *uni = sv_newmortal ();
933 1439
934 // horrible hack to silence warning inside pv_uni_display 1440 // horrible hack to silence warning inside pv_uni_display
935 COP cop = *PL_curcop; 1441 COP cop = *PL_curcop;
936 cop.cop_warnings = pWARN_NONE; 1442 cop.cop_warnings = pWARN_NONE;
938 SAVEVPTR (PL_curcop); 1444 SAVEVPTR (PL_curcop);
939 PL_curcop = &cop; 1445 PL_curcop = &cop;
940 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);
941 LEAVE; 1447 LEAVE;
942 1448
943 croak ("%s, at character offset %d (%s)", 1449 croak ("%s, at character offset %d [\"%s\"]",
944 dec.err, 1450 dec.err,
945 (int)offset, 1451 (int)offset,
946 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); 1452 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
947 } 1453 }
948 1454
949 sv = sv_2mortal (sv); 1455 sv = sv_2mortal (sv);
950 1456
951 if (!(dec.flags & F_ALLOW_NONREF) && !SvROK (sv)) 1457 if (!(dec.json.flags & F_ALLOW_NONREF) && !SvROK (sv))
952 croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)"); 1458 croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)");
953 1459
954 return sv; 1460 return sv;
955} 1461}
956 1462
961 1467
962BOOT: 1468BOOT:
963{ 1469{
964 int i; 1470 int i;
965 1471
966 memset (decode_hexdigit, 0xff, 256);
967 for (i = 10; i--; ) 1472 for (i = 0; i < 256; ++i)
968 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;
969 1478
970 for (i = 7; i--; )
971 {
972 decode_hexdigit ['a' + i] = 10 + i;
973 decode_hexdigit ['A' + i] = 10 + i;
974 }
975
976 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);
977} 1484}
978 1485
979PROTOTYPES: DISABLE 1486PROTOTYPES: DISABLE
980 1487
981SV *new (char *dummy) 1488void CLONE (...)
982 CODE: 1489 CODE:
983 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);
984 OUTPUT: 1566 OUTPUT:
985 RETVAL 1567 RETVAL
986 1568
987SV *ascii (SV *self, int enable = 1) 1569void max_size (JSON *self, UV max_size = 0)
988 ALIAS: 1570 PPCODE:
989 ascii = F_ASCII 1571{
990 utf8 = F_UTF8 1572 UV log2 = 0;
991 indent = F_INDENT 1573
992 canonical = F_CANONICAL 1574 if (max_size > 0x80000000UL) max_size = 0x80000000UL;
993 space_before = F_SPACE_BEFORE 1575 if (max_size == 1) max_size = 2;
994 space_after = F_SPACE_AFTER 1576
995 pretty = F_PRETTY 1577 while ((1UL << log2) < max_size)
996 allow_nonref = F_ALLOW_NONREF 1578 ++log2;
997 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)
998 CODE: 1586 CODE:
999{ 1587 RETVAL = DEC_SIZE (self->flags);
1000 UV *uv = SvJSON (self);
1001 if (enable)
1002 *uv |= ix;
1003 else
1004 *uv &= ~ix;
1005
1006 RETVAL = newSVsv (self);
1007}
1008 OUTPUT: 1588 OUTPUT:
1009 RETVAL 1589 RETVAL
1010 1590
1011void encode (SV *self, SV *scalar) 1591void filter_json_object (JSON *self, SV *cb = &PL_sv_undef)
1012 PPCODE: 1592 PPCODE:
1013 XPUSHs (encode_json (scalar, *SvJSON (self))); 1593{
1594 SvREFCNT_dec (self->cb_object);
1595 self->cb_object = SvOK (cb) ? newSVsv (cb) : 0;
1014 1596
1015void 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)
1016 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:
1017 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);
1018 1643
1019PROTOTYPES: ENABLE 1644PROTOTYPES: ENABLE
1020 1645
1021void to_json (SV *scalar) 1646void encode_json (SV *scalar)
1022 PPCODE: 1647 PPCODE:
1648{
1649 JSON json = { F_DEFAULT | F_UTF8 };
1023 XPUSHs (encode_json (scalar, F_UTF8)); 1650 XPUSHs (encode_json (scalar, &json));
1651}
1024 1652
1025void from_json (SV *jsonstr) 1653void decode_json (SV *jsonstr)
1026 PPCODE: 1654 PPCODE:
1655{
1656 JSON json = { F_DEFAULT | F_UTF8 };
1027 XPUSHs (decode_json (jsonstr, F_UTF8)); 1657 XPUSHs (decode_json (jsonstr, &json, 0));
1658}
1028 1659

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines