-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.ts
74 lines (70 loc) · 2.09 KB
/
util.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
* Copyright (C) Oliver Lenehan (sunsetkookaburra), 2022 */
/** Shorthand to create a `DataView` of `source`,
* respecting `byteOffset` and `byteLength` for ArrayBufferViews.
*
* ```ts
* const data = new Uint8Array([0x09, 0x00]);
* const value = view(data).getUint16(0, true);
* value == 9; // true
* ```
*/
export function view(source: BufferSource): DataView {
return (
source instanceof ArrayBuffer
? new DataView(source)
: new DataView(source.buffer, source.byteOffset, source.byteLength)
);
}
/** Get a `Uint8Array` *reference* of the underlying bytes in `source`.
*
* ```ts
* const data = new Uint16Array([5, 4]);
* const ref = asBytes(data);
* // assuming little-endian
* console.log(ref); // Uint8Array(4) [ 5, 0, 4, 0 ]
* ```
*/
export function asBytes(source: BufferSource): Uint8Array {
return (
source instanceof ArrayBuffer
? new Uint8Array(source)
: new Uint8Array(source.buffer, source.byteOffset, source.byteLength)
);
}
/** Concatenate `arrays` into a new `Uint8Array`
*
* ```ts
* const one = new Uint8Array([0xDE, 0xAD]);
* const two = new Uint16Array([0xEFBE]);
* const out = cat(one, two);
* // assuming little-endian
* console.log(out); // Uint8Array(4) [ 222, 173, 190, 239 ]
* ```
*/
export function cat(arrays: BufferSource[]): Uint8Array {
// get total length
let len = 0;
for (const arr of arrays) {
len += arr.byteLength;
}
let offset = 0;
// new storage space buffer
const buf = new Uint8Array(len);
// fill new buffer by copying
for (const arr of arrays) {
buf.set(asBytes(arr), offset);
offset += arr.byteLength;
}
return buf;
}
export function getByteWindow(source: BufferSource, bitOffset = 0): number {
const buf = asBytes(source);
const i = Math.trunc(bitOffset / 8);
const n = bitOffset % 8;
const hi = ((buf[i] ?? 0) << n) & 0xFF;
const lo = ((buf[i + 1] ?? 0) & 0xFF) >> (8 - n);
return hi | lo;
}