ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/JSON-XS/XS.xs
(Generate patch)

Comparing JSON-XS/XS.xs (file contents):
Revision 1.4 by root, Thu Mar 22 21:13:58 2007 UTC vs.
Revision 1.74 by root, Wed Mar 19 15:17:53 2008 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines