-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbytestruct.mini.test.ts
125 lines (94 loc) · 2.56 KB
/
bytestruct.mini.test.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
import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
import { bytes, ByteStruct, ByteValue } from "./bytestruct.mini.js";
function toBytes(byteStruct: ByteStruct, values: ByteValue[]) {
const buffer = new ArrayBuffer(byteStruct.byteSize());
byteStruct.writeBytes(values, buffer);
return buffer;
}
Deno.test("bytes", () => {
const ty = bytes`be b1 s16 s32`;
assertEquals(ty.byteSize(), 7);
assertEquals(
new Uint8Array(toBytes(ty, [1, 2, 3])),
new Uint8Array([1, 0, 2, 0, 0, 0, 3]),
);
assertEquals(
ty.readBytes(new Uint8Array([1, 0, 2, 0, 0, 0, 3]).buffer),
[1, 2, 3],
);
});
Deno.test("bytes repeat", () => {
const ty = bytes`be b1*2 s16*2 s32*2`;
assertEquals(ty.byteSize(), 14);
const values = [1, 2, 3, 4, 5, 6];
const expectedBytes = new Uint8Array(
[1, 2, 0, 3, 0, 4, 0, 0, 0, 5, 0, 0, 0, 6],
);
assertEquals(
new Uint8Array(toBytes(ty, values)),
expectedBytes,
);
assertEquals(
ty.readBytes(expectedBytes.buffer),
values,
);
});
Deno.test("bytes byte type", () => {
const ty = bytes`be b3 b2 b1`;
assertEquals(ty.byteSize(), 6);
const values = [1, 2, 3, 4, 5, 6];
const expectedBytes = new Uint8Array([1, 2, 3, 4, 5, 6]);
assertEquals(
new Uint8Array(toBytes(ty, values)),
expectedBytes,
);
assertEquals(
ty.readBytes(expectedBytes.buffer),
values,
);
});
Deno.test("bytes change endianness", () => {
const ty = bytes`be u16 le u16 be u16`;
assertEquals(ty.byteSize(), 6);
const values = [1, 2, 3];
const expectedBytes = new Uint8Array([0, 1, 2, 0, 0, 3]);
assertEquals(
new Uint8Array(toBytes(ty, values)),
expectedBytes,
);
assertEquals(
ty.readBytes(expectedBytes.buffer),
values,
);
});
Deno.test("bytes interpolation", () => {
const ty = bytes`be b1*${3} u8*${2}`;
assertEquals(ty.byteSize(), 5);
const values = [1, 2, 3, 4, 5];
const expectedBytes = new Uint8Array([1, 2, 3, 4, 5]);
assertEquals(
new Uint8Array(toBytes(ty, values)),
expectedBytes,
);
assertEquals(
ty.readBytes(expectedBytes.buffer),
values,
);
});
Deno.test("readme bytestruct mini", () => {
const struct = bytes`be s64 u32 u8*2 b3`;
assertEquals(struct.byteSize(), 17);
const array = new Uint8Array(struct.byteSize());
assertEquals(
struct.writeBytes([10n, 2, 3, 4, 5, 6, 7], array.buffer),
17,
);
assertEquals(
array,
new Uint8Array([0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 2, 3, 4, 5, 6, 7]),
);
assertEquals(
struct.readBytes(array.buffer),
[10n, 2, 3, 4, 5, 6, 7],
);
});