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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines