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.12 by root, Sat Mar 24 22:10:08 2007 UTC vs.
Revision 1.23 by root, Tue Apr 3 23:34:17 2007 UTC

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 8
9#define F_ASCII 0x00000001 9#define F_ASCII 0x00000001UL
10#define F_UTF8 0x00000002 10#define F_UTF8 0x00000002UL
11#define F_INDENT 0x00000004 11#define F_INDENT 0x00000004UL
12#define F_CANONICAL 0x00000008 12#define F_CANONICAL 0x00000008UL
13#define F_SPACE_BEFORE 0x00000010 13#define F_SPACE_BEFORE 0x00000010UL
14#define F_SPACE_AFTER 0x00000020 14#define F_SPACE_AFTER 0x00000020UL
15#define F_ALLOW_NONREF 0x00000080 15#define F_ALLOW_NONREF 0x00000080UL
16#define F_SHRINK 0x00000100 16#define F_SHRINK 0x00000100UL
17#define F_MAXDEPTH 0xf8000000UL
18#define S_MAXDEPTH 27
19
20#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH))
21
22// F_SELFCONVERT? <=> to_json/toJson
23// F_BLESSED? <=> { $__class__$ => }
17 24
18#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER 25#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER
19#define F_DEFAULT 0 26#define F_DEFAULT (12UL << S_MAXDEPTH)
20 27
21#define INIT_SIZE 32 // initial scalar size to be allocated 28#define INIT_SIZE 32 // initial scalar size to be allocated
22#define INDENT_STEP 3 // spaces per indentation level 29#define INDENT_STEP 3 // spaces per indentation level
23 30
24#define UTF8_MAX_LEN 11 // for perls UTF-X: max. number of octets per character 31#define UTF8_MAX_LEN 11 // for perls UTF-X: max. number of octets per character
25#define SHORT_STRING_LEN 256 // special-case strings of up to this size 32#define SHORT_STRING_LEN 512 // special-case strings of up to this size
26 33
27#define SB do { 34#define SB do {
28#define SE } while (0) 35#define SE } while (0)
29 36
30static HV *json_stash; // JSON::XS:: 37static HV *json_stash; // JSON::XS::
53 SvPV_renew (sv, SvCUR (sv) + 1); 60 SvPV_renew (sv, SvCUR (sv) + 1);
54#endif 61#endif
55 } 62 }
56} 63}
57 64
65// decode an utf-8 character and return it, or (UV)-1 in
66// case of an error.
67// we special-case "safe" characters from U+80 .. U+7FF,
68// but use the very good perl function to parse anything else.
69// note that we never call this function for a ascii codepoints
70static UV
71decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
72{
73 if (s[0] > 0xdf || s[0] < 0xc2)
74 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY);
75 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf)
76 {
77 *clen = 2;
78 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
79 }
80 else
81 {
82 *clen = (STRLEN)-1;
83 return (UV)-1;
84 }
85}
86
58///////////////////////////////////////////////////////////////////////////// 87/////////////////////////////////////////////////////////////////////////////
59// encoder 88// encoder
60 89
61// structure used for encoding JSON 90// structure used for encoding JSON
62typedef struct 91typedef struct
63{ 92{
64 char *cur; // SvPVX (sv) + current output position 93 char *cur; // SvPVX (sv) + current output position
65 char *end; // SvEND (sv) 94 char *end; // SvEND (sv)
66 SV *sv; // result scalar 95 SV *sv; // result scalar
67 UV flags; // F_* 96 U32 flags; // F_*
68 int indent; // indentation level 97 U32 indent; // indentation level
69 int max_depth; // max. recursion level 98 U32 maxdepth; // max. indentation/recursion level
70} enc_t; 99} enc_t;
71 100
72static void 101static void
73need (enc_t *enc, STRLEN len) 102need (enc_t *enc, STRLEN len)
74{ 103{
133 STRLEN clen; 162 STRLEN clen;
134 UV uch; 163 UV uch;
135 164
136 if (is_utf8) 165 if (is_utf8)
137 { 166 {
138 uch = utf8n_to_uvuni (str, end - str, &clen, UTF8_CHECK_ONLY); 167 //uch = utf8n_to_uvuni (str, end - str, &clen, UTF8_CHECK_ONLY);
168 uch = decode_utf8 (str, end - str, &clen);
139 if (clen == (STRLEN)-1) 169 if (clen == (STRLEN)-1)
140 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str); 170 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str);
141 } 171 }
142 else 172 else
143 { 173 {
241static void 271static void
242encode_av (enc_t *enc, AV *av) 272encode_av (enc_t *enc, AV *av)
243{ 273{
244 int i, len = av_len (av); 274 int i, len = av_len (av);
245 275
276 if (enc->indent >= enc->maxdepth)
277 croak ("data structure too deep (hit recursion limit)");
278
246 encode_ch (enc, '['); encode_nl (enc); 279 encode_ch (enc, '['); encode_nl (enc);
247 ++enc->indent; 280 ++enc->indent;
248 281
249 for (i = 0; i <= len; ++i) 282 for (i = 0; i <= len; ++i)
250 { 283 {
315 348
316static void 349static void
317encode_hv (enc_t *enc, HV *hv) 350encode_hv (enc_t *enc, HV *hv)
318{ 351{
319 int count, i; 352 int count, i;
353
354 if (enc->indent >= enc->maxdepth)
355 croak ("data structure too deep (hit recursion limit)");
320 356
321 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent; 357 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent;
322 358
323 if ((count = hv_iterinit (hv))) 359 if ((count = hv_iterinit (hv)))
324 { 360 {
393 } 429 }
394 430
395 --enc->indent; encode_indent (enc); encode_ch (enc, '}'); 431 --enc->indent; encode_indent (enc); encode_ch (enc, '}');
396} 432}
397 433
434// encode objects, arrays and special \0=false and \1=true values.
435static void
436encode_rv (enc_t *enc, SV *sv)
437{
438 SvGETMAGIC (sv);
439
440 svtype svt = SvTYPE (sv);
441
442 if (svt == SVt_PVHV)
443 encode_hv (enc, (HV *)sv);
444 else if (svt == SVt_PVAV)
445 encode_av (enc, (AV *)sv);
446 else if (svt < SVt_PVAV)
447 {
448 if (SvNIOK (sv) && SvIV (sv) == 0)
449 encode_str (enc, "false", 5, 0);
450 else if (SvNIOK (sv) && SvIV (sv) == 1)
451 encode_str (enc, "true", 4, 0);
452 else
453 croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1",
454 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
455 }
456 else
457 croak ("encountered %s, but JSON can only represent references to arrays or hashes",
458 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
459}
460
398static void 461static void
399encode_sv (enc_t *enc, SV *sv) 462encode_sv (enc_t *enc, SV *sv)
400{ 463{
401 SvGETMAGIC (sv); 464 SvGETMAGIC (sv);
402 465
421 SvIsUV(sv) 484 SvIsUV(sv)
422 ? snprintf (enc->cur, 64, "%"UVuf, (UV)SvUVX (sv)) 485 ? snprintf (enc->cur, 64, "%"UVuf, (UV)SvUVX (sv))
423 : snprintf (enc->cur, 64, "%"IVdf, (IV)SvIVX (sv)); 486 : snprintf (enc->cur, 64, "%"IVdf, (IV)SvIVX (sv));
424 } 487 }
425 else if (SvROK (sv)) 488 else if (SvROK (sv))
426 { 489 encode_rv (enc, SvRV (sv));
427 SV *rv = SvRV (sv);
428
429 if (enc->indent >= enc->max_depth)
430 croak ("data structure too deep (hit recursion limit)");
431
432 switch (SvTYPE (rv))
433 {
434 case SVt_PVAV: encode_av (enc, (AV *)rv); break;
435 case SVt_PVHV: encode_hv (enc, (HV *)rv); break;
436
437 default:
438 croak ("encountered %s, but JSON can only represent references to arrays or hashes",
439 SvPV_nolen (sv));
440 }
441 }
442 else if (!SvOK (sv)) 490 else if (!SvOK (sv))
443 encode_str (enc, "null", 4, 0); 491 encode_str (enc, "null", 4, 0);
444 else 492 else
445 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this", 493 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this",
446 SvPV_nolen (sv), SvFLAGS (sv)); 494 SvPV_nolen (sv), SvFLAGS (sv));
447} 495}
448 496
449static SV * 497static SV *
450encode_json (SV *scalar, UV flags) 498encode_json (SV *scalar, U32 flags)
451{ 499{
452 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar)) 500 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar))
453 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)"); 501 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)");
454 502
455 enc_t enc; 503 enc_t enc;
456 enc.flags = flags; 504 enc.flags = flags;
457 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 505 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
458 enc.cur = SvPVX (enc.sv); 506 enc.cur = SvPVX (enc.sv);
459 enc.end = SvEND (enc.sv); 507 enc.end = SvEND (enc.sv);
460 enc.indent = 0; 508 enc.indent = 0;
461 enc.max_depth = 0x7fffffffUL; 509 enc.maxdepth = DEC_DEPTH (flags);
462 510
463 SvPOK_only (enc.sv); 511 SvPOK_only (enc.sv);
464 encode_sv (&enc, scalar); 512 encode_sv (&enc, scalar);
465 513
466 if (!(flags & (F_ASCII | F_UTF8))) 514 if (!(flags & (F_ASCII | F_UTF8)))
481typedef struct 529typedef struct
482{ 530{
483 char *cur; // current parser pointer 531 char *cur; // current parser pointer
484 char *end; // end of input string 532 char *end; // end of input string
485 const char *err; // parse error, if != 0 533 const char *err; // parse error, if != 0
486 UV flags; // F_* 534 U32 flags; // F_*
535 U32 depth; // recursion depth
536 U32 maxdepth; // recursion depth limit
487} dec_t; 537} dec_t;
488 538
489static void 539static void
490decode_ws (dec_t *dec) 540decode_ws (dec_t *dec)
491{ 541{
500 ++dec->cur; 550 ++dec->cur;
501 } 551 }
502} 552}
503 553
504#define ERR(reason) SB dec->err = reason; goto fail; SE 554#define ERR(reason) SB dec->err = reason; goto fail; SE
555
505#define EXPECT_CH(ch) SB \ 556#define EXPECT_CH(ch) SB \
506 if (*dec->cur != ch) \ 557 if (*dec->cur != ch) \
507 ERR (# ch " expected"); \ 558 ERR (# ch " expected"); \
508 ++dec->cur; \ 559 ++dec->cur; \
509 SE 560 SE
561
562#define DEC_INC_DEPTH if (++dec->depth > dec->maxdepth) ERR ("json datastructure exceeds maximum nesting level (set a higher max_depth)")
563#define DEC_DEC_DEPTH --dec->depth
510 564
511static SV *decode_sv (dec_t *dec); 565static SV *decode_sv (dec_t *dec);
512 566
513static signed char decode_hexdigit[256]; 567static signed char decode_hexdigit[256];
514 568
619 else if (ch >= 0x80) 673 else if (ch >= 0x80)
620 { 674 {
621 --dec->cur; 675 --dec->cur;
622 676
623 STRLEN clen; 677 STRLEN clen;
624 UV uch = utf8n_to_uvuni (dec->cur, dec->end - dec->cur, &clen, UTF8_CHECK_ONLY); 678 UV uch = decode_utf8 (dec->cur, dec->end - dec->cur, &clen);
625 if (clen == (STRLEN)-1) 679 if (clen == (STRLEN)-1)
626 ERR ("malformed UTF-8 character in JSON string"); 680 ERR ("malformed UTF-8 character in JSON string");
627 681
628 do 682 do
629 {
630 *cur++ = *dec->cur++; 683 *cur++ = *dec->cur++;
631 }
632 while (--clen); 684 while (--clen);
633 685
634 utf8 = 1; 686 utf8 = 1;
635 } 687 }
636 else if (!ch)
637 ERR ("unexpected end of string while parsing json string");
638 else 688 else
689 {
690 --dec->cur;
691
692 if (!ch)
693 ERR ("unexpected end of string while parsing json string");
694 else
639 ERR ("invalid character encountered"); 695 ERR ("invalid character encountered while parsing json string");
640 696 }
641 } 697 }
642 while (cur < buf + SHORT_STRING_LEN); 698 while (cur < buf + SHORT_STRING_LEN);
643 699
644 STRLEN len = cur - buf; 700 STRLEN len = cur - buf;
645 701
758static SV * 814static SV *
759decode_av (dec_t *dec) 815decode_av (dec_t *dec)
760{ 816{
761 AV *av = newAV (); 817 AV *av = newAV ();
762 818
819 DEC_INC_DEPTH;
763 decode_ws (dec); 820 decode_ws (dec);
821
764 if (*dec->cur == ']') 822 if (*dec->cur == ']')
765 ++dec->cur; 823 ++dec->cur;
766 else 824 else
767 for (;;) 825 for (;;)
768 { 826 {
786 ERR (", or ] expected while parsing array"); 844 ERR (", or ] expected while parsing array");
787 845
788 ++dec->cur; 846 ++dec->cur;
789 } 847 }
790 848
849 DEC_DEC_DEPTH;
791 return newRV_noinc ((SV *)av); 850 return newRV_noinc ((SV *)av);
792 851
793fail: 852fail:
794 SvREFCNT_dec (av); 853 SvREFCNT_dec (av);
854 DEC_DEC_DEPTH;
795 return 0; 855 return 0;
796} 856}
797 857
798static SV * 858static SV *
799decode_hv (dec_t *dec) 859decode_hv (dec_t *dec)
800{ 860{
801 HV *hv = newHV (); 861 HV *hv = newHV ();
802 862
863 DEC_INC_DEPTH;
803 decode_ws (dec); 864 decode_ws (dec);
865
804 if (*dec->cur == '}') 866 if (*dec->cur == '}')
805 ++dec->cur; 867 ++dec->cur;
806 else 868 else
807 for (;;) 869 for (;;)
808 { 870 {
821 { 883 {
822 SvREFCNT_dec (key); 884 SvREFCNT_dec (key);
823 goto fail; 885 goto fail;
824 } 886 }
825 887
826 //TODO: optimise
827 hv_store_ent (hv, key, value, 0); 888 hv_store_ent (hv, key, value, 0);
889 SvREFCNT_dec (key);
828 890
829 decode_ws (dec); 891 decode_ws (dec);
830 892
831 if (*dec->cur == '}') 893 if (*dec->cur == '}')
832 { 894 {
838 ERR (", or } expected while parsing object/hash"); 900 ERR (", or } expected while parsing object/hash");
839 901
840 ++dec->cur; 902 ++dec->cur;
841 } 903 }
842 904
905 DEC_DEC_DEPTH;
843 return newRV_noinc ((SV *)hv); 906 return newRV_noinc ((SV *)hv);
844 907
845fail: 908fail:
846 SvREFCNT_dec (hv); 909 SvREFCNT_dec (hv);
910 DEC_DEC_DEPTH;
847 return 0; 911 return 0;
848} 912}
849 913
850static SV * 914static SV *
851decode_sv (dec_t *dec) 915decode_sv (dec_t *dec)
903fail: 967fail:
904 return 0; 968 return 0;
905} 969}
906 970
907static SV * 971static SV *
908decode_json (SV *string, UV flags) 972decode_json (SV *string, U32 flags)
909{ 973{
910 SV *sv; 974 SV *sv;
975
976 SvUPGRADE (string, SVt_PV);
911 977
912 if (flags & F_UTF8) 978 if (flags & F_UTF8)
913 sv_utf8_downgrade (string, 0); 979 sv_utf8_downgrade (string, 0);
914 else 980 else
915 sv_utf8_upgrade (string); 981 sv_utf8_upgrade (string);
916 982
917 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP 983 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
918 984
919 dec_t dec; 985 dec_t dec;
920 dec.flags = flags; 986 dec.flags = flags;
921 dec.cur = SvPVX (string); 987 dec.cur = SvPVX (string);
922 dec.end = SvEND (string); 988 dec.end = SvEND (string);
923 dec.err = 0; 989 dec.err = 0;
990 dec.depth = 0;
991 dec.maxdepth = DEC_DEPTH (dec.flags);
924 992
993 *dec.end = 0; // this should basically be a nop, too, but make sure its there
925 sv = decode_sv (&dec); 994 sv = decode_sv (&dec);
926 995
927 if (!sv) 996 if (!sv)
928 { 997 {
929 IV offset = dec.flags & F_UTF8 998 IV offset = dec.flags & F_UTF8
938 SAVEVPTR (PL_curcop); 1007 SAVEVPTR (PL_curcop);
939 PL_curcop = &cop; 1008 PL_curcop = &cop;
940 pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ); 1009 pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ);
941 LEAVE; 1010 LEAVE;
942 1011
943 croak ("%s, at character offset %d (%s)", 1012 croak ("%s, at character offset %d [\"%s\"]",
944 dec.err, 1013 dec.err,
945 (int)offset, 1014 (int)offset,
946 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); 1015 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
947 } 1016 }
948 1017
962BOOT: 1031BOOT:
963{ 1032{
964 int i; 1033 int i;
965 1034
966 memset (decode_hexdigit, 0xff, 256); 1035 memset (decode_hexdigit, 0xff, 256);
1036
967 for (i = 10; i--; ) 1037 for (i = 0; i < 256; ++i)
968 decode_hexdigit ['0' + i] = i; 1038 decode_hexdigit [i] =
969 1039 i >= '0' && i <= '9' ? i - '0'
970 for (i = 7; i--; ) 1040 : i >= 'a' && i <= 'f' ? i - 'a' + 10
971 { 1041 : i >= 'A' && i <= 'F' ? i - 'A' + 10
972 decode_hexdigit ['a' + i] = 10 + i; 1042 : -1;
973 decode_hexdigit ['A' + i] = 10 + i;
974 }
975 1043
976 json_stash = gv_stashpv ("JSON::XS", 1); 1044 json_stash = gv_stashpv ("JSON::XS", 1);
977} 1045}
978 1046
979PROTOTYPES: DISABLE 1047PROTOTYPES: DISABLE
1006 RETVAL = newSVsv (self); 1074 RETVAL = newSVsv (self);
1007} 1075}
1008 OUTPUT: 1076 OUTPUT:
1009 RETVAL 1077 RETVAL
1010 1078
1079SV *max_depth (SV *self, int max_depth = 0x80000000UL)
1080 CODE:
1081{
1082 UV *uv = SvJSON (self);
1083 UV log2 = 0;
1084
1085 if (max_depth > 0x80000000UL) max_depth = 0x80000000UL;
1086
1087 while ((1UL << log2) < max_depth)
1088 ++log2;
1089
1090 *uv = *uv & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1091
1092 RETVAL = newSVsv (self);
1093}
1094 OUTPUT:
1095 RETVAL
1096
1011void encode (SV *self, SV *scalar) 1097void encode (SV *self, SV *scalar)
1012 PPCODE: 1098 PPCODE:
1013 XPUSHs (encode_json (scalar, *SvJSON (self))); 1099 XPUSHs (encode_json (scalar, *SvJSON (self)));
1014 1100
1015void decode (SV *self, SV *jsonstr) 1101void decode (SV *self, SV *jsonstr)
1017 XPUSHs (decode_json (jsonstr, *SvJSON (self))); 1103 XPUSHs (decode_json (jsonstr, *SvJSON (self)));
1018 1104
1019PROTOTYPES: ENABLE 1105PROTOTYPES: ENABLE
1020 1106
1021void to_json (SV *scalar) 1107void to_json (SV *scalar)
1108 ALIAS:
1109 objToJson = 0
1022 PPCODE: 1110 PPCODE:
1023 XPUSHs (encode_json (scalar, F_UTF8)); 1111 XPUSHs (encode_json (scalar, F_DEFAULT | F_UTF8));
1024 1112
1025void from_json (SV *jsonstr) 1113void from_json (SV *jsonstr)
1114 ALIAS:
1115 jsonToObj = 0
1026 PPCODE: 1116 PPCODE:
1027 XPUSHs (decode_json (jsonstr, F_UTF8)); 1117 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8));
1028 1118

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines