-
Notifications
You must be signed in to change notification settings - Fork 21
/
binary-view.ts
45 lines (40 loc) · 1.2 KB
/
binary-view.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
import type { PrimitiveView, ViewConstructor } from "./view-types.ts";
export class BinaryView extends DataView implements PrimitiveView<Uint8Array> {
static viewLength = 0;
static decode(view: DataView, start = 0, length = view.byteLength) {
return new Uint8Array(
view.buffer.slice(
view.byteOffset + start,
view.byteOffset + start + length,
),
);
}
static encode(value: Uint8Array, view: DataView, start = 0, length?: number) {
const size = !length || value.byteLength < length
? value.byteLength
: length;
new Uint8Array(view.buffer, view.byteOffset, view.byteLength).set(
new Uint8Array(value.buffer, value.byteOffset, size),
start,
);
return size;
}
static from(value: Uint8Array) {
return new this(value.buffer, value.byteOffset, value.byteLength);
}
static getLength(size: number) {
return size;
}
get() {
return (this.constructor as typeof BinaryView).decode(this);
}
set(value: Uint8Array) {
(this.constructor as typeof BinaryView).encode(value, this);
}
toJSON() {
return this.get();
}
static initialize(): ViewConstructor<Uint8Array, PrimitiveView<Uint8Array>> {
return this;
}
}