-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathbinaryReader.ts
78 lines (65 loc) · 2.11 KB
/
binaryReader.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
// eslint-disable-next-line no-unused-vars
import { Struct, StructResult } from './dataTypes' // FIXME
/**
* Parses binary buffer (wrapped to DataView) according to a structure
* description
* @param dataView The DataView object
* @param struct Structure description. The structure can't contain keys
* starting with a digit due to the peculiarities of the javascript engine.
* Otherwise, the reading result may be corrupted.
* @param byteOffset Offset in buffer to read, "0" by default
* @returns The structure applying result
*/
export const readStruct = function<S extends Struct> (
dataView: DataView,
struct: S,
byteOffset: number = 0
): StructResult<S> {
let offset: number = byteOffset
const structResult = {} as StructResult<S>
for (const key in struct) {
;(structResult as any)[key] = struct[key].getValue(dataView, offset)
offset += struct[key].byteLength
}
return structResult
}
/**
* @todo Describe me
*
* @param dataView The DataView object
* @param struct Structure description. The structure can't contain keys
* starting with a digit due to the peculiarities of the javascript engine.
* Otherwise, the reading result may be corrupted.
* @param byteOffset Offset in buffer to read, "0" by default
* @param times Times of structure repeating
* @returns The array of structure applying result
*/
export const readStructMultiple = function<S extends Struct> (
dataView: DataView,
struct: S,
byteOffset: number = 0,
times: number = 1
): StructResult<S>[] {
let offset: number = byteOffset
const result: StructResult<S>[] = []
for (let i = 0; i < times; i++) {
const structResult = {} as StructResult<S>
for (const key in struct) {
;(structResult as any)[key] = struct[key].getValue(dataView, offset)
offset += struct[key].byteLength
}
result[i] = structResult
}
return result
}
/**
* Returns length of a structure
* @param struct Structure description
*/
export const getStructLength = <S extends Struct>(struct: S): number => {
let length: number = 0
for (const key in struct) {
length += struct[key].byteLength
}
return length
}