blob: 077c7e216a59b04a67ab568175ba0daeff65e0be [file] [log] [blame]
Meki Cherkaouib0365a72012-02-18 00:59:57 -08001
2var XML_EXT = 0x00;
3
4var XML_TAG = 0x01;
5
6var XML_DTAG = 0x02;
7
8var XML_ATTR = 0x03;
9
10var XML_DATTR = 0x04;
11
12var XML_BLOB = 0x05;
13
14var XML_UDATA = 0x06;
15
16var XML_CLOSE = 0x0;
17
18var XML_SUBTYPE_PROCESSING_INSTRUCTIONS = 16;
19
20
21var XML_TT_BITS = 3;
22var XML_TT_MASK = ((1 << XML_TT_BITS) - 1);
23var XML_TT_VAL_BITS = XML_TT_BITS + 1;
24var XML_TT_VAL_MASK = ((1 << (XML_TT_VAL_BITS)) - 1);
25var XML_REG_VAL_BITS = 7;
26var XML_REG_VAL_MASK = ((1 << XML_REG_VAL_BITS) - 1);
27var XML_TT_NO_MORE = (1 << XML_REG_VAL_BITS); // 0x80
28var BYTE_MASK = 0xFF;
29var LONG_BYTES = 8;
30var LONG_BITS = 64;
31
32var bits_11 = 0x0000007FFL;
33var bits_18 = 0x00003FFFFL;
34var bits_32 = 0x0FFFFFFFFL;
35
36
37var TypeAndVal = function TypeAndVal(_type,_val) {
38 this.type = _type;
39 this.val = _val;
40
41};
42exports.TypeAndVal = TypeAndVal;
43
44var BinaryXMLCodec = function BinaryXMLCodec(){
45
46 this.CODEC_NAME = "Binary";
47
48
49
50};
51
52exports.BinaryXMLCodec = BinaryXMLCodec;
53
54
55
56BinaryXMLCodec.prototype.encodeTypeAndVal = function(
57 //int
58 type,
59 //long
60 val,
61 //byte []
62 buf,
63 //int
64 offset) {
65
66 if ((type > XML_UDATA) || (type < 0) || (val < 0)) {
67 throw new Exception("Tag and value must be positive, and tag valid.");
68 }
69
70 // Encode backwards. Calculate how many bytes we need:
71 int numEncodingBytes = numEncodingBytes(val);
72
73 if ((offset + numEncodingBytes) > buf.length) {
74 throw new Exception("Buffer space of " + (buf.length-offset) +
75 " bytes insufficient to hold " +
76 numEncodingBytes + " of encoded type and value.");
77 }
78
79
80 buf[offset + numEncodingBytes - 1] =
81 (BYTE_MASK &
82 (((XML_TT_MASK & type) |
83 ((XML_TT_VAL_MASK & val) << XML_TT_BITS))) |
84 XML_TT_NO_MORE);
85 val = val >>> XML_TT_VAL_BITS;;
86
87 int i = offset + numEncodingBytes - 2;
88 while ((0 != val) && (i >= offset)) {
89 buf[i] = (BYTE_MASK &
90 (val & XML_REG_VAL_MASK));
91 val = val >>> XML_REG_VAL_BITS;
92 --i;
93 }
94
95 return numEncodingBytes;
96};
97
98BinaryXMLCodec.prototype.decodeTypeAndVal = function(
99 /*InputStream*/
100 istream) {
101
102 int next;
103 int type = -1;
104 long val = 0;
105 boolean more = true;
106
107 do {
108 next = istream.read();
109
110 if (next < 0) {
111 return null;
112 }
113
114 if ((0 == next) && (0 == val)) {
115 return null;
116 }
117
118 more = (0 == (next & XML_TT_NO_MORE));
119
120 if (more) {
121 val = val << XML_REG_VAL_BITS;
122 val |= (next & XML_REG_VAL_MASK);
123 } else {
124
125 type = next & XML_TT_MASK;
126 val = val << XML_TT_VAL_BITS;
127 val |= ((next >>> XML_TT_BITS) & XML_TT_VAL_MASK);
128 }
129
130 } while (more);
131
132 return new TypeAndVal(type, val);
133};
134
135//TODO