-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutils.ts
92 lines (85 loc) · 2.26 KB
/
utils.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
import { within_size } from './assert.js'
import { Endian, Bytes } from './types.js'
export function is_hex (input : string) : boolean {
if (
input.match(/[^a-fA-F0-9]/) === null &&
input.length % 2 === 0
) { return true }
return false
}
export function is_bytes (input : any) : input is Bytes {
if (typeof input === 'string' && is_hex(input)) {
return true
} else if (
typeof input === 'number' ||
typeof input === 'bigint' ||
input instanceof Uint8Array
) {
return true
} else if (
Array.isArray(input) &&
input.every(e => typeof e === 'number')
) {
return true
} else {
return false
}
}
export function set_buffer (
data : number[] | Uint8Array,
size ?: number,
endian : Endian = 'be'
) : Uint8Array {
if (size === undefined) size = data.length
within_size(data, size)
const buffer = new Uint8Array(size).fill(0)
const offset = (endian === 'be') ? 0 : size - data.length
buffer.set(data, offset)
return buffer
}
export function join_array (
arr : Array<Uint8Array | number[]>
) : Uint8Array {
let i, offset = 0
const size = arr.reduce((len, arr) => len + arr.length, 0)
const buff = new Uint8Array(size)
for (i = 0; i < arr.length; i++) {
const a = arr[i]
buff.set(a, offset)
offset += a.length
}
return buff
}
export function bigint_replacer (_ : any, v : any) : any {
return typeof v === 'bigint'
? `${v}n`
: v
}
export function bigint_reviver (_ : any, v : any) : any {
return typeof v === 'string' && /^[0-9]+n$/.test(v)
? BigInt(v.slice(0, -1))
: v
}
export function parse_data (
data_blob : Uint8Array,
chunk_size : number,
total_size : number
) : Uint8Array[] {
const len = data_blob.length,
count = total_size / chunk_size
if (total_size % chunk_size !== 0) {
throw new TypeError(`Invalid parameters: ${total_size} % ${chunk_size} !== 0`)
}
if (len !== total_size) {
throw new TypeError(`Invalid data stream: ${len} !== ${total_size}`)
}
if (len % chunk_size !== 0) {
throw new TypeError(`Invalid data stream: ${len} % ${chunk_size} !== 0`)
}
const chunks = new Array(count)
for (let i = 0; i < count; i++) {
const idx = i * chunk_size
chunks[i] = data_blob.subarray(idx, idx + chunk_size)
}
return chunks
}