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.26 by root, Fri Apr 6 21:17:09 2007 UTC

3#include "XSUB.h" 3#include "XSUB.h"
4 4
5#include "assert.h" 5#include "assert.h"
6#include "string.h" 6#include "string.h"
7#include "stdlib.h" 7#include "stdlib.h"
8#include "stdio.h"
8 9
10#if defined(__BORLANDC__) || defined(_MSC_VER)
11# define snprintf _snprintf // C compilers have this in stdio.h
12#endif
13
9#define F_ASCII 0x00000001 14#define F_ASCII 0x00000001UL
10#define F_UTF8 0x00000002 15#define F_UTF8 0x00000002UL
11#define F_INDENT 0x00000004 16#define F_INDENT 0x00000004UL
12#define F_CANONICAL 0x00000008 17#define F_CANONICAL 0x00000008UL
13#define F_SPACE_BEFORE 0x00000010 18#define F_SPACE_BEFORE 0x00000010UL
14#define F_SPACE_AFTER 0x00000020 19#define F_SPACE_AFTER 0x00000020UL
15#define F_ALLOW_NONREF 0x00000080 20#define F_ALLOW_NONREF 0x00000080UL
16#define F_SHRINK 0x00000100 21#define F_SHRINK 0x00000100UL
22#define F_MAXDEPTH 0xf8000000UL
23#define S_MAXDEPTH 27
24
25#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH))
26
27// F_SELFCONVERT? <=> to_json/toJson
28// F_BLESSED? <=> { $__class__$ => }
17 29
18#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER 30#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER
19#define F_DEFAULT 0 31#define F_DEFAULT (9UL << S_MAXDEPTH)
20 32
21#define INIT_SIZE 32 // initial scalar size to be allocated 33#define INIT_SIZE 32 // initial scalar size to be allocated
22#define INDENT_STEP 3 // spaces per indentation level 34#define INDENT_STEP 3 // spaces per indentation level
23 35
24#define UTF8_MAX_LEN 11 // for perls UTF-X: max. number of octets per character 36#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 37#define SHORT_STRING_LEN 512 // special-case strings of up to this size
26 38
27#define SB do { 39#define SB do {
28#define SE } while (0) 40#define SE } while (0)
29 41
30static HV *json_stash; // JSON::XS:: 42static HV *json_stash; // JSON::XS::
53 SvPV_renew (sv, SvCUR (sv) + 1); 65 SvPV_renew (sv, SvCUR (sv) + 1);
54#endif 66#endif
55 } 67 }
56} 68}
57 69
70// decode an utf-8 character and return it, or (UV)-1 in
71// case of an error.
72// we special-case "safe" characters from U+80 .. U+7FF,
73// but use the very good perl function to parse anything else.
74// note that we never call this function for a ascii codepoints
75static UV
76decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
77{
78 if (s[0] > 0xdf || s[0] < 0xc2)
79 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY);
80 else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf)
81 {
82 *clen = 2;
83 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
84 }
85 else
86 {
87 *clen = (STRLEN)-1;
88 return (UV)-1;
89 }
90}
91
58///////////////////////////////////////////////////////////////////////////// 92/////////////////////////////////////////////////////////////////////////////
59// encoder 93// encoder
60 94
61// structure used for encoding JSON 95// structure used for encoding JSON
62typedef struct 96typedef struct
63{ 97{
64 char *cur; // SvPVX (sv) + current output position 98 char *cur; // SvPVX (sv) + current output position
65 char *end; // SvEND (sv) 99 char *end; // SvEND (sv)
66 SV *sv; // result scalar 100 SV *sv; // result scalar
67 UV flags; // F_* 101 U32 flags; // F_*
68 int indent; // indentation level 102 U32 indent; // indentation level
69 int max_depth; // max. recursion level 103 U32 maxdepth; // max. indentation/recursion level
70} enc_t; 104} enc_t;
71 105
72static void 106static void
73need (enc_t *enc, STRLEN len) 107need (enc_t *enc, STRLEN len)
74{ 108{
133 STRLEN clen; 167 STRLEN clen;
134 UV uch; 168 UV uch;
135 169
136 if (is_utf8) 170 if (is_utf8)
137 { 171 {
138 uch = utf8n_to_uvuni (str, end - str, &clen, UTF8_CHECK_ONLY); 172 //uch = utf8n_to_uvuni (str, end - str, &clen, UTF8_CHECK_ONLY);
173 uch = decode_utf8 (str, end - str, &clen);
139 if (clen == (STRLEN)-1) 174 if (clen == (STRLEN)-1)
140 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str); 175 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str);
141 } 176 }
142 else 177 else
143 { 178 {
241static void 276static void
242encode_av (enc_t *enc, AV *av) 277encode_av (enc_t *enc, AV *av)
243{ 278{
244 int i, len = av_len (av); 279 int i, len = av_len (av);
245 280
281 if (enc->indent >= enc->maxdepth)
282 croak ("data structure too deep (hit recursion limit)");
283
246 encode_ch (enc, '['); encode_nl (enc); 284 encode_ch (enc, '['); encode_nl (enc);
247 ++enc->indent; 285 ++enc->indent;
248 286
249 for (i = 0; i <= len; ++i) 287 for (i = 0; i <= len; ++i)
250 { 288 {
315 353
316static void 354static void
317encode_hv (enc_t *enc, HV *hv) 355encode_hv (enc_t *enc, HV *hv)
318{ 356{
319 int count, i; 357 int count, i;
358
359 if (enc->indent >= enc->maxdepth)
360 croak ("data structure too deep (hit recursion limit)");
320 361
321 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent; 362 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent;
322 363
323 if ((count = hv_iterinit (hv))) 364 if ((count = hv_iterinit (hv)))
324 { 365 {
372 413
373 encode_nl (enc); 414 encode_nl (enc);
374 } 415 }
375 else 416 else
376 { 417 {
377 SV *sv;
378 HE *he = hv_iternext (hv); 418 HE *he = hv_iternext (hv);
379 419
380 for (;;) 420 for (;;)
381 { 421 {
382 encode_indent (enc); 422 encode_indent (enc);
391 encode_nl (enc); 431 encode_nl (enc);
392 } 432 }
393 } 433 }
394 434
395 --enc->indent; encode_indent (enc); encode_ch (enc, '}'); 435 --enc->indent; encode_indent (enc); encode_ch (enc, '}');
436}
437
438// encode objects, arrays and special \0=false and \1=true values.
439static void
440encode_rv (enc_t *enc, SV *sv)
441{
442 svtype svt;
443
444 SvGETMAGIC (sv);
445 svt = SvTYPE (sv);
446
447 if (svt == SVt_PVHV)
448 encode_hv (enc, (HV *)sv);
449 else if (svt == SVt_PVAV)
450 encode_av (enc, (AV *)sv);
451 else if (svt < SVt_PVAV)
452 {
453 if (SvNIOK (sv) && SvIV (sv) == 0)
454 encode_str (enc, "false", 5, 0);
455 else if (SvNIOK (sv) && SvIV (sv) == 1)
456 encode_str (enc, "true", 4, 0);
457 else
458 croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1",
459 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
460 }
461 else
462 croak ("encountered %s, but JSON can only represent references to arrays or hashes",
463 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
396} 464}
397 465
398static void 466static void
399encode_sv (enc_t *enc, SV *sv) 467encode_sv (enc_t *enc, SV *sv)
400{ 468{
421 SvIsUV(sv) 489 SvIsUV(sv)
422 ? snprintf (enc->cur, 64, "%"UVuf, (UV)SvUVX (sv)) 490 ? snprintf (enc->cur, 64, "%"UVuf, (UV)SvUVX (sv))
423 : snprintf (enc->cur, 64, "%"IVdf, (IV)SvIVX (sv)); 491 : snprintf (enc->cur, 64, "%"IVdf, (IV)SvIVX (sv));
424 } 492 }
425 else if (SvROK (sv)) 493 else if (SvROK (sv))
426 { 494 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)) 495 else if (!SvOK (sv))
443 encode_str (enc, "null", 4, 0); 496 encode_str (enc, "null", 4, 0);
444 else 497 else
445 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this", 498 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this",
446 SvPV_nolen (sv), SvFLAGS (sv)); 499 SvPV_nolen (sv), SvFLAGS (sv));
447} 500}
448 501
449static SV * 502static SV *
450encode_json (SV *scalar, UV flags) 503encode_json (SV *scalar, U32 flags)
451{ 504{
505 enc_t enc;
506
452 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar)) 507 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar))
453 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)"); 508 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)");
454 509
455 enc_t enc;
456 enc.flags = flags; 510 enc.flags = flags;
457 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 511 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
458 enc.cur = SvPVX (enc.sv); 512 enc.cur = SvPVX (enc.sv);
459 enc.end = SvEND (enc.sv); 513 enc.end = SvEND (enc.sv);
460 enc.indent = 0; 514 enc.indent = 0;
461 enc.max_depth = 0x7fffffffUL; 515 enc.maxdepth = DEC_DEPTH (flags);
462 516
463 SvPOK_only (enc.sv); 517 SvPOK_only (enc.sv);
464 encode_sv (&enc, scalar); 518 encode_sv (&enc, scalar);
465 519
466 if (!(flags & (F_ASCII | F_UTF8))) 520 if (!(flags & (F_ASCII | F_UTF8)))
481typedef struct 535typedef struct
482{ 536{
483 char *cur; // current parser pointer 537 char *cur; // current parser pointer
484 char *end; // end of input string 538 char *end; // end of input string
485 const char *err; // parse error, if != 0 539 const char *err; // parse error, if != 0
486 UV flags; // F_* 540 U32 flags; // F_*
541 U32 depth; // recursion depth
542 U32 maxdepth; // recursion depth limit
487} dec_t; 543} dec_t;
488 544
489static void 545static void
490decode_ws (dec_t *dec) 546decode_ws (dec_t *dec)
491{ 547{
500 ++dec->cur; 556 ++dec->cur;
501 } 557 }
502} 558}
503 559
504#define ERR(reason) SB dec->err = reason; goto fail; SE 560#define ERR(reason) SB dec->err = reason; goto fail; SE
561
505#define EXPECT_CH(ch) SB \ 562#define EXPECT_CH(ch) SB \
506 if (*dec->cur != ch) \ 563 if (*dec->cur != ch) \
507 ERR (# ch " expected"); \ 564 ERR (# ch " expected"); \
508 ++dec->cur; \ 565 ++dec->cur; \
509 SE 566 SE
567
568#define DEC_INC_DEPTH if (++dec->depth > dec->maxdepth) ERR ("json datastructure exceeds maximum nesting level (set a higher max_depth)")
569#define DEC_DEC_DEPTH --dec->depth
510 570
511static SV *decode_sv (dec_t *dec); 571static SV *decode_sv (dec_t *dec);
512 572
513static signed char decode_hexdigit[256]; 573static signed char decode_hexdigit[256];
514 574
616 } 676 }
617 else if (ch >= 0x20 && ch <= 0x7f) 677 else if (ch >= 0x20 && ch <= 0x7f)
618 *cur++ = ch; 678 *cur++ = ch;
619 else if (ch >= 0x80) 679 else if (ch >= 0x80)
620 { 680 {
681 STRLEN clen;
682 UV uch;
683
621 --dec->cur; 684 --dec->cur;
622 685
623 STRLEN clen;
624 UV uch = utf8n_to_uvuni (dec->cur, dec->end - dec->cur, &clen, UTF8_CHECK_ONLY); 686 uch = decode_utf8 (dec->cur, dec->end - dec->cur, &clen);
625 if (clen == (STRLEN)-1) 687 if (clen == (STRLEN)-1)
626 ERR ("malformed UTF-8 character in JSON string"); 688 ERR ("malformed UTF-8 character in JSON string");
627 689
628 do 690 do
629 {
630 *cur++ = *dec->cur++; 691 *cur++ = *dec->cur++;
631 }
632 while (--clen); 692 while (--clen);
633 693
634 utf8 = 1; 694 utf8 = 1;
635 } 695 }
636 else if (!ch)
637 ERR ("unexpected end of string while parsing json string");
638 else 696 else
697 {
698 --dec->cur;
699
700 if (!ch)
701 ERR ("unexpected end of string while parsing JSON string");
702 else
639 ERR ("invalid character encountered"); 703 ERR ("invalid character encountered while parsing JSON string");
640 704 }
641 } 705 }
642 while (cur < buf + SHORT_STRING_LEN); 706 while (cur < buf + SHORT_STRING_LEN);
643 707
708 {
644 STRLEN len = cur - buf; 709 STRLEN len = cur - buf;
645 710
646 if (sv) 711 if (sv)
647 { 712 {
648 SvGROW (sv, SvCUR (sv) + len + 1); 713 SvGROW (sv, SvCUR (sv) + len + 1);
649 memcpy (SvPVX (sv) + SvCUR (sv), buf, len); 714 memcpy (SvPVX (sv) + SvCUR (sv), buf, len);
650 SvCUR_set (sv, SvCUR (sv) + len); 715 SvCUR_set (sv, SvCUR (sv) + len);
651 } 716 }
652 else 717 else
653 sv = newSVpvn (buf, len); 718 sv = newSVpvn (buf, len);
719 }
654 } 720 }
655 while (*dec->cur != '"'); 721 while (*dec->cur != '"');
656 722
657 ++dec->cur; 723 ++dec->cur;
658 724
758static SV * 824static SV *
759decode_av (dec_t *dec) 825decode_av (dec_t *dec)
760{ 826{
761 AV *av = newAV (); 827 AV *av = newAV ();
762 828
829 DEC_INC_DEPTH;
763 decode_ws (dec); 830 decode_ws (dec);
831
764 if (*dec->cur == ']') 832 if (*dec->cur == ']')
765 ++dec->cur; 833 ++dec->cur;
766 else 834 else
767 for (;;) 835 for (;;)
768 { 836 {
786 ERR (", or ] expected while parsing array"); 854 ERR (", or ] expected while parsing array");
787 855
788 ++dec->cur; 856 ++dec->cur;
789 } 857 }
790 858
859 DEC_DEC_DEPTH;
791 return newRV_noinc ((SV *)av); 860 return newRV_noinc ((SV *)av);
792 861
793fail: 862fail:
794 SvREFCNT_dec (av); 863 SvREFCNT_dec (av);
864 DEC_DEC_DEPTH;
795 return 0; 865 return 0;
796} 866}
797 867
798static SV * 868static SV *
799decode_hv (dec_t *dec) 869decode_hv (dec_t *dec)
800{ 870{
801 HV *hv = newHV (); 871 HV *hv = newHV ();
802 872
873 DEC_INC_DEPTH;
803 decode_ws (dec); 874 decode_ws (dec);
875
804 if (*dec->cur == '}') 876 if (*dec->cur == '}')
805 ++dec->cur; 877 ++dec->cur;
806 else 878 else
807 for (;;) 879 for (;;)
808 { 880 {
821 { 893 {
822 SvREFCNT_dec (key); 894 SvREFCNT_dec (key);
823 goto fail; 895 goto fail;
824 } 896 }
825 897
826 //TODO: optimise
827 hv_store_ent (hv, key, value, 0); 898 hv_store_ent (hv, key, value, 0);
899 SvREFCNT_dec (key);
828 900
829 decode_ws (dec); 901 decode_ws (dec);
830 902
831 if (*dec->cur == '}') 903 if (*dec->cur == '}')
832 { 904 {
838 ERR (", or } expected while parsing object/hash"); 910 ERR (", or } expected while parsing object/hash");
839 911
840 ++dec->cur; 912 ++dec->cur;
841 } 913 }
842 914
915 DEC_DEC_DEPTH;
843 return newRV_noinc ((SV *)hv); 916 return newRV_noinc ((SV *)hv);
844 917
845fail: 918fail:
846 SvREFCNT_dec (hv); 919 SvREFCNT_dec (hv);
920 DEC_DEC_DEPTH;
847 return 0; 921 return 0;
848} 922}
849 923
850static SV * 924static SV *
851decode_sv (dec_t *dec) 925decode_sv (dec_t *dec)
894 ERR ("'null' expected"); 968 ERR ("'null' expected");
895 969
896 break; 970 break;
897 971
898 default: 972 default:
899 ERR ("malformed json string, neither array, object, number, string or atom"); 973 ERR ("malformed JSON string, neither array, object, number, string or atom");
900 break; 974 break;
901 } 975 }
902 976
903fail: 977fail:
904 return 0; 978 return 0;
905} 979}
906 980
907static SV * 981static SV *
908decode_json (SV *string, UV flags) 982decode_json (SV *string, U32 flags)
909{ 983{
984 dec_t dec;
910 SV *sv; 985 SV *sv;
986
987 SvUPGRADE (string, SVt_PV);
911 988
912 if (flags & F_UTF8) 989 if (flags & F_UTF8)
913 sv_utf8_downgrade (string, 0); 990 sv_utf8_downgrade (string, 0);
914 else 991 else
915 sv_utf8_upgrade (string); 992 sv_utf8_upgrade (string);
916 993
917 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP 994 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
918 995
919 dec_t dec;
920 dec.flags = flags; 996 dec.flags = flags;
921 dec.cur = SvPVX (string); 997 dec.cur = SvPVX (string);
922 dec.end = SvEND (string); 998 dec.end = SvEND (string);
923 dec.err = 0; 999 dec.err = 0;
1000 dec.depth = 0;
1001 dec.maxdepth = DEC_DEPTH (dec.flags);
924 1002
1003 *dec.end = 0; // this should basically be a nop, too, but make sure its there
925 sv = decode_sv (&dec); 1004 sv = decode_sv (&dec);
926 1005
927 if (!sv) 1006 if (!sv)
928 { 1007 {
929 IV offset = dec.flags & F_UTF8 1008 IV offset = dec.flags & F_UTF8
938 SAVEVPTR (PL_curcop); 1017 SAVEVPTR (PL_curcop);
939 PL_curcop = &cop; 1018 PL_curcop = &cop;
940 pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ); 1019 pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ);
941 LEAVE; 1020 LEAVE;
942 1021
943 croak ("%s, at character offset %d (%s)", 1022 croak ("%s, at character offset %d [\"%s\"]",
944 dec.err, 1023 dec.err,
945 (int)offset, 1024 (int)offset,
946 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); 1025 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
947 } 1026 }
948 1027
962BOOT: 1041BOOT:
963{ 1042{
964 int i; 1043 int i;
965 1044
966 memset (decode_hexdigit, 0xff, 256); 1045 memset (decode_hexdigit, 0xff, 256);
1046
967 for (i = 10; i--; ) 1047 for (i = 0; i < 256; ++i)
968 decode_hexdigit ['0' + i] = i; 1048 decode_hexdigit [i] =
969 1049 i >= '0' && i <= '9' ? i - '0'
970 for (i = 7; i--; ) 1050 : i >= 'a' && i <= 'f' ? i - 'a' + 10
971 { 1051 : i >= 'A' && i <= 'F' ? i - 'A' + 10
972 decode_hexdigit ['a' + i] = 10 + i; 1052 : -1;
973 decode_hexdigit ['A' + i] = 10 + i;
974 }
975 1053
976 json_stash = gv_stashpv ("JSON::XS", 1); 1054 json_stash = gv_stashpv ("JSON::XS", 1);
977} 1055}
978 1056
979PROTOTYPES: DISABLE 1057PROTOTYPES: DISABLE
1006 RETVAL = newSVsv (self); 1084 RETVAL = newSVsv (self);
1007} 1085}
1008 OUTPUT: 1086 OUTPUT:
1009 RETVAL 1087 RETVAL
1010 1088
1089SV *max_depth (SV *self, UV max_depth = 0x80000000UL)
1090 CODE:
1091{
1092 UV *uv = SvJSON (self);
1093 UV log2 = 0;
1094
1095 if (max_depth > 0x80000000UL) max_depth = 0x80000000UL;
1096
1097 while ((1UL << log2) < max_depth)
1098 ++log2;
1099
1100 *uv = *uv & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1101
1102 RETVAL = newSVsv (self);
1103}
1104 OUTPUT:
1105 RETVAL
1106
1011void encode (SV *self, SV *scalar) 1107void encode (SV *self, SV *scalar)
1012 PPCODE: 1108 PPCODE:
1013 XPUSHs (encode_json (scalar, *SvJSON (self))); 1109 XPUSHs (encode_json (scalar, *SvJSON (self)));
1014 1110
1015void decode (SV *self, SV *jsonstr) 1111void decode (SV *self, SV *jsonstr)
1017 XPUSHs (decode_json (jsonstr, *SvJSON (self))); 1113 XPUSHs (decode_json (jsonstr, *SvJSON (self)));
1018 1114
1019PROTOTYPES: ENABLE 1115PROTOTYPES: ENABLE
1020 1116
1021void to_json (SV *scalar) 1117void to_json (SV *scalar)
1118 ALIAS:
1119 objToJson = 0
1022 PPCODE: 1120 PPCODE:
1023 XPUSHs (encode_json (scalar, F_UTF8)); 1121 XPUSHs (encode_json (scalar, F_DEFAULT | F_UTF8));
1024 1122
1025void from_json (SV *jsonstr) 1123void from_json (SV *jsonstr)
1124 ALIAS:
1125 jsonToObj = 0
1026 PPCODE: 1126 PPCODE:
1027 XPUSHs (decode_json (jsonstr, F_UTF8)); 1127 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8));
1028 1128

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines