-
Notifications
You must be signed in to change notification settings - Fork 0
/
strukt.test.ts
71 lines (61 loc) · 1.67 KB
/
strukt.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
import { Strukt, getFieldTypeSize, RecordOf, SchemaOf, Schema, } from "./strukt"; // deno need .ts ending
console.debug(
getFieldTypeSize('u8'),
getFieldTypeSize('i8'),
getFieldTypeSize('ptr'),
getFieldTypeSize('str'),
getFieldTypeSize('i32'),
getFieldTypeSize(['u8', 10]),
);
const Student1 = new Strukt('Student1', {
name: 'u8',
age: 'u16',
isAlive: 'bool',
isMale: 'bool',
});
type std = typeof Student1; // can generate currect type from Strukt
type sch = SchemaOf<typeof Student1>; // can get schema type from Strukt
type rec = RecordOf<typeof Student1>; // can get record type from Strukt
console.log(
Student1,
Student1.size,
Student1.sizeOf('age'),
Student1.sizeOf("isAlive"),
);
const Student2 = new Strukt('Student2', {test:'bool', ...Student1.schema, 'end':'ptr'});
// notice that we can edit schema of existing strukt for another strukt
console.log(
Student2,
Student2.size,
Student2.sizeOf('age'),
Student2.sizeOf("isAlive"),
);
const Teacher = new Strukt('Teacher', {
'id': 'u8',
'align_id': ['u8', 5],
'index': 'u32',
'age': 'u8',
});
console.log(
Teacher,
Teacher.size,
Teacher.sizeOf('age'),
Teacher.sizeOf('id'),
);
const buf = new ArrayBuffer(Teacher.size);
const u8buf = new Uint8Array(buf);
u8buf.fill(-1); // 0xFF
console.log(u8buf);
for(let i=0; i<buf.byteLength; ++i) {
u8buf[i] = i+74;
}
const teacher = Teacher.readFrom(buf) as RecordOf<typeof Teacher>;
console.log('random write', u8buf);
console.log('random read', teacher);
teacher.age = 26;
teacher.index = 5;
teacher.id = 2;
console.log('edit', teacher);
Teacher.writeTo(buf, teacher);
console.log(u8buf);
console.log('read again', Teacher.readFrom(buf));