ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/JSON-XS/XS.xs
Revision: 1.75
Committed: Wed Mar 19 15:37:54 2008 UTC (16 years, 2 months ago) by root
Branch: MAIN
CVS Tags: rel-2_1
Changes since 1.74: +19 -16 lines
Log Message:
*** empty log message ***

File Contents

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