Array coders for binary structures.
This module provides utilities for encoding and decoding arrays in two modes:
- Length-prefixed arrays using a numeric length coder
- Fixed-length arrays using a literal length or a import("./ref.ts").RefValue
All coders follow the common import("./mod.ts").Coder interface.
It's the user's responsibility to provide a buffer big enough to fit the whole data.
Length-prefixed and fixed-length arrays
Length-prefixed and fixed-length arrays
import { assertEquals } from "@std/assert"; import { array, arrayLP, arrayFL } from "@hertzg/binstruct/array"; import { struct } from "@hertzg/binstruct/struct"; import { u8le, u16le } from "@hertzg/binstruct/numeric"; // A structure mixing both array kinds const coder = struct({ lenPref: arrayLP(u8le(), u16le()), // [len:u16] followed by items fixed: arrayFL(u8le(), 3), // exactly 3 items auto: array(u8le(), 2), // auto-selects fixed-length while: array(u8le(), ({ index }) => index < 2), // while index < 2 }); const value = { lenPref: [1, 2, 3], fixed: [4, 5, 6], auto: [7, 8], while: [9, 10] }; const buf = new Uint8Array(1024); const written = coder.encode(value, buf); const [decoded, read] = coder.decode(buf); assertEquals(decoded, value); assertEquals(written, read);
Creates a Coder for arrays that automatically chooses between length-prefixed and fixed-length based on the arguments provided.
Creates a Coder for fixed-length arrays of a given element type.
Creates a Coder for length-prefixed arrays of a given element type.
Creates a Coder for arrays using a custom condition function to determine when to stop.
Condition function type for arrayWhile that determines when to continue processing array elements.
Symbol identifier for fixed-length array coders.
Symbol identifier for length-prefixed array coders.
Symbol identifier for conditional while-loop array coders.
Usage
import * as mod from "array/array.ts";