VoidShell/widget/utils.ts
2024-10-31 15:39:18 -06:00

69 lines
1.7 KiB
TypeScript

import Gio from "gi://Gio";
import GLib from "gi://GLib";
export async function readFromStreamRaw(
stream: Gio.InputStream,
bytes: number
): Promise<Uint8Array> {
return new Promise<Uint8Array>((resolve, reject) => {
const buffer = new Uint8Array(bytes);
stream.read_bytes_async(
bytes,
GLib.PRIORITY_DEFAULT,
null,
(stream, result) => {
try {
const data = stream.read_bytes_finish(result);
data.get_data(buffer);
resolve(buffer);
} catch (e) {
reject(e);
}
}
);
});
}
export async function readFromStream(
stream: Gio.InputStream,
bytes: number
): Promise<Uint8Array> {
return new Promise<Uint8Array>((resolve, reject) => {
const chunkCount = Math.ceil(bytes / 4096);
const buffer = await Array.from({ length: chunkCount }, (_, i) => i).reduce(
(acc, i) => {
const buffer = await acc;
const chunkSize = Math.min(4096, bytes - i * 4096);
const chunk = await readFromStreamRaw(stream, chunkSize);
buffer.set(chunk, i * 4096);
return buffer;
},
Promise.resolve(new Uint8Array(bytes))
);
});
}
export async function writeToStream(
stream: Gio.OutputStream,
data: ArrayBuffer | Uint8Array
): Promise<void> {
if (data instanceof ArrayBuffer) {
data = new Uint8Array(data);
}
return new Promise<void>((resolve, reject) => {
stream.write_all_async(
data,
GLib.PRIORITY_DEFAULT,
null,
(stream, result) => {
try {
stream.write_all_finish(result);
resolve();
} catch (e) {
reject(e);
}
}
);
});
}