source: trip-planner-front/node_modules/hdr-histogram-js/src/ByteBuffer.ts@ 188ee53

Last change on this file since 188ee53 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 2.1 KB
Line 
1const { pow, floor } = Math;
2const TWO_POW_32 = pow(2, 32);
3
4/**
5 * Mimic Java's ByteBufffer with big endian order
6 */
7class ByteBuffer {
8 position: number;
9
10 data: Uint8Array;
11
12 int32ArrayForConvert: Uint32Array;
13 int8ArrayForConvert: Uint8Array;
14
15 static allocate(size = 16): ByteBuffer {
16 return new ByteBuffer(new Uint8Array(size));
17 }
18
19 constructor(data: Uint8Array) {
20 this.position = 0;
21 this.data = data;
22 this.int32ArrayForConvert = new Uint32Array(1);
23 this.int8ArrayForConvert = new Uint8Array(this.int32ArrayForConvert.buffer);
24 }
25
26 put(value: number) {
27 if (this.position === this.data.length) {
28 const oldArray = this.data;
29 this.data = new Uint8Array(this.data.length * 2);
30 this.data.set(oldArray);
31 }
32 this.data[this.position] = value;
33 this.position++;
34 }
35
36 putInt32(value: number) {
37 if (this.data.length - this.position < 4) {
38 const oldArray = this.data;
39 this.data = new Uint8Array(this.data.length * 2 + 4);
40 this.data.set(oldArray);
41 }
42 this.int32ArrayForConvert[0] = value;
43 this.data.set(this.int8ArrayForConvert.reverse(), this.position);
44 this.position += 4;
45 }
46
47 putInt64(value: number) {
48 this.putInt32(floor(value / TWO_POW_32));
49 this.putInt32(value);
50 }
51
52 putArray(array: Uint8Array) {
53 if (this.data.length - this.position < array.byteLength) {
54 const oldArray = this.data;
55 this.data = new Uint8Array(this.position + array.byteLength);
56 this.data.set(oldArray);
57 }
58 this.data.set(array, this.position);
59 this.position += array.byteLength;
60 }
61
62 get(): number {
63 const value = this.data[this.position];
64 this.position++;
65 return value;
66 }
67
68 getInt32(): number {
69 this.int8ArrayForConvert.set(
70 this.data.slice(this.position, this.position + 4).reverse()
71 );
72 const value = this.int32ArrayForConvert[0];
73 this.position += 4;
74 return value;
75 }
76
77 getInt64(): number {
78 const high = this.getInt32();
79 const low = this.getInt32();
80 return high * TWO_POW_32 + low;
81 }
82
83 resetPosition() {
84 this.position = 0;
85 }
86}
87
88export default ByteBuffer;
Note: See TracBrowser for help on using the repository browser.