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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines