import { concatUint8Arrays } from "../../stream/shared.js";
import { onceEvent } from "../../stream/internal/event-utils.js";
import { isWritableStream } from "../../stream/internal/type-guards.js";
export async function pipeIterableToSink(iterable, sink) {
    if (isWritableStream(sink)) {
        const writer = sink.getWriter();
        try {
            for await (const chunk of iterable) {
                await writer.write(chunk);
            }
            await writer.close();
        }
        finally {
            try {
                writer.releaseLock();
            }
            catch {
                // Ignore
            }
        }
        return;
    }
    // Node-style Writable
    for await (const chunk of iterable) {
        const ok = sink.write(chunk);
        if (ok === false && typeof sink.once === "function") {
            await onceEvent(sink, "drain");
        }
    }
    if (typeof sink.end === "function") {
        sink.end();
    }
    if (typeof sink.once === "function") {
        await Promise.race([onceEvent(sink, "finish"), onceEvent(sink, "close")]);
    }
}
export async function collect(iterable) {
    const chunks = [];
    let total = 0;
    for await (const chunk of iterable) {
        chunks.push(chunk);
        total += chunk.length;
    }
    return concatUint8Arrays(chunks, total);
}
