function bytes
bytes(lengthOrRef?: LengthOrRef | null): Coder<Uint8Array>

Creates a Coder for byte slices.

Examples

Example 1

import { assertEquals } from "@std/assert";
import { bytes } from "@hertzg/binstruct/bytes";

// Fixed length - truncates to 4 bytes
const fixed = bytes(4);
const data = new Uint8Array([1, 2, 3, 4, 5]);
const buffer = new Uint8Array(100);
const written = fixed.encode(data, buffer);
const [decoded] = fixed.decode(buffer);
assertEquals(Array.from(decoded), [1, 2, 3, 4]);

// Variable length - consumes all bytes
const variable = bytes();
const varData = new Uint8Array([1, 2, 3]);
const varWritten = variable.encode(varData, buffer);
const [varDecoded] = variable.decode(buffer);
assertEquals(varDecoded.slice(0, 3), varData);

Parameters

optional
lengthOrRef: LengthOrRef | null

Optional fixed length. If not provided, consumes all available bytes

Return Type

Coder<Uint8Array>

A Coder for byte slices

Usage

import { bytes } from "bytes/bytes.ts";