import Gio from "gi://Gio"; import GLib from "gi://GLib"; export async function readFromStreamRaw( stream: Gio.InputStream, bytes: number ): Promise { return new Promise((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 { return new Promise((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 { if (data instanceof ArrayBuffer) { data = new Uint8Array(data); } return new Promise((resolve, reject) => { stream.write_all_async( data, GLib.PRIORITY_DEFAULT, null, (stream, result) => { try { stream.write_all_finish(result); resolve(); } catch (e) { reject(e); } } ); }); }