Core buffers

@webbuf/fixedbuf

Fixed-sized buffers optimized with Rust/WASM

Install

npm install @webbuf/fixedbuf

Usage

import { FixedBuf } from "@webbuf/fixedbuf";
import { WebBuf } from "@webbuf/webbuf";

// Create fixed-size buffers
const buf32 = FixedBuf.alloc<32>(32); // 32-byte buffer
const buf16 = FixedBuf.alloc<16>(16, 0xff); // 16 bytes filled with 0xff
const random = FixedBuf.fromRandom<32>(32); // 32 random bytes

// Empty and all-zero buffers are zero; no timing guarantee is implied
const empty: FixedBuf<0> = FixedBuf.alloc(0);
if (!empty.isZero() || !buf32.isZero())
  throw new Error("Expected zero buffers");
if (buf16.isZero()) throw new Error("Expected nonzero bytes");

// Create from encoded strings
const fromHex = FixedBuf.fromHex<4>(4, "deadbeef");
const fromB64 = FixedBuf.fromBase64(14, "SGVsbG8gV29ybGQhISE=");
const urlFixed: FixedBuf<2> = FixedBuf.fromBase64Url(2, "-_8=");
if (urlFixed.toBase64Url() !== "-_8")
  throw new Error("Expected URL-safe bytes");
if (urlFixed.toBase64Url(true) !== "-_8=") throw new Error("Expected padding");

// Create from WebBuf
const webBuf = WebBuf.alloc(32);
const fixed = FixedBuf.fromBuf<32>(32, webBuf);

// Copy a selected native range; later source mutations do not affect it
const native = new Uint8Array([0xaa, 1, 2, 0xbb]);
const copied: FixedBuf<2> = FixedBuf.fromUint8Array(2, native.subarray(1, 3));
native[1] = 9;
if (copied.toHex() !== "0102") throw new Error("Expected an independent copy");

// Access underlying buffer
const underlying: WebBuf = fixed.buf;

// Convert to strings
fromHex.toHex(); // "deadbeef"
fromB64.toBase64(); // "SGVsbG8gV29ybGQhISE="

// Clone and reverse
const cloned = fixed.clone();
const reversed = fixed.toReverse();

API reference (1 export)

Classes

FixedBuf

class
constructor<N extends number>(size: N, buf: WebBuf): FixedBuf<N>
static fromBuf<N extends number>(size: N, buf: WebBuf): FixedBuf<N>
static fromUint8Array<N extends number>(size: N, bytes: Uint8Array): FixedBuf<N>
static alloc<N extends number>(size: N, fill?: number): FixedBuf<N>
static fromHex<N extends number>(size: N, hex: string): FixedBuf<N>
static fromBase64(size: number, base64: string): FixedBuf<number>
static fromBase64Url<N extends number>(size: N, text: string, stripWhitespace?: boolean): FixedBuf<N>
static fromBase32<N extends number>(size: N, str: string, options?: Base32Options): FixedBuf<N>
static fromRandom<N extends number>(size: N): FixedBuf<N>
readonly buf: WebBuf
isZero(): boolean
toHex(): string
toBase64Url(padding?: boolean): string
toBase64(): string
toBase32(options?: Base32Options): string
clone(): FixedBuf<N>
toReverse(): FixedBuf<N>
wipe(): void