MCPcopy Create free account
hub / github.com/denoland/std / Buffer

Class Buffer

io/buffer.ts:45–497  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

43 * ```
44 */
45export class Buffer implements Writer, WriterSync, Reader, ReaderSync {
46 #buf: Uint8Array; // contents are the bytes buf[off : len(buf)]
47 #off = 0; // read at buf[off], write at buf[buf.byteLength]
48
49 /**
50 * Constructs a new instance with the specified {@linkcode ArrayBuffer} as its
51 * initial contents.
52 *
53 * @param ab The ArrayBuffer to use as the initial contents of the buffer.
54 */
55 constructor(ab?: ArrayBufferLike | ArrayLike<number>) {
56 if (ab === undefined) {
57 this.#buf = new Uint8Array(0);
58 } else if (ab instanceof SharedArrayBuffer) {
59 // Note: This is necessary to avoid type error
60 this.#buf = new Uint8Array(ab);
61 } else {
62 this.#buf = new Uint8Array(ab);
63 }
64 }
65
66 /**
67 * Returns a slice holding the unread portion of the buffer.
68 *
69 * The slice is valid for use only until the next buffer modification (that
70 * is, only until the next call to a method like `read()`, `write()`,
71 * `reset()`, or `truncate()`). If `options.copy` is false the slice aliases the buffer content at
72 * least until the next buffer modification, so immediate changes to the
73 * slice will affect the result of future reads.
74 *
75 * @example Usage
76 * ```ts
77 * import { Buffer } from "@std/io/buffer";
78 * import { assertEquals } from "@std/assert/equals";
79 *
80 * const buf = new Buffer();
81 * await buf.write(new TextEncoder().encode("Hello, world!"));
82 *
83 * const slice = buf.bytes();
84 * assertEquals(new TextDecoder().decode(slice), "Hello, world!");
85 * ```
86 *
87 * @param options The options for the slice.
88 * @returns A slice holding the unread portion of the buffer.
89 */
90 bytes(options = { copy: true }): Uint8Array {
91 if (options.copy === false) return this.#buf.subarray(this.#off);
92 return this.#buf.slice(this.#off);
93 }
94
95 /**
96 * Returns whether the unread portion of the buffer is empty.
97 *
98 * @example Usage
99 * ```ts
100 * import { Buffer } from "@std/io/buffer";
101 * import { assertEquals } from "@std/assert/equals";
102 *

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected