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.108 by root, Tue Aug 17 23:27:36 2010 UTC vs.
Revision 1.130 by root, Sat Nov 26 06:09:29 2016 UTC

6#include <string.h> 6#include <string.h>
7#include <stdlib.h> 7#include <stdlib.h>
8#include <stdio.h> 8#include <stdio.h>
9#include <limits.h> 9#include <limits.h>
10#include <float.h> 10#include <float.h>
11#include <inttypes.h>
11 12
12#if defined(__BORLANDC__) || defined(_MSC_VER) 13#if defined(__BORLANDC__) || defined(_MSC_VER)
13# define snprintf _snprintf // C compilers have this in stdio.h 14# define snprintf _snprintf // C compilers have this in stdio.h
14#endif 15#endif
15 16
16// some old perls do not have this, try to make it work, no 17// some old perls do not have this, try to make it work, no
17// guarantees, though. if it breaks, you get to keep the pieces. 18// guarantees, though. if it breaks, you get to keep the pieces.
18#ifndef UTF8_MAXBYTES 19#ifndef UTF8_MAXBYTES
19# define UTF8_MAXBYTES 13 20# define UTF8_MAXBYTES 13
21#endif
22
23// compatibility with perl <5.18
24#ifndef HvNAMELEN_get
25# define HvNAMELEN_get(hv) strlen (HvNAME (hv))
26#endif
27#ifndef HvNAMELEN
28# define HvNAMELEN(hv) HvNAMELEN_get (hv)
29#endif
30#ifndef HvNAMEUTF8
31# define HvNAMEUTF8(hv) 0
20#endif 32#endif
21 33
22// three extra for rounding, sign, and end of string 34// three extra for rounding, sign, and end of string
23#define IVUV_MAXCHARS (sizeof (UV) * CHAR_BIT * 28 / 93 + 3) 35#define IVUV_MAXCHARS (sizeof (UV) * CHAR_BIT * 28 / 93 + 3)
24 36
33#define F_SHRINK 0x00000200UL 45#define F_SHRINK 0x00000200UL
34#define F_ALLOW_BLESSED 0x00000400UL 46#define F_ALLOW_BLESSED 0x00000400UL
35#define F_CONV_BLESSED 0x00000800UL 47#define F_CONV_BLESSED 0x00000800UL
36#define F_RELAXED 0x00001000UL 48#define F_RELAXED 0x00001000UL
37#define F_ALLOW_UNKNOWN 0x00002000UL 49#define F_ALLOW_UNKNOWN 0x00002000UL
50#define F_ALLOW_TAGS 0x00004000UL
38#define F_HOOK 0x00080000UL // some hooks exist, so slow-path processing 51#define F_HOOK 0x00080000UL // some hooks exist, so slow-path processing
39 52
40#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER 53#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER
41 54
42#define INIT_SIZE 32 // initial scalar size to be allocated 55#define INIT_SIZE 32 // initial scalar size to be allocated
67#define ERR_NESTING_EXCEEDED "json text or perl structure exceeds maximum nesting level (max_depth set too low?)" 80#define ERR_NESTING_EXCEEDED "json text or perl structure exceeds maximum nesting level (max_depth set too low?)"
68 81
69#ifdef USE_ITHREADS 82#ifdef USE_ITHREADS
70# define JSON_SLOW 1 83# define JSON_SLOW 1
71# define JSON_STASH (json_stash ? json_stash : gv_stashpv ("JSON::XS", 1)) 84# define JSON_STASH (json_stash ? json_stash : gv_stashpv ("JSON::XS", 1))
85# define BOOL_STASH (bool_stash ? bool_stash : gv_stashpv ("Types::Serialiser::Boolean", 1))
72#else 86#else
73# define JSON_SLOW 0 87# define JSON_SLOW 0
74# define JSON_STASH json_stash 88# define JSON_STASH json_stash
89# define BOOL_STASH bool_stash
75#endif 90#endif
76 91
77static HV *json_stash, *json_boolean_stash; // JSON::XS:: 92// the amount of HEs to allocate on the stack, when sorting keys
78static SV *json_true, *json_false; 93#define STACK_HES 64
94
95static HV *json_stash, *bool_stash; // JSON::XS::, Types::Serialiser::Boolean::
96static SV *bool_true, *bool_false, *sv_json;
79 97
80enum { 98enum {
81 INCR_M_WS = 0, // initial whitespace skipping, must be 0 99 INCR_M_WS = 0, // initial whitespace skipping, must be 0
82 INCR_M_STR, // inside string 100 INCR_M_STR, // inside string
83 INCR_M_BS, // inside backslash 101 INCR_M_BS, // inside backslash
260 } 278 }
261 279
262 // this relies greatly on the quality of the pow () 280 // this relies greatly on the quality of the pow ()
263 // implementation of the platform, but a good 281 // implementation of the platform, but a good
264 // implementation is hard to beat. 282 // implementation is hard to beat.
283 // (IEEE 754 conformant ones are required to be exact)
265 if (postdp) *expo -= eaccum; 284 if (postdp) *expo -= eaccum;
266 *accum += uaccum * Perl_pow (10., *expo); 285 *accum += uaccum * Perl_pow (10., *expo);
267 *expo += eaccum; 286 *expo += eaccum;
268} 287}
269 288
283 // a recursion depth of ten gives us >>500 bits 302 // a recursion depth of ten gives us >>500 bits
284 json_atof_scan1 (s, &accum, &expo, 0, 10); 303 json_atof_scan1 (s, &accum, &expo, 0, 10);
285 304
286 return neg ? -accum : accum; 305 return neg ? -accum : accum;
287} 306}
307
308// target of scalar reference is bool? -1 == nope, 0 == false, 1 == true
309static int
310ref_bool_type (SV *sv)
311{
312 svtype svt = SvTYPE (sv);
313
314 if (svt < SVt_PVAV)
315 {
316 STRLEN len = 0;
317 char *pv = svt ? SvPV (sv, len) : 0;
318
319 if (len == 1)
320 if (*pv == '1')
321 return 1;
322 else if (*pv == '0')
323 return 0;
324 }
325
326 return -1;
327}
328
329// returns whether scalar is not a reference in the sense of allow_nonref
330static int
331json_nonref (SV *scalar)
332{
333 if (!SvROK (scalar))
334 return 1;
335
336 scalar = SvRV (scalar);
337
338 if (SvTYPE (scalar) >= SVt_PVMG)
339 {
340 if (SvSTASH (scalar) == bool_stash)
341 return 1;
342
343 if (!SvOBJECT (scalar) && ref_bool_type (scalar) >= 0)
344 return 1;
345 }
346
347 return 0;
348}
349
288///////////////////////////////////////////////////////////////////////////// 350/////////////////////////////////////////////////////////////////////////////
289// encoder 351// encoder
290 352
291// structure used for encoding JSON 353// structure used for encoding JSON
292typedef struct 354typedef struct
300} enc_t; 362} enc_t;
301 363
302INLINE void 364INLINE void
303need (enc_t *enc, STRLEN len) 365need (enc_t *enc, STRLEN len)
304{ 366{
305 if (expect_false (enc->cur + len >= enc->end)) 367 if (expect_false ((uintptr_t)(enc->end - enc->cur) < len))
306 { 368 {
307 STRLEN cur = enc->cur - (char *)SvPVX (enc->sv); 369 STRLEN cur = enc->cur - (char *)SvPVX (enc->sv);
308 SvGROW (enc->sv, cur + (len < (cur >> 2) ? cur >> 2 : len) + 1); 370 SvGROW (enc->sv, cur + (len < (cur >> 2) ? cur >> 2 : len) + 1);
309 enc->cur = SvPVX (enc->sv) + cur; 371 enc->cur = SvPVX (enc->sv) + cur;
310 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1; 372 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
479 541
480 if (enc->indent >= enc->json.max_depth) 542 if (enc->indent >= enc->json.max_depth)
481 croak (ERR_NESTING_EXCEEDED); 543 croak (ERR_NESTING_EXCEEDED);
482 544
483 encode_ch (enc, '['); 545 encode_ch (enc, '[');
484 546
485 if (len >= 0) 547 if (len >= 0)
486 { 548 {
487 encode_nl (enc); ++enc->indent; 549 encode_nl (enc); ++enc->indent;
488 550
489 for (i = 0; i <= len; ++i) 551 for (i = 0; i <= len; ++i)
501 encode_comma (enc); 563 encode_comma (enc);
502 } 564 }
503 565
504 encode_nl (enc); --enc->indent; encode_indent (enc); 566 encode_nl (enc); --enc->indent; encode_indent (enc);
505 } 567 }
506 568
507 encode_ch (enc, ']'); 569 encode_ch (enc, ']');
508} 570}
509 571
510static void 572static void
511encode_hk (enc_t *enc, HE *he) 573encode_hk (enc_t *enc, HE *he)
515 if (HeKLEN (he) == HEf_SVKEY) 577 if (HeKLEN (he) == HEf_SVKEY)
516 { 578 {
517 SV *sv = HeSVKEY (he); 579 SV *sv = HeSVKEY (he);
518 STRLEN len; 580 STRLEN len;
519 char *str; 581 char *str;
520 582
521 SvGETMAGIC (sv); 583 SvGETMAGIC (sv);
522 str = SvPV (sv, len); 584 str = SvPV (sv, len);
523 585
524 encode_str (enc, str, len, SvUTF8 (sv)); 586 encode_str (enc, str, len, SvUTF8 (sv));
525 } 587 }
591 } 653 }
592 654
593 if (count) 655 if (count)
594 { 656 {
595 int i, fast = 1; 657 int i, fast = 1;
596#if defined(__BORLANDC__) || defined(_MSC_VER) 658 HE *hes_stack [STACK_HES];
597 HE **hes = _alloca (count * sizeof (HE)); 659 HE **hes = hes_stack;
598#else 660
599 HE *hes [count]; // if your compiler dies here, you need to enable C99 mode 661 // allocate larger arrays on the heap
600#endif 662 if (count > STACK_HES)
663 {
664 SV *sv = sv_2mortal (NEWSV (0, count * sizeof (*hes)));
665 hes = (HE **)SvPVX (sv);
666 }
601 667
602 i = 0; 668 i = 0;
603 while ((he = hv_iternext (hv))) 669 while ((he = hv_iternext (hv)))
604 { 670 {
605 hes [i++] = he; 671 hes [i++] = he;
674// encode objects, arrays and special \0=false and \1=true values. 740// encode objects, arrays and special \0=false and \1=true values.
675static void 741static void
676encode_rv (enc_t *enc, SV *sv) 742encode_rv (enc_t *enc, SV *sv)
677{ 743{
678 svtype svt; 744 svtype svt;
745 GV *method;
679 746
680 SvGETMAGIC (sv); 747 SvGETMAGIC (sv);
681 svt = SvTYPE (sv); 748 svt = SvTYPE (sv);
682 749
683 if (expect_false (SvOBJECT (sv))) 750 if (expect_false (SvOBJECT (sv)))
684 { 751 {
685 HV *stash = !JSON_SLOW || json_boolean_stash 752 HV *stash = SvSTASH (sv);
686 ? json_boolean_stash
687 : gv_stashpv ("JSON::XS::Boolean", 1);
688 753
689 if (SvSTASH (sv) == stash) 754 if (stash == bool_stash)
690 { 755 {
691 if (SvIV (sv)) 756 if (SvIV (sv))
692 encode_str (enc, "true", 4, 0); 757 encode_str (enc, "true", 4, 0);
693 else 758 else
694 encode_str (enc, "false", 5, 0); 759 encode_str (enc, "false", 5, 0);
695 } 760 }
761 else if ((enc->json.flags & F_ALLOW_TAGS) && (method = gv_fetchmethod_autoload (stash, "FREEZE", 0)))
762 {
763 int count;
764 dSP;
765
766 ENTER; SAVETMPS;
767 SAVESTACK_POS ();
768 PUSHMARK (SP);
769 EXTEND (SP, 2);
770 // we re-bless the reference to get overload and other niceties right
771 PUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), stash));
772 PUSHs (sv_json);
773
774 PUTBACK;
775 count = call_sv ((SV *)GvCV (method), G_ARRAY);
776 SPAGAIN;
777
778 // catch this surprisingly common error
779 if (SvROK (TOPs) && SvRV (TOPs) == sv)
780 croak ("%s::FREEZE method returned same object as was passed instead of a new one", HvNAME (SvSTASH (sv)));
781
782 encode_ch (enc, '(');
783 encode_ch (enc, '"');
784 encode_str (enc, HvNAME (stash), HvNAMELEN (stash), HvNAMEUTF8 (stash));
785 encode_ch (enc, '"');
786 encode_ch (enc, ')');
787 encode_ch (enc, '[');
788
789 while (count)
790 {
791 encode_sv (enc, SP[1 - count--]);
792
793 if (count)
794 encode_ch (enc, ',');
795 }
796
797 encode_ch (enc, ']');
798
799 FREETMPS; LEAVE;
800 }
801 else if ((enc->json.flags & F_CONV_BLESSED) && (method = gv_fetchmethod_autoload (stash, "TO_JSON", 0)))
802 {
803 dSP;
804
805 ENTER; SAVETMPS;
806 PUSHMARK (SP);
807 // we re-bless the reference to get overload and other niceties right
808 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), stash));
809
810 // calling with G_SCALAR ensures that we always get a 1 return value
811 PUTBACK;
812 call_sv ((SV *)GvCV (method), G_SCALAR);
813 SPAGAIN;
814
815 // catch this surprisingly common error
816 if (SvROK (TOPs) && SvRV (TOPs) == sv)
817 croak ("%s::TO_JSON method returned same object as was passed instead of a new one", HvNAME (SvSTASH (sv)));
818
819 sv = POPs;
820 PUTBACK;
821
822 encode_sv (enc, sv);
823
824 FREETMPS; LEAVE;
825 }
826 else if (enc->json.flags & F_ALLOW_BLESSED)
827 encode_str (enc, "null", 4, 0);
696 else 828 else
697 {
698#if 0
699 if (0 && sv_derived_from (rv, "JSON::Literal"))
700 {
701 // not yet
702 }
703#endif
704 if (enc->json.flags & F_CONV_BLESSED)
705 {
706 // we re-bless the reference to get overload and other niceties right
707 GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 0);
708
709 if (to_json)
710 {
711 dSP;
712
713 ENTER; SAVETMPS; PUSHMARK (SP);
714 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv)));
715
716 // calling with G_SCALAR ensures that we always get a 1 return value
717 PUTBACK;
718 call_sv ((SV *)GvCV (to_json), G_SCALAR);
719 SPAGAIN;
720
721 // catch this surprisingly common error
722 if (SvROK (TOPs) && SvRV (TOPs) == sv)
723 croak ("%s::TO_JSON method returned same object as was passed instead of a new one", HvNAME (SvSTASH (sv)));
724
725 sv = POPs;
726 PUTBACK;
727
728 encode_sv (enc, sv);
729
730 FREETMPS; LEAVE;
731 }
732 else if (enc->json.flags & F_ALLOW_BLESSED)
733 encode_str (enc, "null", 4, 0);
734 else
735 croak ("encountered object '%s', but neither allow_blessed enabled nor TO_JSON method available on it",
736 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
737 }
738 else if (enc->json.flags & F_ALLOW_BLESSED)
739 encode_str (enc, "null", 4, 0);
740 else
741 croak ("encountered object '%s', but neither allow_blessed nor convert_blessed settings are enabled", 829 croak ("encountered object '%s', but neither allow_blessed, convert_blessed nor allow_tags settings are enabled (or TO_JSON/FREEZE method missing)",
742 SvPV_nolen (sv_2mortal (newRV_inc (sv)))); 830 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
743 }
744 } 831 }
745 else if (svt == SVt_PVHV) 832 else if (svt == SVt_PVHV)
746 encode_hv (enc, (HV *)sv); 833 encode_hv (enc, (HV *)sv);
747 else if (svt == SVt_PVAV) 834 else if (svt == SVt_PVAV)
748 encode_av (enc, (AV *)sv); 835 encode_av (enc, (AV *)sv);
749 else if (svt < SVt_PVAV) 836 else if (svt < SVt_PVAV)
750 { 837 {
751 STRLEN len = 0; 838 int bool_type = ref_bool_type (sv);
752 char *pv = svt ? SvPV (sv, len) : 0;
753 839
754 if (len == 1 && *pv == '1') 840 if (bool_type == 1)
755 encode_str (enc, "true", 4, 0); 841 encode_str (enc, "true", 4, 0);
756 else if (len == 1 && *pv == '0') 842 else if (bool_type == 0)
757 encode_str (enc, "false", 5, 0); 843 encode_str (enc, "false", 5, 0);
758 else if (enc->json.flags & F_ALLOW_UNKNOWN) 844 else if (enc->json.flags & F_ALLOW_UNKNOWN)
759 encode_str (enc, "null", 4, 0); 845 encode_str (enc, "null", 4, 0);
760 else 846 else
761 croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1", 847 croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1",
824 } 910 }
825 else 911 else
826 { 912 {
827 // large integer, use the (rather slow) snprintf way. 913 // large integer, use the (rather slow) snprintf way.
828 need (enc, IVUV_MAXCHARS); 914 need (enc, IVUV_MAXCHARS);
829 enc->cur += 915 enc->cur +=
830 SvIsUV(sv) 916 SvIsUV(sv)
831 ? snprintf (enc->cur, IVUV_MAXCHARS, "%"UVuf, (UV)SvUVX (sv)) 917 ? snprintf (enc->cur, IVUV_MAXCHARS, "%"UVuf, (UV)SvUVX (sv))
832 : snprintf (enc->cur, IVUV_MAXCHARS, "%"IVdf, (IV)SvIVX (sv)); 918 : snprintf (enc->cur, IVUV_MAXCHARS, "%"IVdf, (IV)SvIVX (sv));
833 } 919 }
834 } 920 }
835 else if (SvROK (sv)) 921 else if (SvROK (sv))
836 encode_rv (enc, SvRV (sv)); 922 encode_rv (enc, SvRV (sv));
837 else if (!SvOK (sv) || enc->json.flags & F_ALLOW_UNKNOWN) 923 else if (!SvOK (sv) || enc->json.flags & F_ALLOW_UNKNOWN)
838 encode_str (enc, "null", 4, 0); 924 encode_str (enc, "null", 4, 0);
839 else 925 else
840 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this", 926 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, check your input data",
841 SvPV_nolen (sv), SvFLAGS (sv)); 927 SvPV_nolen (sv), (unsigned int)SvFLAGS (sv));
842} 928}
843 929
844static SV * 930static SV *
845encode_json (SV *scalar, JSON *json) 931encode_json (SV *scalar, JSON *json)
846{ 932{
847 enc_t enc; 933 enc_t enc;
848 934
849 if (!(json->flags & F_ALLOW_NONREF) && !SvROK (scalar)) 935 if (!(json->flags & F_ALLOW_NONREF) && json_nonref (scalar))
850 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)"); 936 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)");
851 937
852 enc.json = *json; 938 enc.json = *json;
853 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 939 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
854 enc.cur = SvPVX (enc.sv); 940 enc.cur = SvPVX (enc.sv);
1061 *cur++ = *dec_cur++; 1147 *cur++ = *dec_cur++;
1062 while (--clen); 1148 while (--clen);
1063 1149
1064 utf8 = 1; 1150 utf8 = 1;
1065 } 1151 }
1152 else if (ch == '\t' && dec->json.flags & F_RELAXED)
1153 *cur++ = ch;
1066 else 1154 else
1067 { 1155 {
1068 --dec_cur; 1156 --dec_cur;
1069 1157
1070 if (!ch) 1158 if (!ch)
1258 if (*dec->cur == ']') 1346 if (*dec->cur == ']')
1259 { 1347 {
1260 ++dec->cur; 1348 ++dec->cur;
1261 break; 1349 break;
1262 } 1350 }
1263 1351
1264 if (*dec->cur != ',') 1352 if (*dec->cur != ',')
1265 ERR (", or ] expected while parsing array"); 1353 ERR (", or ] expected while parsing array");
1266 1354
1267 ++dec->cur; 1355 ++dec->cur;
1268 1356
1392 1480
1393 hv_iterinit (hv); 1481 hv_iterinit (hv);
1394 he = hv_iternext (hv); 1482 he = hv_iternext (hv);
1395 hv_iterinit (hv); 1483 hv_iterinit (hv);
1396 1484
1397 // the next line creates a mortal sv each time its called. 1485 // the next line creates a mortal sv each time it's called.
1398 // might want to optimise this for common cases. 1486 // might want to optimise this for common cases.
1399 cb = hv_fetch_ent (dec->json.cb_sk_object, hv_iterkeysv (he), 0, 0); 1487 cb = hv_fetch_ent (dec->json.cb_sk_object, hv_iterkeysv (he), 0, 0);
1400 1488
1401 if (cb) 1489 if (cb)
1402 { 1490 {
1403 dSP; 1491 dSP;
1404 int count; 1492 int count;
1405 1493
1406 ENTER; SAVETMPS; PUSHMARK (SP); 1494 ENTER; SAVETMPS;
1495 SAVESTACK_POS ();
1496 PUSHMARK (SP);
1407 XPUSHs (HeVAL (he)); 1497 XPUSHs (HeVAL (he));
1408 sv_2mortal (sv); 1498 sv_2mortal (sv);
1409 1499
1410 PUTBACK; count = call_sv (HeVAL (cb), G_ARRAY); SPAGAIN; 1500 PUTBACK; count = call_sv (HeVAL (cb), G_ARRAY); SPAGAIN;
1411 1501
1424 if (dec->json.cb_object) 1514 if (dec->json.cb_object)
1425 { 1515 {
1426 dSP; 1516 dSP;
1427 int count; 1517 int count;
1428 1518
1429 ENTER; SAVETMPS; PUSHMARK (SP); 1519 ENTER; SAVETMPS;
1520 SAVESTACK_POS ();
1521 PUSHMARK (SP);
1430 XPUSHs (sv_2mortal (sv)); 1522 XPUSHs (sv_2mortal (sv));
1431 1523
1432 PUTBACK; count = call_sv (dec->json.cb_object, G_ARRAY); SPAGAIN; 1524 PUTBACK; count = call_sv (dec->json.cb_object, G_ARRAY); SPAGAIN;
1433 1525
1434 if (count == 1) 1526 if (count == 1)
1450 DEC_DEC_DEPTH; 1542 DEC_DEC_DEPTH;
1451 return 0; 1543 return 0;
1452} 1544}
1453 1545
1454static SV * 1546static SV *
1547decode_tag (dec_t *dec)
1548{
1549 SV *tag = 0;
1550 SV *val = 0;
1551
1552 if (!(dec->json.flags & F_ALLOW_TAGS))
1553 ERR ("malformed JSON string, neither array, object, number, string or atom");
1554
1555 ++dec->cur;
1556
1557 decode_ws (dec);
1558
1559 tag = decode_sv (dec);
1560 if (!tag)
1561 goto fail;
1562
1563 if (!SvPOK (tag))
1564 ERR ("malformed JSON string, (tag) must be a string");
1565
1566 decode_ws (dec);
1567
1568 if (*dec->cur != ')')
1569 ERR (") expected after tag");
1570
1571 ++dec->cur;
1572
1573 decode_ws (dec);
1574
1575 val = decode_sv (dec);
1576 if (!val)
1577 goto fail;
1578
1579 if (!SvROK (val) || SvTYPE (SvRV (val)) != SVt_PVAV)
1580 ERR ("malformed JSON string, tag value must be an array");
1581
1582 {
1583 AV *av = (AV *)SvRV (val);
1584 int i, len = av_len (av) + 1;
1585 HV *stash = gv_stashsv (tag, 0);
1586 SV *sv;
1587
1588 if (!stash)
1589 ERR ("cannot decode perl-object (package does not exist)");
1590
1591 GV *method = gv_fetchmethod_autoload (stash, "THAW", 0);
1592
1593 if (!method)
1594 ERR ("cannot decode perl-object (package does not have a THAW method)");
1595
1596 dSP;
1597
1598 ENTER; SAVETMPS;
1599 PUSHMARK (SP);
1600 EXTEND (SP, len + 2);
1601 // we re-bless the reference to get overload and other niceties right
1602 PUSHs (tag);
1603 PUSHs (sv_json);
1604
1605 for (i = 0; i < len; ++i)
1606 PUSHs (*av_fetch (av, i, 1));
1607
1608 PUTBACK;
1609 call_sv ((SV *)GvCV (method), G_SCALAR);
1610 SPAGAIN;
1611
1612 SvREFCNT_dec (tag);
1613 SvREFCNT_dec (val);
1614 sv = SvREFCNT_inc (POPs);
1615
1616 PUTBACK;
1617
1618 FREETMPS; LEAVE;
1619
1620 return sv;
1621 }
1622
1623fail:
1624 SvREFCNT_dec (tag);
1625 SvREFCNT_dec (val);
1626 return 0;
1627}
1628
1629static SV *
1455decode_sv (dec_t *dec) 1630decode_sv (dec_t *dec)
1456{ 1631{
1457 // the beauty of JSON: you need exactly one character lookahead 1632 // the beauty of JSON: you need exactly one character lookahead
1458 // to parse everything. 1633 // to parse everything.
1459 switch (*dec->cur) 1634 switch (*dec->cur)
1460 { 1635 {
1461 case '"': ++dec->cur; return decode_str (dec); 1636 case '"': ++dec->cur; return decode_str (dec);
1462 case '[': ++dec->cur; return decode_av (dec); 1637 case '[': ++dec->cur; return decode_av (dec);
1463 case '{': ++dec->cur; return decode_hv (dec); 1638 case '{': ++dec->cur; return decode_hv (dec);
1639 case '(': return decode_tag (dec);
1464 1640
1465 case '-': 1641 case '-':
1466 case '0': case '1': case '2': case '3': case '4': 1642 case '0': case '1': case '2': case '3': case '4':
1467 case '5': case '6': case '7': case '8': case '9': 1643 case '5': case '6': case '7': case '8': case '9':
1468 return decode_num (dec); 1644 return decode_num (dec);
1470 case 't': 1646 case 't':
1471 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1647 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
1472 { 1648 {
1473 dec->cur += 4; 1649 dec->cur += 4;
1474#if JSON_SLOW 1650#if JSON_SLOW
1475 json_true = get_bool ("JSON::XS::true"); 1651 bool_true = get_bool ("Types::Serialiser::true");
1476#endif 1652#endif
1477 return newSVsv (json_true); 1653 return newSVsv (bool_true);
1478 } 1654 }
1479 else 1655 else
1480 ERR ("'true' expected"); 1656 ERR ("'true' expected");
1481 1657
1482 break; 1658 break;
1484 case 'f': 1660 case 'f':
1485 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1661 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
1486 { 1662 {
1487 dec->cur += 5; 1663 dec->cur += 5;
1488#if JSON_SLOW 1664#if JSON_SLOW
1489 json_false = get_bool ("JSON::XS::false"); 1665 bool_false = get_bool ("Types::Serialiser::false");
1490#endif 1666#endif
1491 return newSVsv (json_false); 1667 return newSVsv (bool_false);
1492 } 1668 }
1493 else 1669 else
1494 ERR ("'false' expected"); 1670 ERR ("'false' expected");
1495 1671
1496 break; 1672 break;
1505 ERR ("'null' expected"); 1681 ERR ("'null' expected");
1506 1682
1507 break; 1683 break;
1508 1684
1509 default: 1685 default:
1510 ERR ("malformed JSON string, neither array, object, number, string or atom"); 1686 ERR ("malformed JSON string, neither tag, array, object, number, string or atom");
1511 break; 1687 break;
1512 } 1688 }
1513 1689
1514fail: 1690fail:
1515 return 0; 1691 return 0;
1516} 1692}
1517 1693
1518static SV * 1694static SV *
1519decode_json (SV *string, JSON *json, char **offset_return) 1695decode_json (SV *string, JSON *json, STRLEN *offset_return)
1520{ 1696{
1521 dec_t dec; 1697 dec_t dec;
1522 SV *sv; 1698 SV *sv;
1523 1699
1524 /* work around bugs in 5.10 where manipulating magic values 1700 /* work around bugs in 5.10 where manipulating magic values
1525 * will perl ignore the magic in subsequent accesses 1701 * makes perl ignore the magic in subsequent accesses.
1702 * also make a copy of non-PV values, to get them into a clean
1703 * state (SvPV should do that, but it's buggy, see below).
1704 *
1705 * SvIsCOW_shared_hash works around a bug in perl (possibly 5.16),
1706 * as reported by Reini Urban.
1526 */ 1707 */
1527 /*SvGETMAGIC (string);*/ 1708 /*SvGETMAGIC (string);*/
1528 if (SvMAGICAL (string)) 1709 if (SvMAGICAL (string) || !SvPOK (string) || SvIsCOW_shared_hash (string))
1529 string = sv_2mortal (newSVsv (string)); 1710 string = sv_2mortal (newSVsv (string));
1530 1711
1531 SvUPGRADE (string, SVt_PV); 1712 SvUPGRADE (string, SVt_PV);
1532 1713
1533 /* work around a bug in perl 5.10, which causes SvCUR to fail an 1714 /* work around a bug in perl 5.10, which causes SvCUR to fail an
1572 1753
1573 decode_ws (&dec); 1754 decode_ws (&dec);
1574 sv = decode_sv (&dec); 1755 sv = decode_sv (&dec);
1575 1756
1576 if (offset_return) 1757 if (offset_return)
1577 *offset_return = dec.cur; 1758 *offset_return = dec.cur - SvPVX (string);
1578 1759 else if (sv)
1579 if (!(offset_return || !sv))
1580 { 1760 {
1581 // check for trailing garbage 1761 // check for trailing garbage
1582 decode_ws (&dec); 1762 decode_ws (&dec);
1583 1763
1584 if (*dec.cur) 1764 if (*dec.cur)
1602 pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ); 1782 pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ);
1603 LEAVE; 1783 LEAVE;
1604 1784
1605 croak ("%s, at character offset %d (before \"%s\")", 1785 croak ("%s, at character offset %d (before \"%s\")",
1606 dec.err, 1786 dec.err,
1607 ptr_to_index (string, dec.cur), 1787 (int)ptr_to_index (string, dec.cur),
1608 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); 1788 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
1609 } 1789 }
1610 1790
1611 sv = sv_2mortal (sv); 1791 sv = sv_2mortal (sv);
1612 1792
1613 if (!(dec.json.flags & F_ALLOW_NONREF) && !SvROK (sv)) 1793 if (!(dec.json.flags & F_ALLOW_NONREF) && json_nonref (sv))
1614 croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)"); 1794 croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)");
1615 1795
1616 return sv; 1796 return sv;
1617} 1797}
1618 1798
1740 self->incr_mode = INCR_M_STR; 1920 self->incr_mode = INCR_M_STR;
1741 goto incr_m_str; 1921 goto incr_m_str;
1742 1922
1743 case '[': 1923 case '[':
1744 case '{': 1924 case '{':
1925 case '(':
1745 if (++self->incr_nest > self->max_depth) 1926 if (++self->incr_nest > self->max_depth)
1746 croak (ERR_NESTING_EXCEEDED); 1927 croak (ERR_NESTING_EXCEEDED);
1747 break; 1928 break;
1748 1929
1749 case ']': 1930 case ']':
1750 case '}': 1931 case '}':
1751 if (--self->incr_nest <= 0) 1932 if (--self->incr_nest <= 0)
1752 goto interrupt; 1933 goto interrupt;
1934 break;
1935
1936 case ')':
1937 --self->incr_nest;
1753 break; 1938 break;
1754 1939
1755 case '#': 1940 case '#':
1756 self->incr_mode = INCR_M_C1; 1941 self->incr_mode = INCR_M_C1;
1757 goto incr_m_c; 1942 goto incr_m_c;
1783 i >= '0' && i <= '9' ? i - '0' 1968 i >= '0' && i <= '9' ? i - '0'
1784 : i >= 'a' && i <= 'f' ? i - 'a' + 10 1969 : i >= 'a' && i <= 'f' ? i - 'a' + 10
1785 : i >= 'A' && i <= 'F' ? i - 'A' + 10 1970 : i >= 'A' && i <= 'F' ? i - 'A' + 10
1786 : -1; 1971 : -1;
1787 1972
1788 json_stash = gv_stashpv ("JSON::XS" , 1); 1973 json_stash = gv_stashpv ("JSON::XS" , 1);
1789 json_boolean_stash = gv_stashpv ("JSON::XS::Boolean", 1); 1974 bool_stash = gv_stashpv ("Types::Serialiser::Boolean", 1);
1790
1791 json_true = get_bool ("JSON::XS::true"); 1975 bool_true = get_bool ("Types::Serialiser::true");
1792 json_false = get_bool ("JSON::XS::false"); 1976 bool_false = get_bool ("Types::Serialiser::false");
1977
1978 sv_json = newSVpv ("JSON", 0);
1979 SvREADONLY_on (sv_json);
1793 1980
1794 CvNODEBUG_on (get_cv ("JSON::XS::incr_text", 0)); /* the debugger completely breaks lvalue subs */ 1981 CvNODEBUG_on (get_cv ("JSON::XS::incr_text", 0)); /* the debugger completely breaks lvalue subs */
1795} 1982}
1796 1983
1797PROTOTYPES: DISABLE 1984PROTOTYPES: DISABLE
1798 1985
1799void CLONE (...) 1986void CLONE (...)
1800 CODE: 1987 CODE:
1801 json_stash = 0; 1988 json_stash = 0;
1802 json_boolean_stash = 0; 1989 bool_stash = 0;
1803 1990
1804void new (char *klass) 1991void new (char *klass)
1805 PPCODE: 1992 PPCODE:
1806{ 1993{
1807 SV *pv = NEWSV (0, sizeof (JSON)); 1994 SV *pv = NEWSV (0, sizeof (JSON));
1808 SvPOK_only (pv); 1995 SvPOK_only (pv);
1809 json_init ((JSON *)SvPVX (pv)); 1996 json_init ((JSON *)SvPVX (pv));
1810 XPUSHs (sv_2mortal (sv_bless ( 1997 XPUSHs (sv_2mortal (sv_bless (
1811 newRV_noinc (pv), 1998 newRV_noinc (pv),
1812 strEQ (klass, "JSON::XS") ? JSON_STASH : gv_stashpv (klass, 1) 1999 strEQ (klass, "JSON::XS") ? JSON_STASH : gv_stashpv (klass, 1)
1827 shrink = F_SHRINK 2014 shrink = F_SHRINK
1828 allow_blessed = F_ALLOW_BLESSED 2015 allow_blessed = F_ALLOW_BLESSED
1829 convert_blessed = F_CONV_BLESSED 2016 convert_blessed = F_CONV_BLESSED
1830 relaxed = F_RELAXED 2017 relaxed = F_RELAXED
1831 allow_unknown = F_ALLOW_UNKNOWN 2018 allow_unknown = F_ALLOW_UNKNOWN
2019 allow_tags = F_ALLOW_TAGS
1832 PPCODE: 2020 PPCODE:
1833{ 2021{
1834 if (enable) 2022 if (enable)
1835 self->flags |= ix; 2023 self->flags |= ix;
1836 else 2024 else
1852 get_shrink = F_SHRINK 2040 get_shrink = F_SHRINK
1853 get_allow_blessed = F_ALLOW_BLESSED 2041 get_allow_blessed = F_ALLOW_BLESSED
1854 get_convert_blessed = F_CONV_BLESSED 2042 get_convert_blessed = F_CONV_BLESSED
1855 get_relaxed = F_RELAXED 2043 get_relaxed = F_RELAXED
1856 get_allow_unknown = F_ALLOW_UNKNOWN 2044 get_allow_unknown = F_ALLOW_UNKNOWN
2045 get_allow_tags = F_ALLOW_TAGS
1857 PPCODE: 2046 PPCODE:
1858 XPUSHs (boolSV (self->flags & ix)); 2047 XPUSHs (boolSV (self->flags & ix));
1859 2048
1860void max_depth (JSON *self, U32 max_depth = 0x80000000UL) 2049void max_depth (JSON *self, U32 max_depth = 0x80000000UL)
1861 PPCODE: 2050 PPCODE:
1889} 2078}
1890 2079
1891void filter_json_single_key_object (JSON *self, SV *key, SV *cb = &PL_sv_undef) 2080void filter_json_single_key_object (JSON *self, SV *key, SV *cb = &PL_sv_undef)
1892 PPCODE: 2081 PPCODE:
1893{ 2082{
1894 if (!self->cb_sk_object) 2083 if (!self->cb_sk_object)
1895 self->cb_sk_object = newHV (); 2084 self->cb_sk_object = newHV ();
1896 2085
1897 if (SvOK (cb)) 2086 if (SvOK (cb))
1898 hv_store_ent (self->cb_sk_object, key, newSVsv (cb), 0); 2087 hv_store_ent (self->cb_sk_object, key, newSVsv (cb), 0);
1899 else 2088 else
1910 XPUSHs (ST (0)); 2099 XPUSHs (ST (0));
1911} 2100}
1912 2101
1913void encode (JSON *self, SV *scalar) 2102void encode (JSON *self, SV *scalar)
1914 PPCODE: 2103 PPCODE:
1915 XPUSHs (encode_json (scalar, self)); 2104 PUTBACK; scalar = encode_json (scalar, self); SPAGAIN;
2105 XPUSHs (scalar);
1916 2106
1917void decode (JSON *self, SV *jsonstr) 2107void decode (JSON *self, SV *jsonstr)
1918 PPCODE: 2108 PPCODE:
1919 XPUSHs (decode_json (jsonstr, self, 0)); 2109 PUTBACK; jsonstr = decode_json (jsonstr, self, 0); SPAGAIN;
2110 XPUSHs (jsonstr);
1920 2111
1921void decode_prefix (JSON *self, SV *jsonstr) 2112void decode_prefix (JSON *self, SV *jsonstr)
1922 PPCODE: 2113 PPCODE:
1923{ 2114{
1924 char *offset; 2115 SV *sv;
2116 STRLEN offset;
2117 PUTBACK; sv = decode_json (jsonstr, self, &offset); SPAGAIN;
1925 EXTEND (SP, 2); 2118 EXTEND (SP, 2);
1926 PUSHs (decode_json (jsonstr, self, &offset)); 2119 PUSHs (sv);
1927 PUSHs (sv_2mortal (newSVuv (ptr_to_index (jsonstr, offset)))); 2120 PUSHs (sv_2mortal (newSVuv (ptr_to_index (jsonstr, SvPV_nolen (jsonstr) + offset))));
1928} 2121}
1929 2122
1930void incr_parse (JSON *self, SV *jsonstr = 0) 2123void incr_parse (JSON *self, SV *jsonstr = 0)
1931 PPCODE: 2124 PPCODE:
1932{ 2125{
1978 } 2171 }
1979 2172
1980 if (GIMME_V != G_VOID) 2173 if (GIMME_V != G_VOID)
1981 do 2174 do
1982 { 2175 {
2176 SV *sv;
1983 char *offset; 2177 STRLEN offset;
1984 2178
1985 if (!INCR_DONE (self)) 2179 if (!INCR_DONE (self))
1986 { 2180 {
1987 incr_parse (self); 2181 incr_parse (self);
1988 2182
1989 if (self->incr_pos > self->max_size && self->max_size) 2183 if (self->incr_pos > self->max_size && self->max_size)
1990 croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu", 2184 croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu",
1991 (unsigned long)self->incr_pos, (unsigned long)self->max_size); 2185 (unsigned long)self->incr_pos, (unsigned long)self->max_size);
1992 2186
1993 if (!INCR_DONE (self)) 2187 if (!INCR_DONE (self))
2188 {
2189 // as an optimisation, do not accumulate white space in the incr buffer
2190 if (self->incr_mode == INCR_M_WS && self->incr_pos)
2191 {
2192 self->incr_pos = 0;
2193 SvCUR_set (self->incr_text, 0);
2194 }
2195
1994 break; 2196 break;
2197 }
1995 } 2198 }
1996 2199
1997 XPUSHs (decode_json (self->incr_text, self, &offset)); 2200 PUTBACK; sv = decode_json (self->incr_text, self, &offset); SPAGAIN;
2201 XPUSHs (sv);
1998 2202
1999 self->incr_pos -= offset - SvPVX (self->incr_text); 2203 self->incr_pos -= offset;
2000 self->incr_nest = 0; 2204 self->incr_nest = 0;
2001 self->incr_mode = 0; 2205 self->incr_mode = 0;
2002 2206
2003 sv_chop (self->incr_text, offset); 2207 sv_chop (self->incr_text, SvPVX (self->incr_text) + offset);
2004 } 2208 }
2005 while (GIMME_V == G_ARRAY); 2209 while (GIMME_V == G_ARRAY);
2006} 2210}
2007 2211
2008SV *incr_text (JSON *self) 2212SV *incr_text (JSON *self)
2046 SvREFCNT_dec (self->incr_text); 2250 SvREFCNT_dec (self->incr_text);
2047 2251
2048PROTOTYPES: ENABLE 2252PROTOTYPES: ENABLE
2049 2253
2050void encode_json (SV *scalar) 2254void encode_json (SV *scalar)
2051 ALIAS:
2052 to_json_ = 0
2053 encode_json = F_UTF8
2054 PPCODE: 2255 PPCODE:
2055{ 2256{
2056 JSON json; 2257 JSON json;
2057 json_init (&json); 2258 json_init (&json);
2058 json.flags |= ix; 2259 json.flags |= F_UTF8;
2059 XPUSHs (encode_json (scalar, &json)); 2260 PUTBACK; scalar = encode_json (scalar, &json); SPAGAIN;
2261 XPUSHs (scalar);
2060} 2262}
2061 2263
2062void decode_json (SV *jsonstr) 2264void decode_json (SV *jsonstr)
2063 ALIAS:
2064 from_json_ = 0
2065 decode_json = F_UTF8
2066 PPCODE: 2265 PPCODE:
2067{ 2266{
2068 JSON json; 2267 JSON json;
2069 json_init (&json); 2268 json_init (&json);
2070 json.flags |= ix; 2269 json.flags |= F_UTF8;
2071 XPUSHs (decode_json (jsonstr, &json, 0)); 2270 PUTBACK; jsonstr = decode_json (jsonstr, &json, 0); SPAGAIN;
2271 XPUSHs (jsonstr);
2072} 2272}
2073 2273

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines