From 8bcfc03d71cbd2cfd7ab68035ec0968d9f93b5b8 Mon Sep 17 00:00:00 2001 From: Kitson Kelly Date: Thu, 23 Apr 2020 00:06:51 +1000 Subject: Rewrite streams (#4842) --- cli/js/web/blob.ts | 49 ++++++++++++++++++++++--------------------------- 1 file changed, 22 insertions(+), 27 deletions(-) (limited to 'cli/js/web/blob.ts') diff --git a/cli/js/web/blob.ts b/cli/js/web/blob.ts index 8f9615933..d30bb7e38 100644 --- a/cli/js/web/blob.ts +++ b/cli/js/web/blob.ts @@ -1,8 +1,7 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import * as domTypes from "./dom_types.d.ts"; import { TextDecoder, TextEncoder } from "./text_encoding.ts"; import { build } from "../build.ts"; -import { ReadableStream } from "./streams/mod.ts"; +import { ReadableStreamImpl } from "./streams/readable_stream.ts"; export const bytesSymbol = Symbol("bytes"); @@ -124,40 +123,36 @@ function processBlobParts( return bytes; } -function getStream(blobBytes: Uint8Array): domTypes.ReadableStream { - return new ReadableStream({ - start: ( - controller: domTypes.ReadableStreamDefaultController - ): void => { +function getStream(blobBytes: Uint8Array): ReadableStream { + // TODO: Align to spec https://fetch.spec.whatwg.org/#concept-construct-readablestream + return new ReadableStreamImpl({ + type: "bytes", + start: (controller: ReadableByteStreamController): void => { controller.enqueue(blobBytes); controller.close(); }, - }) as domTypes.ReadableStream; + }); } async function readBytes( - reader: domTypes.ReadableStreamReader + reader: ReadableStreamReader ): Promise { const chunks: Uint8Array[] = []; while (true) { - try { - const { done, value } = await reader.read(); - if (!done && value instanceof Uint8Array) { - chunks.push(value); - } else if (done) { - const size = chunks.reduce((p, i) => p + i.byteLength, 0); - const bytes = new Uint8Array(size); - let offs = 0; - for (const chunk of chunks) { - bytes.set(chunk, offs); - offs += chunk.byteLength; - } - return Promise.resolve(bytes); - } else { - return Promise.reject(new TypeError()); + const { done, value } = await reader.read(); + if (!done && value instanceof Uint8Array) { + chunks.push(value); + } else if (done) { + const size = chunks.reduce((p, i) => p + i.byteLength, 0); + const bytes = new Uint8Array(size); + let offs = 0; + for (const chunk of chunks) { + bytes.set(chunk, offs); + offs += chunk.byteLength; } - } catch (e) { - return Promise.reject(e); + return bytes; + } else { + throw new TypeError("Invalid reader result."); } } } @@ -207,7 +202,7 @@ export class DenoBlob implements Blob { }); } - stream(): domTypes.ReadableStream { + stream(): ReadableStream { return getStream(this[bytesSymbol]); } -- cgit v1.2.3