-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgibbon.ts
507 lines (470 loc) · 17.3 KB
/
gibbon.ts
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
import { GibbonProcessor } from "./gibbon-processor.js";
/**
* A Gibbon
* @param {ArrayBuffer} arrayBuffer - allocate this Gibbon with some working memory
*/
export class Gibbon {
arrayBuffer: ArrayBuffer;
dataView: DataView;
constructor(arrayBuffer: ArrayBuffer) {
this.arrayBuffer = arrayBuffer;
this.dataView = new DataView(this.arrayBuffer);
}
/**
* Compare two gibbon instances on data contents
*
* @param {Gibbon} gibbon - instance of <b>a</b> Gibbon
* @returns {boolean} if instance (or contents) are the same
*/
equals(gibbon: Gibbon): boolean {
let same = false;
const arrayBuffer = gibbon.arrayBuffer;
const thisArrayBuffer = this.arrayBuffer;
if (thisArrayBuffer === arrayBuffer) {
same = true;
} else {
const thisDataView = this.dataView;
const dataView = gibbon.dataView;
const byteLength = Math.max(
thisArrayBuffer.byteLength,
arrayBuffer.byteLength
);
let result = true;
for (let i = 0; i < byteLength && result; i++) {
const value1 =
i < thisDataView.byteLength
? thisDataView.getUint8(i)
: 0x0;
const value2 =
i < dataView.byteLength ? dataView.getUint8(i) : 0x0;
if (value1 !== value2) {
result = false;
}
}
same = result;
}
return same;
}
/**
* This method analyzes every bit value in this gibbon and creates the corresponding <br>
* position array where bits are logical true.
*
* @example
* ```
*
* // Initialize a Gibbon (2 bytes)
* const gibbon = Gibbon.create(2);
*
* // Pre set some bit positions
* gibbon.setPosition(1)
* .setPosition(2)
* .setPosition(3)
* .setPosition(4)
* .setPosition(5)
* .setPosition(6)
* .setPosition(7)
* .setPosition(8)
* .setPosition(10);
*
* gibbon.getPositionsArray(); // returns: [1, 2, 3, 4, 5, 6, 7, 8, 10]
* ```
*
* @returns {Array} Which contains bit positions from this gibbon, which are logical set to true
*/
getPositionsArray(): Array<number> {
const dataView = this.dataView;
const byteLength = this.arrayBuffer.byteLength;
const positions = [];
for (let byteNo = 0; byteNo < byteLength; byteNo++) {
const value = dataView.getUint8(byteNo);
for (let bitPos = 0; bitPos < 8; bitPos++) {
const posValue = GibbonProcessor.isTrue(value, bitPos);
if (posValue) {
positions.push(byteNo * 8 + bitPos + 1);
}
}
}
return positions;
}
/**
* Set bit: true according to integer position in the Gibbon <br>
* <i>Note: Starting from 1</i>
* @throws {Error} Position can't exceed data view bounds.
* @param {Number} position - unsigned integer value
* @returns {Gibbon} - For chaining purposes
*/
setPosition(position: number): Gibbon {
const bitBytePosition = GibbonProcessor.getByteNoAndBitPos(position);
const dataViewBounds = this.dataView.byteLength;
if (bitBytePosition.byteNo < dataViewBounds) {
let byte = this.dataView.getUint8(bitBytePosition.byteNo);
byte = GibbonProcessor.setBit(byte, bitBytePosition.bitPos);
this.dataView.setUint8(bitBytePosition.byteNo, byte);
} else {
// Because we can't exceed the amount of allocated bytes,
// Please ensure position ends within the allocated memory
throw new Error("Illegal position");
}
return this;
}
/**
* Set bit: false according to integer position
* Note: Starting from 1
* @param {Number} position - unsigned integer value
* @returns {Gibbon}
*/
clearPosition(position: number): Gibbon {
const bitBytePosition = GibbonProcessor.getByteNoAndBitPos(position);
let byte = this.dataView.getUint8(bitBytePosition.byteNo);
byte = GibbonProcessor.clearBit(byte, bitBytePosition.bitPos);
this.dataView.setUint8(bitBytePosition.byteNo, byte);
return this;
}
/**
* Toggle bit value true => false, false => true
* @example
* ```
* const gibbon = Gibbon.create(2);
* gibbon.changePosition(1, true);
*
* gibbon.isPosition(1); // true
* ```
* @param {Number} position - unsigned integer value
* @returns {Gibbon}
*/
togglePosition(position: number): Gibbon {
const bitBytePosition = GibbonProcessor.getByteNoAndBitPos(position);
let byte = this.dataView.getUint8(bitBytePosition.byteNo);
byte = GibbonProcessor.toggleBit(byte, bitBytePosition.bitPos);
this.dataView.setUint8(bitBytePosition.byteNo, byte);
return this;
}
/**
* Set value for a bit on position
*
* @example
* ```
* const gibbon = Gibbon.create(2);
* gibbon.changePosition(1, true);
*
* gibbon.isPosition(1); // returns true
* ```
*
* @param {Number} position - unsigned integer value
* @param {boolean} [on] - Optional set true or false (default : false)
* @returns {Gibbon} - Return itself for chaining purposes
*/
changePosition(position: number, on = false): Gibbon {
const bitBytePosition = GibbonProcessor.getByteNoAndBitPos(position);
let byte = this.dataView.getUint8(bitBytePosition.byteNo);
byte = GibbonProcessor.changeBit(byte, bitBytePosition.bitPos, on);
this.dataView.setUint8(bitBytePosition.byteNo, byte);
return this;
}
/**
* Checks if a value is true or false on a specific position
*
*
* @example
* ```
* const gibbon = Gibbon.create(2);
* gibbon.setPosition(1);
*
* gibbon.isPosition(1); // returns true
* ```
* @param {Number} position - unsigned integer value
* @returns {boolean} if membership is set
*/
isPosition(position: number): boolean {
const bitBytePosition = GibbonProcessor.getByteNoAndBitPos(position);
const byte = this.dataView.getUint8(bitBytePosition.byteNo);
return GibbonProcessor.isTrue(byte, bitBytePosition.bitPos);
}
/**
* Merge with incomming bytes
* @param {Gibbon} gibbon
* @returns {Gibbon} - Return itself for chaining purposes
*/
mergeWithGibbon(gibbon: Gibbon): Gibbon {
const { dataView: thisDataView } = this;
const { dataView: incomingDataView } = gibbon;
if (incomingDataView.byteLength > thisDataView.byteLength) {
throw new Error(`Incoming Gibbon is too big`);
}
// Pick the smallest one at least
const byteLength = Math.min(
thisDataView.byteLength,
incomingDataView.byteLength
);
for (let i = 0; i < byteLength; i++) {
const thisByte = thisDataView.getUint8(i);
const incommingByte = incomingDataView.getUint8(i);
thisDataView.setUint8(i, thisByte | incommingByte);
}
return this;
}
/**
* Compare 2 gibbons and see if this gibbon shares all given bits
* @param {Gibbon} gibbon
* @returns {boolean}
*/
hasAllFromGibbon(gibbon: Gibbon): boolean {
const { byteLength: thisByteLength } = this.dataView;
const { byteLength: givenByteLength } = gibbon.dataView;
const minByteLength = Math.min(thisByteLength, givenByteLength);
let hasAllBits = true;
for (let i = 0; i < minByteLength && hasAllBits; i++) {
const byte1 = this.dataView.getUint8(i);
const byte2 = gibbon.dataView.getUint8(i);
hasAllBits = GibbonProcessor.hasAllBits({ byte1, byte2 });
}
return hasAllBits;
}
/**
* Compares all given positions
* - A positive position means this position should be set logical '1'
* - A negative position means this position should be set logical '0'
*
* When one wants to check on bit positions outside the memory bounds (dataViewBounds), <br>
* method wil return early with `false`.
*
*
* @example
* ```
* // Initialize a gibbon with 2 bytes
* const gibbon = Gibbon.create(2);
* // Set 2 bit positions to logical '1'
* gibbon.setPosition(1).setPosition(2);
*
* gibbon.hasAllFromPositions([1, 2]); // true
* ```
*
* @example
* ```
* // Set 2 bit positions to logical '1' then the first bit position back to '0'
* const gibbon = Gibbon.create(2);
* gibbon.setPosition(1).setPosition(2).togglePosition(1);
*
* gibbon.hasAllFromPositions([-1, 2]); // true
* ```
*
* @param {Array<Number>} positionArray - containing signed integer values (representing bit positions)
* @return {boolean} true when all positions correspondent to the given indexes
* @throws {TypeError} if positionArray is not an instance of array
*
*/
hasAllFromPositions(positionArray: Array<number> = []): boolean {
// Remove duplicate values from shallow copy
const positions = Array.from(new Set(positionArray));
// Create an internal Gibbon to reuse `hasAnyFromGibbon`
const incomingGibbon = Gibbon.create(
this.dataView.byteLength
).setAllFromPositions(positions);
return this.hasAllFromGibbon(incomingGibbon);
}
/**
* Compare 2 gibbons and see if this gibbon has at least one bit alike
* @param {Gibbon} gibbon
* @returns {boolean}
*/
hasAnyFromGibbon(gibbon: Gibbon): boolean {
const { byteLength: thisByteLength } = this.dataView;
const { byteLength: givenByteLength } = gibbon.dataView;
const byteLength = Math.min(thisByteLength, givenByteLength);
let hasAny = false;
for (let i = 0; i < byteLength && !hasAny; i++) {
const byte1 = this.dataView.getUint8(i);
const byte2 = gibbon.dataView.getUint8(i);
hasAny = GibbonProcessor.hasAnyBits({ byte1, byte2 });
}
return hasAny;
}
/**
* Compares the given positions<br>
* - A positive position means this position should be set logical '1'<br>
* - A negative position means this position should be set logical '0'<br><br>
*
* When any of the positions conforms to logical '1' (true), we return `true` early.<br><br>
*
* When one wants to check on bit positions outside the memory bounds (dataViewBounds), <br>
* method wil return early with `false`.
*
*
* @example
* ```
* // Initialize a gibbon with 2 bytes
* const gibbon = Gibbon.create(2);
* // Set 3 bit positions to logical '1'
* gibbon.setPosition(1).setPosition(2).setPosition(10);
*
* gibbon.hasAnyFromPositions([1, 9]); // true
* ```
* @example
* ```
* // Set 2 bit positions to logical '1' then the first bit position back to '0'
* const gibbon = Gibbon.create(2);
* gibbon.setPosition(1).setPosition(2),togglePosition(1);
*
* gibbon.hasAllFromPositions([-1, 100]); // true
* ```
* @param {Array<Number>} positionArray - containing signed integer values (representing bit positions)
* @return {boolean} true when one of these positions correspond
* @throws {TypeError} if positionArray is not an instance of array
*/
hasAnyFromPositions(positionArray: Array<number> = []): boolean {
// Remove duplicate values and sort
const positions = Array.from(new Set(positionArray));
// Create an internal Gibbon to reuse `hasAnyFromGibbon`
const incomingGibbon = Gibbon.create(
this.dataView.byteLength
).setAllFromPositions(positions);
return this.hasAnyFromGibbon(incomingGibbon);
}
/**
* Able to manipulate bits according to an array of signed integers
*
* @example
* ```
* // Set 2 bit positions to logical '1'
* const gibbon = Gibbon.create(2);
* gibbon.setAllFromPositions([1, 2]);
* gibbon.hasAllFromPositions([1, 2]); // returns true
* ```
* @example
* ```
* // Set 1 bit positions to logical '1' and the second to '0'
* const gibbon = Gibbon.create(2);
* gibbon.setAllFromPositions([1, -2]);
* gibbon.hasAllFromPositions([1]); // returns true
* ```
* @param {Array<Number>} positionArray - Array with integer values starting from 1.
* @returns {Gibbon} - For chaining purposes
* @throws {Error} When out of bounds
*/
setAllFromPositions(positionArray: Array<number> = []): Gibbon {
const dataViewBounds = this.dataView.byteLength;
// Remove duplicate values
const positions = Array.from(new Set(positionArray));
for (let i = 0; i < positions.length; i++) {
const position = positions[i];
const positionAbs = Math.abs(position);
const bitBytePosition =
GibbonProcessor.getByteNoAndBitPos(positionAbs);
// Check if position is not out of bounds of the data view:
if (bitBytePosition.byteNo >= dataViewBounds) {
throw new Error("Illegal position");
}
let byte = this.dataView.getUint8(bitBytePosition.byteNo);
byte = GibbonProcessor.changeBit(
byte,
bitBytePosition.bitPos,
position >= 0
);
this.dataView.setUint8(bitBytePosition.byteNo, byte);
}
return this;
}
/**
* Able to manipulate bits according to an array of signed integers
* (opposite of setAllFromPositions)
*
* @example
* ```
* // Set 2 bit positions to logical '0'
* const gibbon = Gibbon.create(2);
* gibbon.unsetAllFromPositions([1, 2]);
* gibbon.hasAllFromPositions([1, 2]); // returns false
* gibbon.hasAllFromPositions([-1, -2]); // returns true
* ```
* @example
* ```
* // Set 1 bit positions to logical '0' and the second to '1'
* const gibbon = Gibbon.create(2);
* gibbon.setAllFromPositions([1, -2]);
* gibbon.hasAllFromPositions([2]); // returns true
* ```
* @param {Array<Number>} positionArray - Array with integer values starting from 1.
* @returns {Gibbon} - For chaining purposes
* @throws {TypeError} if positionArray is not an instance of array
*/
unsetAllFromPositions(positionArray: Array<number> = []): Gibbon {
const positions = positionArray.map((position) => -position);
return this.setAllFromPositions(positions);
}
/**
* Accepts a string of Buffer to create a new Gibbon instance
* @param {string|Buffer} data
* @returns {Gibbon}
*/
static decode(data: Buffer | string): Gibbon {
if (data instanceof Buffer) {
return Gibbon.fromBuffer(data);
}
return Gibbon.fromString(data);
}
/**
* Depending on the GIBBONS_ENCODE_FROM_TO_STRING environment variable if converts this
* Gibbon to a `string` or `Buffer`
*
* @returns {Buffer|string}
*/
encode(): string | Buffer {
if (process.env.GIBBONS_ENCODE_FROM_TO_STRING) {
return this.toString();
}
return this.toBuffer();
}
/**
* Converts this Gibbon instance to a Buffer
* @returns {Buffer}
*/
toBuffer(): Buffer {
return Buffer.from(this.arrayBuffer);
}
static fromBuffer(buffer: Buffer): Gibbon {
const arrayBuffer = new ArrayBuffer(buffer.length);
const view = new Uint8Array(arrayBuffer);
for (let i = 0; i < buffer.length; ++i) {
view[i] = buffer[i];
}
return new Gibbon(arrayBuffer);
}
/**
* Convert the whole ArrayBuffer to a string<br>
* (Hint: Could be used to store a gibbon in persistent storage as a encoded string)
*
* @returns {string} - Encoded string
* @override
*/
toString(): string {
return String.fromCharCode.apply(
null,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
new Uint16Array(this.arrayBuffer) as any
);
}
/**
* Class method to create a new Gibbon from a string<br>
* (Hint: Could be used to retrieve from persistent storage)
*
* @param {string} gibbonString - To be decoded to a Gibbon
* @returns {Gibbon} - new instance of a Gibbon
*/
static fromString(gibbonString: string): Gibbon {
const arrayBuffer = new ArrayBuffer(gibbonString.length * 2); // 2 bytes for each char
const typedArray = new Uint16Array(arrayBuffer);
for (let i = 0, strLen = gibbonString.length; i < strLen; i++) {
typedArray[i] = gibbonString.charCodeAt(i);
}
return new Gibbon(arrayBuffer);
}
/**
* Creates a new empty Gibbon from a given byte size
* @param {Number} byteSize - Allocate this Gibbon with a unsigned integer value (size in bytes)
* @returns {Gibbon} - new instance of a Gibbon
*/
static create(byteSize: number): Gibbon {
const arrayBuffer = new ArrayBuffer(byteSize);
return new Gibbon(arrayBuffer);
}
}