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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines