-
Notifications
You must be signed in to change notification settings - Fork 0
/
struct.ts
95 lines (83 loc) · 1.74 KB
/
struct.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
import { LITTLE_ENDIAN } from './endian.ts';
import type { ArrayBufferReal, MemberInfos, Type } from './type.ts';
import { dataView } from './util.ts';
let members: WeakMap<typeof Struct, MemberInfos>;
/**
* Binary structure buffer view.
*/
export class Struct implements Type {
/**
* @inheritdoc
*/
declare public readonly ['constructor']: Omit<typeof Struct, 'new'>;
/**
* Buffer data.
*/
readonly #buffer: ArrayBufferLike;
/**
* Byte offset into buffer.
*/
readonly #byteOffset: number;
/**
* Little endian, or big.
*/
readonly #littleEndian: boolean;
/**
* @inheritdoc
*/
constructor(
buffer: ArrayBufferReal,
byteOffset = 0,
littleEndian: boolean | null = null,
) {
dataView(this.#buffer = buffer);
if (byteOffset < -0x1fffffffffffff || byteOffset > 0x1fffffffffffff) {
throw new RangeError(`Invalid offset: ${byteOffset}`);
}
this.#byteOffset = byteOffset - byteOffset % 1 || 0;
this.#littleEndian = !!(littleEndian ?? LITTLE_ENDIAN);
}
/**
* @inheritdoc
*/
public get buffer(): ArrayBufferLike {
return this.#buffer;
}
/**
* @inheritdoc
*/
public get byteLength(): number {
return this.constructor.BYTE_LENGTH;
}
/**
* @inheritdoc
*/
public get byteOffset(): number {
return this.#byteOffset;
}
/**
* @inheritdoc
*/
public get littleEndian(): boolean {
return this.#littleEndian;
}
/**
* Byte length of struct.
*/
public static readonly BYTE_LENGTH: number = 0;
/**
* Members infos.
*/
public static get MEMBERS(): Readonly<MemberInfos> {
let r = (members ??= new WeakMap()).get(this);
if (!r) {
members.set(
this,
r = Object.create(
Object.getPrototypeOf(this).MEMBERS ?? null,
) as Readonly<MemberInfos>,
);
}
return r;
}
}