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.

Examples

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);

Functions

f
array<TDecoded>(
elementType: Coder<TDecoded>,
lengthCoderOrLengthTypeOrCondition: Coder<number> | LengthOrRef | ArrayWhileCondition<TDecoded>
): Coder<TDecoded[]>
2 overloads

Creates a Coder for arrays that automatically chooses between length-prefixed and fixed-length based on the arguments provided.

f
arrayFL<TDecoded>(
elementType: Coder<TDecoded>,
lengthOrRef: LengthOrRef
): Coder<TDecoded[]>

Creates a Coder for fixed-length arrays of a given element type.

f
arrayLP<TDecoded>(
elementType: Coder<TDecoded>,
lengthType: Coder<number>
): Coder<TDecoded[]>

Creates a Coder for length-prefixed arrays of a given element type.

f
arrayWhile<TDecoded>(
elementType: Coder<TDecoded>,
condition: ArrayWhileCondition<TDecoded>
): Coder<TDecoded[]>

Creates a Coder for arrays using a custom condition function to determine when to stop.

Type Aliases

T
ArrayWhileCondition<TDecoded> = (params: { index: number; array: TDecoded[]; buffer: Uint8Array; context: Context; }) => boolean

Condition function type for arrayWhile that determines when to continue processing array elements.

Variables

v
kKindArrayFL: symbol

Symbol identifier for fixed-length array coders.

v
kKindArrayLP: symbol

Symbol identifier for length-prefixed array coders.

v
kKindArrayWhile: symbol

Symbol identifier for conditional while-loop array coders.