first commit

This commit is contained in:
2026-05-29 08:20:56 +01:00
commit 949299f58d
6368 changed files with 527176 additions and 0 deletions

View File

@@ -0,0 +1,71 @@
# bufferToUint8Array
<!-- begin:auto-docs -->
_(no submodules)_
<!-- end:auto-docs -->
## Purpose
`bufferToUint8Array` normalises the two byte-container shapes that show up in
mixed Node/browser code — `Buffer` and `ArrayBuffer` — into the single
canonical `Uint8Array` form used throughout `@suaveplan/streams`. The streams
package treats `Uint8Array` as the universal byte chunk; this helper lets call
sites accept either input without sprinkling `instanceof` checks across every
adapter.
The conversion is zero-copy. For `Buffer` inputs we construct a view that
respects the source's `byteOffset` / `byteLength`, which matters because Node
typically slices new `Buffer`s out of a shared pool. For `ArrayBuffer` inputs
we wrap the entire buffer.
## Features
- Accepts both Node `Buffer` and standard `ArrayBuffer` inputs.
- Zero-copy: never allocates a new backing buffer.
- Honours `Buffer.subarray` offsets correctly (avoids a common foot-gun).
- Pure synchronous function with no dependencies.
## Usage: Basic Example
```ts
import { bufferToUint8Array } from "@suaveplan/streams/utils/buffer/buffer-to-uint8/buffer-to-uint8";
const u8 = bufferToUint8Array(Buffer.from("hello"));
console.log(u8.byteLength); // 5
```
## Usage: Advanced Example
```ts
import { bufferToUint8Array } from "@suaveplan/streams/utils/buffer/buffer-to-uint8/buffer-to-uint8";
// Coming from `node:fs/promises#readFile` (returns Buffer in Node)
async function loadAsU8(path: string): Promise<Uint8Array> {
const { readFile } = await import("node:fs/promises");
return bufferToUint8Array(await readFile(path));
}
// Coming from a browser `Response.arrayBuffer()`
async function fetchAsU8(url: string): Promise<Uint8Array> {
const ab = await (await fetch(url)).arrayBuffer();
return bufferToUint8Array(ab);
}
```
## API Reference
### `bufferToUint8Array(buffer: Buffer | ArrayBuffer): Uint8Array`
- **`buffer`** — either a Node `Buffer` (a `Uint8Array` subclass with possibly
non-zero `byteOffset`) or a standard DOM/ES `ArrayBuffer`.
- **Returns** — a `Uint8Array` view over the same memory as the input.
- **Throws** — never; type narrowing is performed via `instanceof ArrayBuffer`.
## Implementation Notes
- The `instanceof ArrayBuffer` check intentionally precedes the `Buffer` branch
because `Buffer instanceof ArrayBuffer` is `false` in Node (Buffer extends
`Uint8Array`, not `ArrayBuffer`).
- The returned view shares memory with the source. If you need an independent
copy, follow up with `.slice()` or pair this helper with
`createUint8ArraySlice`.
- Universal: this module has no Node-only or DOM-only imports.