function ref
ref<TDecoded>(coder: Coder<TDecoded>): RefValue<TDecoded>

Creates a reference value that can be resolved during encoding/decoding.

References allow for self-referential or circular data structures by deferring the resolution of a coder until the context is available.

Examples

Example 1

import { assertEquals } from "@std/assert";
import { ref, struct, u16le, u8, u32le, array } from "@hertzg/binstruct";

// Create the coders that will be referenced
const channelsLength = u16le();
const pointsLength = u16le();

// Define a complex structure with shared length references
const coder = struct({
  channelsLength: channelsLength,
  channels: struct({
    r: array(u8(), ref(channelsLength)),
    g: array(u8(), ref(channelsLength)),
    b: array(u8(), ref(channelsLength)),
  }),
  pointsLength: pointsLength,
  points: array(u32le(), ref(pointsLength)),
});

// Create sample data
const data = {
  channelsLength: 3,
  channels: {
    r: [255, 128, 64],
    g: [0, 255, 128],
    b: [0, 0, 255],
  },
  pointsLength: 2,
  points: [12345, 67890],
};

// Encode the data with context
const buffer = new Uint8Array(1000);
const bytesWritten = coder.encode(data, buffer);

// Decode the data with context
const [decoded, bytesRead] = coder.decode(buffer);

// Verify the data matches
assertEquals(decoded.channelsLength, data.channelsLength);
assertEquals(decoded.channels.r, data.channels.r);
assertEquals(decoded.channels.g, data.channels.g);
assertEquals(decoded.channels.b, data.channels.b);
assertEquals(decoded.pointsLength, data.pointsLength);
assertEquals(decoded.points, data.points);
assertEquals(bytesWritten, bytesRead);

Type Parameters

TDecoded

Parameters

coder: Coder<TDecoded>

The coder to reference

Return Type

A RefValue that can be resolved with a context

It's the user's responsibility to provide a buffer big enough to fit the whole data.

Usage

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