-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.js
More file actions
87 lines (71 loc) · 2.17 KB
/
utils.js
File metadata and controls
87 lines (71 loc) · 2.17 KB
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
const DEFAULT_OPTIONS = {
prefix: "0x",
separator: " ",
};
function normalizeOptions(opts = {}) {
return {
...DEFAULT_OPTIONS,
...opts,
};
}
export function toHex(val, opts) {
const { prefix } = normalizeOptions(opts);
return prefix + (val >>> 0).toString(16).padStart(2, "0").toUpperCase();
}
export function joinHex(tag, data, opts, nBytes = 0) {
const options = normalizeOptions(opts);
const result = [];
if (Array.isArray(tag)) {
for (const value of tag) {
result.push(toHex(value & 0xFF, options));
}
} else if (tag !== null && tag !== undefined) {
result.push(toHex(tag & 0xFF, options));
}
if (Array.isArray(data)) {
for (const value of data) {
result.push(toHex(value & 0xFF, options));
}
} else if (nBytes && data != null) {
for (let i = 0; i < nBytes; i++) {
const byte = (data >>> (i * 8)) & 0xFF;
result.push(toHex(byte, options));
}
}
return result.join(options.separator) + options.separator;
}
export function formatByteSequence(data, opts) {
const options = normalizeOptions(opts);
if (!Array.isArray(data) || data.length === 0) {
return "";
}
const separator = options.separator === "," ? ", " : options.separator;
const values = [];
for (const value of data) {
values.push(toHex(value & 0xFF, options));
}
return values.join(separator);
}
export function readIntLE(bytes, offset, n, signed = true) {
if (!n || n <= 0) return undefined;
let v = 0;
for (let i = 0; i < n; i++) {
const b = bytes[offset + i];
if (b == null) return undefined;
v |= (b & 0xff) << (8 * i);
}
if (!signed) {
return v >>> 0;
}
if (n === 4) return v | 0;
const bits = n * 8;
const sign = 1 << (bits - 1);
if (v & sign) v = v - (1 << bits); // two's complement
return v;
}
export function errDataExpected(name) {
return new Error(`${name}: (at least 1-byte arg) expected`);
}
export function errUnexpectedEnd(name, nBytes) {
return new Error(`${name}: missing data (requested ${nBytes} bytes)`);
}