-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathutil.ts
63 lines (52 loc) · 1.64 KB
/
util.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
const encoder = new TextEncoder();
const decoder = new TextDecoder();
/** Escapes unsafe html characters in a string */
export function escapeHTML(unsafe: string): string {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
/** Encodes a string to an Uint8Array */
export function encodeUTF8(text: string): Uint8Array {
return encoder.encode(text);
}
/** Encodes an Uint8Array to a string */
export function decodeUTF8(arr: Uint8Array): string {
return decoder.decode(arr);
}
/** Prepends a string encoded as UTF8 to an Uint8Array */
export function prependUTF8(arr: Uint8Array, text: string): Uint8Array {
return new Uint8Array([...encodeUTF8(text), ...arr]);
}
/** Checks if Uint8Arrays are equal */
export function uint8ArraysEqual(
a: Uint8Array | undefined,
b: Uint8Array | undefined,
): boolean {
return a === undefined || b === undefined ||
(a.length === b.length && a.every((v, i) => v === b[i]));
}
/** Concatinates a number of Uint8Arrays */
export function uint8ArraysConcat(...arrs: Uint8Array[]): Uint8Array {
const len = arrs.reduce((acc, val) => acc + val.length, 0);
const result = new Uint8Array(len);
let offset = 0;
for (const arr of arrs) {
result.set(arr, offset);
offset += arr.length;
}
return result;
}
/** Reads a ReadableStream<Uint8Array> to completion into a Uint8Array */
export async function readToUint8Array(
stream: ReadableStream<Uint8Array>,
): Promise<Uint8Array> {
const data = [];
for await (const part of stream) {
data.push(part);
}
return uint8ArraysConcat(...data);
}