This repository has been archived by the owner on Jun 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
BitByteArray.js
302 lines (283 loc) · 8.4 KB
/
BitByteArray.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
const BitByte = require('@zekfad/bitbyte');
/** Class representing an array of bits. */
class BitByteArray {
/**
* Create an array of bits.
* @param {number} length - Bits array length.
*/
constructor(length = 0) {
if ('[object Number]' !== Object.prototype.toString.call(length))
throw new Error('Length must be a number');
this.bytes = [];
this.length = length;
}
/**
* Set array of bits' length.
* @type {number}
*/
set length(length) {
this.bits = this.setLength(length);
}
/**
* Get array of bits' length.
* @type {number}
*/
get length() {
return this.bits;
}
/**
* Change array of bits' length.
* @param {number} length - Bits array length.
* @returns {number} - Bits array length.
*/
setLength(length) {
if ('[object Number]' !== Object.prototype.toString.call(length))
throw new Error('Length must be a number');
this.setBytes(Math.ceil(length / 8));
let actions = this.length > length
? this.length
: length;
for (let i = 0; i < actions; i++) {
if (i <= length) {
Object.defineProperty(this, i, {
get: function () {
return this.getBit(i);
},
set: function (newBit) {
this.setBit(i, newBit);
},
enumerable : true,
configurable: true,
});
} else delete this[i];
}
this.bits = length;
return length;
}
/**
* Change array of bits' count of bytes.
* @param {number} length - Count of bytes.
* @returns {number} - Count of bytes.
*/
setBytes(length) {
if ('[object Number]' !== Object.prototype.toString.call(length))
throw new Error('Length must be a number');
for (let i = 0; i < length; i++) {
if (i >= this.bytes.length)
this.bytes[i] = new BitByte();
}
/**
* Note: Because `this.bytes` is an Array, scaling down it's
* length will result in drop of unnecessary trails.
*/
return this.bytes.length = length;
}
/**
* Change bit on a given offset.
* @param {number} offset - Bit offset.
* @param {number|boolean} bit - Bit.
* @returns {number} - Bit.
*/
setBit(offset, bit) {
this.checkOffset(offset);
return this.bytes[Math.floor(offset / 8)].setBit(offset % 8, bit);
}
/**
* Get bit on a given offset.
* @param {number} offset - Bit offset.
* @returns {number} - Bit.
*/
getBit(offset) {
this.checkOffset(offset);
return this.bytes[Math.floor(offset / 8)].getBit(offset % 8);
}
/**
* Get local storage of bytes as an array of numbers.
* @returns {number[]} - Bytes array.
*/
getBytes() {
return this.bytes.map(byte => byte.getByte());
}
/**
* Get local storage of bytes as a string.
* @returns {string} - String representation of bits array.
*/
toString() {
let buffer = '',
bytes = this.getBytes();
for (let i = 0; i < bytes.length; i += 2) {
buffer += String.fromCharCode(bytes[i] + (bytes[i + 1] << 8));
}
return buffer;
}
/**
* Assign array of bits to an instance.
* @param {number[]|boolean[]} bits - Bits array.
* @param {number} offset - Assign offset.
* @returns {boolean} - Returns true if no errors found.
*/
assign(bits, offset = 0) {
if ('[object Array]' !== Object.prototype.toString.call(bits) && !(bits instanceof BitByteArray))
throw new Error('Bits must be an array or BitByteArray instance');
if ('[object Number]' !== Object.prototype.toString.call(offset))
throw new Error('Offset must be a number');
[ ...bits, ].forEach((bit, index) => this.setBit(offset + index, bit));
return true;
}
/**
* Fill local storage of bits with a provided bit.
* @param {number|boolean} bit - Bit.
* @returns {BitByteArray} - Returns instance if no errors found.
*/
fill(bit = 0) {
for (var i = 0; i < this.length; i++) {
this.setBit(i, bit);
}
return this;
}
/**
* Check if given offset is acceptable.
* Throws an exception if offset is out of bounds.
* @param {number} offset - Bit offset.
* @returns {boolean} - Returns true if given argument is acceptable.
*/
checkOffset(offset) {
if ('[object Number]' !== Object.prototype.toString.call(offset)) {
throw new Error('Offset must be a number');
}
if (offset >= this.length || offset < 0) {
throw new Error('Offset must be less than array length');
}
return true;
}
/**
* Generate bits sequence.
* @yields {number} - Next number in the sequence.
*/
*[Symbol.iterator]() {
for (let i = 0; i < this.length; i++) {
yield this.getBit(i);
}
}
}
/**
* Add left padding for provided array and return array of bits.
* @param {number[]|boolean[]} source - Source data.
* @param {number} length - Required array length.
* @returns {number[]} - Padded array.
*/
function bitsArrayLeftPad(source, length) {
let output = [];
output.length = length;
for (let i = output.length - 1; i > -1; i--) {
output[i] = !source[i - (output.length - source.length)] ^ true;
}
return output;
}
/**
* Create an array of bits from existing data.
* @param {number|number[]|boolean|boolean[]|string} source - Source data.
* @returns {BitByteArray} - Created BitByteArray.
*/
BitByteArray.from = function (source) {
let bitsArray = new BitByteArray();
switch (Object.prototype.toString.call(source)) {
case '[object Number]':
var data = (source >>> 0)
.toString(2)
.split('')
.map(i => +i),
fullBitsArray = bitsArrayLeftPad(data, 4 * 8);
bitsArray.length = fullBitsArray.length;
bitsArray.assign(fullBitsArray);
break;
case '[object Boolean]':
bitsArray.length = 1;
bitsArray.setBit(0, source);
break;
case '[object Array]':
var isBooleansArray = true,
isNumbersArary = true,
isCharsArray = true;
for (let i = 0; i < source.length; i++) {
if (true === isBooleansArray)
if ('[object Boolean]' !== Object.prototype.toString.call(source[i]))
isBooleansArray = false;
if (true === isNumbersArary)
if ('[object Number]' === Object.prototype.toString.call(source[i])
|| '[object Boolean]' === Object.prototype.toString.call(source[i])) {
if (true === isCharsArray)
isCharsArray = source[i] > -1 && source[i] <= 255;
} else {
isNumbersArary = false;
isCharsArray = false;
}
}
if (isBooleansArray) {
bitsArray.length = source.length;
bitsArray.assign(source);
} else if (isNumbersArary) {
let tempBitsArray = [];
if (isCharsArray) {
source.forEach(char => {
char ^= false;
[ ...new BitByte(char), ]
.forEach(bit => tempBitsArray.push(bit));
});
} else {
source.forEach(number => {
let binaryNumber = BitByteArray.from(number);
tempBitsArray.push(...bitsArrayLeftPad([ ...binaryNumber, ], binaryNumber.bytes.length * 8));
});
}
bitsArray.length = tempBitsArray.length;
bitsArray.assign(tempBitsArray);
}
break;
case '[object String]':
var tempBitsArray = [],
bytes = [];
for (let i = 0; i < source.length; i++) {
const code = source.charCodeAt(i);
bytes.push(code & 255, code >> 8);
}
bytes.forEach(char => {
[ ...new BitByte(char), ]
.forEach(bit => tempBitsArray.push(bit));
});
bitsArray.length = tempBitsArray.length;
bitsArray.assign(tempBitsArray);
break;
}
return bitsArray;
};
/**
* Get class representing an array of bits with index assign checks.
* @param {number} length - Bits array length.
* @returns {BitByteArray}
*/
BitByteArray.safe = function (...args) {
return new Proxy(new BitByteArray(...args), {
get: function (obj, prop) {
if ('[object Symbol]' !== Object.prototype.toString.call(prop) && !isNaN(+prop))
obj.checkOffset(+prop);
return obj[prop];
},
set: function (obj, prop, value) {
if ('[object Symbol]' !== Object.prototype.toString.call(prop) && !isNaN(+prop))
obj.checkOffset(+prop);
return obj[prop] = value;
},
});
};
/**
* Create booleans array from provided source array.
* @param {Array.} source - Source array.
* @returns {boolean[]} - Booleans array.
*/
BitByteArray.projectBitsArray = function (source) {
if ('[object Array]' !== Object.prototype.toString.call(source) && !(source instanceof BitByteArray))
throw new Error('Source must be an array or BitByteArray instance');
return [ ...source, ].map(elem => !elem ^ true);
};
module.exports = BitByteArray;