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.19 by root, Sun Mar 25 21:52:47 2007 UTC vs.
Revision 1.73 by root, Wed Mar 19 13:44:43 2008 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines