| 66 | * ``` |
| 67 | */ |
| 68 | export class Buffer { |
| 69 | #buf: Uint8Array; // contents are the bytes buf[off : len(buf)] |
| 70 | #off = 0; // read at buf[off], write at buf[buf.byteLength] |
| 71 | #readable: ReadableStream<Uint8Array> = new ReadableStream({ |
| 72 | type: "bytes", |
| 73 | pull: (controller) => { |
| 74 | const view = new Uint8Array(controller.byobRequest!.view!.buffer); |
| 75 | if (this.empty()) { |
| 76 | // Buffer is empty, reset to recover space. |
| 77 | this.reset(); |
| 78 | controller.close(); |
| 79 | controller.byobRequest!.respond(0); |
| 80 | return; |
| 81 | } |
| 82 | const nread = copy(this.#buf.subarray(this.#off), view); |
| 83 | this.#off += nread; |
| 84 | controller.byobRequest!.respond(nread); |
| 85 | }, |
| 86 | autoAllocateChunkSize: DEFAULT_CHUNK_SIZE, |
| 87 | }); |
| 88 | |
| 89 | /** |
| 90 | * Getter returning the instance's {@linkcode ReadableStream}. |
| 91 | * |
| 92 | * @returns A `ReadableStream` of the buffer. |
| 93 | * |
| 94 | * @example Read the content out of the buffer to stdout |
| 95 | * ```ts ignore |
| 96 | * import { Buffer } from "@std/streams/buffer"; |
| 97 | * |
| 98 | * const buf = new Buffer(); |
| 99 | * await buf.readable.pipeTo(Deno.stdout.writable); |
| 100 | * ``` |
| 101 | */ |
| 102 | get readable(): ReadableStream<Uint8Array> { |
| 103 | return this.#readable; |
| 104 | } |
| 105 | |
| 106 | #writable = new WritableStream<Uint8Array>({ |
| 107 | write: (chunk) => { |
| 108 | const m = this.#grow(chunk.byteLength); |
| 109 | copy(chunk, this.#buf, m); |
| 110 | }, |
| 111 | }); |
| 112 | |
| 113 | /** |
| 114 | * Getter returning the instance's {@linkcode WritableStream}. |
| 115 | * |
| 116 | * @returns A `WritableStream` of the buffer. |
| 117 | * |
| 118 | * @example Write the data from stdin to the buffer |
| 119 | * ```ts ignore |
| 120 | * import { Buffer } from "@std/streams/buffer"; |
| 121 | * |
| 122 | * const buf = new Buffer(); |
| 123 | * await Deno.stdin.readable.pipeTo(buf.writable); |
| 124 | * ``` |
| 125 | */ |