2021-01-10 21:59:07 -05:00
|
|
|
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
|
2020-06-27 16:55:01 -04:00
|
|
|
|
2020-11-19 07:39:45 -05:00
|
|
|
/** Create a `Writer` from a `WritableStreamDefaultReader`. */
|
|
|
|
export function writerFromStreamWriter(
|
2020-07-14 15:24:17 -04:00
|
|
|
streamWriter: WritableStreamDefaultWriter<Uint8Array>,
|
2020-06-27 16:55:01 -04:00
|
|
|
): Deno.Writer {
|
|
|
|
return {
|
|
|
|
async write(p: Uint8Array): Promise<number> {
|
|
|
|
await streamWriter.ready;
|
|
|
|
await streamWriter.write(p);
|
|
|
|
return p.length;
|
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2020-11-19 07:39:45 -05:00
|
|
|
/** Create a `Reader` from a `ReadableStreamDefaultReader`. */
|
|
|
|
export function readerFromStreamReader(
|
2020-07-14 15:24:17 -04:00
|
|
|
streamReader: ReadableStreamDefaultReader<Uint8Array>,
|
2020-06-27 16:55:01 -04:00
|
|
|
): Deno.Reader {
|
|
|
|
const buffer = new Deno.Buffer();
|
|
|
|
|
|
|
|
return {
|
|
|
|
async read(p: Uint8Array): Promise<number | null> {
|
|
|
|
if (buffer.empty()) {
|
|
|
|
const res = await streamReader.read();
|
|
|
|
if (res.done) {
|
|
|
|
return null; // EOF
|
|
|
|
}
|
|
|
|
|
|
|
|
await Deno.writeAll(buffer, res.value);
|
|
|
|
}
|
|
|
|
|
|
|
|
return buffer.read(p);
|
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|
2020-11-19 07:39:45 -05:00
|
|
|
|
|
|
|
/** Create a `WritableStream` from a `Writer`. */
|
|
|
|
export function writableStreamFromWriter(
|
|
|
|
writer: Deno.Writer,
|
|
|
|
): WritableStream<Uint8Array> {
|
|
|
|
return new WritableStream({
|
|
|
|
async write(chunk) {
|
|
|
|
await Deno.writeAll(writer, chunk);
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/** Create a `ReadableStream` from an `AsyncIterator`. */
|
|
|
|
export function readableStreamFromAsyncIterator<T>(
|
|
|
|
iterator: AsyncIterableIterator<T>,
|
|
|
|
): ReadableStream<T> {
|
|
|
|
return new ReadableStream({
|
|
|
|
async pull(controller) {
|
|
|
|
const { value, done } = await iterator.next();
|
|
|
|
|
|
|
|
if (done) {
|
|
|
|
controller.close();
|
|
|
|
} else {
|
|
|
|
controller.enqueue(value);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|