Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 19 additions & 3 deletions streams/buffer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,16 @@ const DEFAULT_CHUNK_SIZE = 16_640;
export class Buffer {
#buf: Uint8Array; // contents are the bytes buf[off : len(buf)]
#off = 0; // read at buf[off], write at buf[buf.byteLength]
#startedPromise = Promise.withResolvers();
#startedBool = false;
#readable: ReadableStream<Uint8Array> = new ReadableStream({
type: "bytes",
pull: (controller) => {
pull: async (controller) => {
if (!this.#startedBool) {
await this.#startedPromise.promise;
this.#startedBool = true;
}

const view = new Uint8Array(controller.byobRequest!.view!.buffer);
if (this.empty()) {
// Buffer is empty, reset to recover space.
Expand All @@ -37,7 +44,9 @@ export class Buffer {
}
const nread = copy(this.#buf.subarray(this.#off), view);
this.#off += nread;
controller.byobRequest!.respond(nread);
if (nread !== 0) {
controller.byobRequest!.respond(nread);
}
},
autoAllocateChunkSize: DEFAULT_CHUNK_SIZE,
});
Expand All @@ -51,6 +60,7 @@ export class Buffer {
write: (chunk) => {
const m = this.#grow(chunk.byteLength);
copy(chunk, this.#buf, m);
this.#startedPromise.resolve(undefined);
},
});

Expand All @@ -61,7 +71,13 @@ export class Buffer {

/** Constructs a new instance. */
constructor(ab?: ArrayBufferLike | ArrayLike<number>) {
this.#buf = ab === undefined ? new Uint8Array(0) : new Uint8Array(ab);
if (ab === undefined) {
this.#buf = new Uint8Array(0);
} else {
this.#buf = new Uint8Array(ab);
this.#startedBool = true;
this.#startedPromise.resolve(undefined);
}
}

/** Returns a slice holding the unread portion of the buffer.
Expand Down