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.17 by root, Sun Mar 25 02:46:41 2007 UTC vs.
Revision 1.27 by root, Mon Apr 9 05:09:57 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
17 24
18// F_SKIPINVALID? 25#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH))
19// F_EXECCODEREF? 26
20// F_SELFCONVERT? <=> { &__class__ => } 27// F_SELFCONVERT? <=> to_json/toJson
28// F_BLESSED? <=> { $__class__$ => }
21 29
22#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER 30#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER
23#define F_DEFAULT 0 31#define F_DEFAULT (9UL << S_MAXDEPTH)
24 32
25#define INIT_SIZE 32 // initial scalar size to be allocated 33#define INIT_SIZE 32 // initial scalar size to be allocated
26#define INDENT_STEP 3 // spaces per indentation level 34#define INDENT_STEP 3 // spaces per indentation level
27 35
28#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
73 { 81 {
74 *clen = 2; 82 *clen = 2;
75 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f); 83 return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
76 } 84 }
77 else 85 else
86 {
87 *clen = (STRLEN)-1;
78 return (UV)-1; 88 return (UV)-1;
89 }
79} 90}
80 91
81///////////////////////////////////////////////////////////////////////////// 92/////////////////////////////////////////////////////////////////////////////
82// encoder 93// encoder
83 94
85typedef struct 96typedef struct
86{ 97{
87 char *cur; // SvPVX (sv) + current output position 98 char *cur; // SvPVX (sv) + current output position
88 char *end; // SvEND (sv) 99 char *end; // SvEND (sv)
89 SV *sv; // result scalar 100 SV *sv; // result scalar
90 UV flags; // F_* 101 U32 flags; // F_*
91 int indent; // indentation level 102 U32 indent; // indentation level
92 int max_depth; // max. recursion level 103 U32 maxdepth; // max. indentation/recursion level
93} enc_t; 104} enc_t;
94 105
95static void 106static void
96need (enc_t *enc, STRLEN len) 107need (enc_t *enc, STRLEN len)
97{ 108{
98 if (enc->cur + len >= enc->end) 109 if (enc->cur + len >= enc->end)
99 { 110 {
100 STRLEN cur = enc->cur - SvPVX (enc->sv); 111 STRLEN cur = enc->cur - SvPVX (enc->sv);
101 SvGROW (enc->sv, cur + len + 1); 112 SvGROW (enc->sv, cur + len + 1);
102 enc->cur = SvPVX (enc->sv) + cur; 113 enc->cur = SvPVX (enc->sv) + cur;
103 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv); 114 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
104 } 115 }
105} 116}
106 117
107static void 118static void
108encode_ch (enc_t *enc, char ch) 119encode_ch (enc_t *enc, char ch)
265static void 276static void
266encode_av (enc_t *enc, AV *av) 277encode_av (enc_t *enc, AV *av)
267{ 278{
268 int i, len = av_len (av); 279 int i, len = av_len (av);
269 280
281 if (enc->indent >= enc->maxdepth)
282 croak ("data structure too deep (hit recursion limit)");
283
270 encode_ch (enc, '['); encode_nl (enc); 284 encode_ch (enc, '['); encode_nl (enc);
271 ++enc->indent; 285 ++enc->indent;
272 286
273 for (i = 0; i <= len; ++i) 287 for (i = 0; i <= len; ++i)
274 { 288 {
339 353
340static void 354static void
341encode_hv (enc_t *enc, HV *hv) 355encode_hv (enc_t *enc, HV *hv)
342{ 356{
343 int count, i; 357 int count, i;
358
359 if (enc->indent >= enc->maxdepth)
360 croak ("data structure too deep (hit recursion limit)");
344 361
345 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent; 362 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent;
346 363
347 if ((count = hv_iterinit (hv))) 364 if ((count = hv_iterinit (hv)))
348 { 365 {
396 413
397 encode_nl (enc); 414 encode_nl (enc);
398 } 415 }
399 else 416 else
400 { 417 {
401 SV *sv;
402 HE *he = hv_iternext (hv); 418 HE *he = hv_iternext (hv);
403 419
404 for (;;) 420 for (;;)
405 { 421 {
406 encode_indent (enc); 422 encode_indent (enc);
415 encode_nl (enc); 431 encode_nl (enc);
416 } 432 }
417 } 433 }
418 434
419 --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))));
420} 464}
421 465
422static void 466static void
423encode_sv (enc_t *enc, SV *sv) 467encode_sv (enc_t *enc, SV *sv)
424{ 468{
445 SvIsUV(sv) 489 SvIsUV(sv)
446 ? snprintf (enc->cur, 64, "%"UVuf, (UV)SvUVX (sv)) 490 ? snprintf (enc->cur, 64, "%"UVuf, (UV)SvUVX (sv))
447 : snprintf (enc->cur, 64, "%"IVdf, (IV)SvIVX (sv)); 491 : snprintf (enc->cur, 64, "%"IVdf, (IV)SvIVX (sv));
448 } 492 }
449 else if (SvROK (sv)) 493 else if (SvROK (sv))
450 { 494 encode_rv (enc, SvRV (sv));
451 SV *rv = SvRV (sv);
452
453 if (enc->indent >= enc->max_depth)
454 croak ("data structure too deep (hit recursion limit)");
455
456 switch (SvTYPE (rv))
457 {
458 case SVt_PVAV: encode_av (enc, (AV *)rv); break;
459 case SVt_PVHV: encode_hv (enc, (HV *)rv); break;
460
461 default:
462 croak ("encountered %s, but JSON can only represent references to arrays or hashes",
463 SvPV_nolen (sv));
464 }
465 }
466 else if (!SvOK (sv)) 495 else if (!SvOK (sv))
467 encode_str (enc, "null", 4, 0); 496 encode_str (enc, "null", 4, 0);
468 else 497 else
469 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",
470 SvPV_nolen (sv), SvFLAGS (sv)); 499 SvPV_nolen (sv), SvFLAGS (sv));
471} 500}
472 501
473static SV * 502static SV *
474encode_json (SV *scalar, UV flags) 503encode_json (SV *scalar, U32 flags)
475{ 504{
505 enc_t enc;
506
476 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar)) 507 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar))
477 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)");
478 509
479 enc_t enc;
480 enc.flags = flags; 510 enc.flags = flags;
481 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 511 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
482 enc.cur = SvPVX (enc.sv); 512 enc.cur = SvPVX (enc.sv);
483 enc.end = SvEND (enc.sv); 513 enc.end = SvEND (enc.sv);
484 enc.indent = 0; 514 enc.indent = 0;
485 enc.max_depth = 0x7fffffffUL; 515 enc.maxdepth = DEC_DEPTH (flags);
486 516
487 SvPOK_only (enc.sv); 517 SvPOK_only (enc.sv);
488 encode_sv (&enc, scalar); 518 encode_sv (&enc, scalar);
489 519
490 if (!(flags & (F_ASCII | F_UTF8))) 520 if (!(flags & (F_ASCII | F_UTF8)))
491 SvUTF8_on (enc.sv); 521 SvUTF8_on (enc.sv);
492 522
493 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); 523 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
524 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings
494 525
495 if (enc.flags & F_SHRINK) 526 if (enc.flags & F_SHRINK)
496 shrink (enc.sv); 527 shrink (enc.sv);
497 528
498 return enc.sv; 529 return enc.sv;
505typedef struct 536typedef struct
506{ 537{
507 char *cur; // current parser pointer 538 char *cur; // current parser pointer
508 char *end; // end of input string 539 char *end; // end of input string
509 const char *err; // parse error, if != 0 540 const char *err; // parse error, if != 0
510 UV flags; // F_* 541 U32 flags; // F_*
542 U32 depth; // recursion depth
543 U32 maxdepth; // recursion depth limit
511} dec_t; 544} dec_t;
512 545
513static void 546static void
514decode_ws (dec_t *dec) 547decode_ws (dec_t *dec)
515{ 548{
524 ++dec->cur; 557 ++dec->cur;
525 } 558 }
526} 559}
527 560
528#define ERR(reason) SB dec->err = reason; goto fail; SE 561#define ERR(reason) SB dec->err = reason; goto fail; SE
562
529#define EXPECT_CH(ch) SB \ 563#define EXPECT_CH(ch) SB \
530 if (*dec->cur != ch) \ 564 if (*dec->cur != ch) \
531 ERR (# ch " expected"); \ 565 ERR (# ch " expected"); \
532 ++dec->cur; \ 566 ++dec->cur; \
533 SE 567 SE
568
569#define DEC_INC_DEPTH if (++dec->depth > dec->maxdepth) ERR ("json datastructure exceeds maximum nesting level (set a higher max_depth)")
570#define DEC_DEC_DEPTH --dec->depth
534 571
535static SV *decode_sv (dec_t *dec); 572static SV *decode_sv (dec_t *dec);
536 573
537static signed char decode_hexdigit[256]; 574static signed char decode_hexdigit[256];
538 575
640 } 677 }
641 else if (ch >= 0x20 && ch <= 0x7f) 678 else if (ch >= 0x20 && ch <= 0x7f)
642 *cur++ = ch; 679 *cur++ = ch;
643 else if (ch >= 0x80) 680 else if (ch >= 0x80)
644 { 681 {
682 STRLEN clen;
683 UV uch;
684
645 --dec->cur; 685 --dec->cur;
646 686
647 STRLEN clen;
648 UV uch = decode_utf8 (dec->cur, dec->end - dec->cur, &clen); 687 uch = decode_utf8 (dec->cur, dec->end - dec->cur, &clen);
649 if (clen == (STRLEN)-1) 688 if (clen == (STRLEN)-1)
650 ERR ("malformed UTF-8 character in JSON string"); 689 ERR ("malformed UTF-8 character in JSON string");
651 690
652 do 691 do
653 {
654 *cur++ = *dec->cur++; 692 *cur++ = *dec->cur++;
655 }
656 while (--clen); 693 while (--clen);
657 694
658 utf8 = 1; 695 utf8 = 1;
659 } 696 }
660 else if (!ch)
661 ERR ("unexpected end of string while parsing json string");
662 else 697 else
698 {
699 --dec->cur;
700
701 if (!ch)
702 ERR ("unexpected end of string while parsing JSON string");
703 else
663 ERR ("invalid character encountered"); 704 ERR ("invalid character encountered while parsing JSON string");
664 705 }
665 } 706 }
666 while (cur < buf + SHORT_STRING_LEN); 707 while (cur < buf + SHORT_STRING_LEN);
667 708
709 {
668 STRLEN len = cur - buf; 710 STRLEN len = cur - buf;
669 711
670 if (sv) 712 if (sv)
671 { 713 {
672 SvGROW (sv, SvCUR (sv) + len + 1); 714 SvGROW (sv, SvCUR (sv) + len + 1);
673 memcpy (SvPVX (sv) + SvCUR (sv), buf, len); 715 memcpy (SvPVX (sv) + SvCUR (sv), buf, len);
674 SvCUR_set (sv, SvCUR (sv) + len); 716 SvCUR_set (sv, SvCUR (sv) + len);
675 } 717 }
676 else 718 else
677 sv = newSVpvn (buf, len); 719 sv = newSVpvn (buf, len);
720 }
678 } 721 }
679 while (*dec->cur != '"'); 722 while (*dec->cur != '"');
680 723
681 ++dec->cur; 724 ++dec->cur;
682 725
782static SV * 825static SV *
783decode_av (dec_t *dec) 826decode_av (dec_t *dec)
784{ 827{
785 AV *av = newAV (); 828 AV *av = newAV ();
786 829
830 DEC_INC_DEPTH;
787 decode_ws (dec); 831 decode_ws (dec);
832
788 if (*dec->cur == ']') 833 if (*dec->cur == ']')
789 ++dec->cur; 834 ++dec->cur;
790 else 835 else
791 for (;;) 836 for (;;)
792 { 837 {
810 ERR (", or ] expected while parsing array"); 855 ERR (", or ] expected while parsing array");
811 856
812 ++dec->cur; 857 ++dec->cur;
813 } 858 }
814 859
860 DEC_DEC_DEPTH;
815 return newRV_noinc ((SV *)av); 861 return newRV_noinc ((SV *)av);
816 862
817fail: 863fail:
818 SvREFCNT_dec (av); 864 SvREFCNT_dec (av);
865 DEC_DEC_DEPTH;
819 return 0; 866 return 0;
820} 867}
821 868
822static SV * 869static SV *
823decode_hv (dec_t *dec) 870decode_hv (dec_t *dec)
824{ 871{
825 HV *hv = newHV (); 872 HV *hv = newHV ();
826 873
874 DEC_INC_DEPTH;
827 decode_ws (dec); 875 decode_ws (dec);
876
828 if (*dec->cur == '}') 877 if (*dec->cur == '}')
829 ++dec->cur; 878 ++dec->cur;
830 else 879 else
831 for (;;) 880 for (;;)
832 { 881 {
845 { 894 {
846 SvREFCNT_dec (key); 895 SvREFCNT_dec (key);
847 goto fail; 896 goto fail;
848 } 897 }
849 898
850 //TODO: optimise
851 hv_store_ent (hv, key, value, 0); 899 hv_store_ent (hv, key, value, 0);
900 SvREFCNT_dec (key);
852 901
853 decode_ws (dec); 902 decode_ws (dec);
854 903
855 if (*dec->cur == '}') 904 if (*dec->cur == '}')
856 { 905 {
862 ERR (", or } expected while parsing object/hash"); 911 ERR (", or } expected while parsing object/hash");
863 912
864 ++dec->cur; 913 ++dec->cur;
865 } 914 }
866 915
916 DEC_DEC_DEPTH;
867 return newRV_noinc ((SV *)hv); 917 return newRV_noinc ((SV *)hv);
868 918
869fail: 919fail:
870 SvREFCNT_dec (hv); 920 SvREFCNT_dec (hv);
921 DEC_DEC_DEPTH;
871 return 0; 922 return 0;
872} 923}
873 924
874static SV * 925static SV *
875decode_sv (dec_t *dec) 926decode_sv (dec_t *dec)
918 ERR ("'null' expected"); 969 ERR ("'null' expected");
919 970
920 break; 971 break;
921 972
922 default: 973 default:
923 ERR ("malformed json string, neither array, object, number, string or atom"); 974 ERR ("malformed JSON string, neither array, object, number, string or atom");
924 break; 975 break;
925 } 976 }
926 977
927fail: 978fail:
928 return 0; 979 return 0;
929} 980}
930 981
931static SV * 982static SV *
932decode_json (SV *string, UV flags) 983decode_json (SV *string, U32 flags)
933{ 984{
985 dec_t dec;
934 SV *sv; 986 SV *sv;
987
988 SvUPGRADE (string, SVt_PV);
935 989
936 if (flags & F_UTF8) 990 if (flags & F_UTF8)
937 sv_utf8_downgrade (string, 0); 991 sv_utf8_downgrade (string, 0);
938 else 992 else
939 sv_utf8_upgrade (string); 993 sv_utf8_upgrade (string);
940 994
941 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP 995 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
942 996
943 dec_t dec;
944 dec.flags = flags; 997 dec.flags = flags;
945 dec.cur = SvPVX (string); 998 dec.cur = SvPVX (string);
946 dec.end = SvEND (string); 999 dec.end = SvEND (string);
947 dec.err = 0; 1000 dec.err = 0;
1001 dec.depth = 0;
1002 dec.maxdepth = DEC_DEPTH (dec.flags);
948 1003
1004 *dec.end = 0; // this should basically be a nop, too, but make sure its there
949 sv = decode_sv (&dec); 1005 sv = decode_sv (&dec);
950 1006
951 if (!sv) 1007 if (!sv)
952 { 1008 {
953 IV offset = dec.flags & F_UTF8 1009 IV offset = dec.flags & F_UTF8
962 SAVEVPTR (PL_curcop); 1018 SAVEVPTR (PL_curcop);
963 PL_curcop = &cop; 1019 PL_curcop = &cop;
964 pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ); 1020 pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ);
965 LEAVE; 1021 LEAVE;
966 1022
967 croak ("%s, at character offset %d (%s)", 1023 croak ("%s, at character offset %d [\"%s\"]",
968 dec.err, 1024 dec.err,
969 (int)offset, 1025 (int)offset,
970 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); 1026 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
971 } 1027 }
972 1028
986BOOT: 1042BOOT:
987{ 1043{
988 int i; 1044 int i;
989 1045
990 memset (decode_hexdigit, 0xff, 256); 1046 memset (decode_hexdigit, 0xff, 256);
1047
991 for (i = 10; i--; ) 1048 for (i = 0; i < 256; ++i)
992 decode_hexdigit ['0' + i] = i; 1049 decode_hexdigit [i] =
993 1050 i >= '0' && i <= '9' ? i - '0'
994 for (i = 7; i--; ) 1051 : i >= 'a' && i <= 'f' ? i - 'a' + 10
995 { 1052 : i >= 'A' && i <= 'F' ? i - 'A' + 10
996 decode_hexdigit ['a' + i] = 10 + i; 1053 : -1;
997 decode_hexdigit ['A' + i] = 10 + i;
998 }
999 1054
1000 json_stash = gv_stashpv ("JSON::XS", 1); 1055 json_stash = gv_stashpv ("JSON::XS", 1);
1001} 1056}
1002 1057
1003PROTOTYPES: DISABLE 1058PROTOTYPES: DISABLE
1030 RETVAL = newSVsv (self); 1085 RETVAL = newSVsv (self);
1031} 1086}
1032 OUTPUT: 1087 OUTPUT:
1033 RETVAL 1088 RETVAL
1034 1089
1090SV *max_depth (SV *self, UV max_depth = 0x80000000UL)
1091 CODE:
1092{
1093 UV *uv = SvJSON (self);
1094 UV log2 = 0;
1095
1096 if (max_depth > 0x80000000UL) max_depth = 0x80000000UL;
1097
1098 while ((1UL << log2) < max_depth)
1099 ++log2;
1100
1101 *uv = *uv & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1102
1103 RETVAL = newSVsv (self);
1104}
1105 OUTPUT:
1106 RETVAL
1107
1035void encode (SV *self, SV *scalar) 1108void encode (SV *self, SV *scalar)
1036 PPCODE: 1109 PPCODE:
1037 XPUSHs (encode_json (scalar, *SvJSON (self))); 1110 XPUSHs (encode_json (scalar, *SvJSON (self)));
1038 1111
1039void decode (SV *self, SV *jsonstr) 1112void decode (SV *self, SV *jsonstr)
1044 1117
1045void to_json (SV *scalar) 1118void to_json (SV *scalar)
1046 ALIAS: 1119 ALIAS:
1047 objToJson = 0 1120 objToJson = 0
1048 PPCODE: 1121 PPCODE:
1049 XPUSHs (encode_json (scalar, F_UTF8)); 1122 XPUSHs (encode_json (scalar, F_DEFAULT | F_UTF8));
1050 1123
1051void from_json (SV *jsonstr) 1124void from_json (SV *jsonstr)
1052 ALIAS: 1125 ALIAS:
1053 jsonToObj = 0 1126 jsonToObj = 0
1054 PPCODE: 1127 PPCODE:
1055 XPUSHs (decode_json (jsonstr, F_UTF8)); 1128 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8));
1056 1129

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines