Struct coder for binary structures.
Creates a coder from an object schema of property-name to import("./mod.ts").Coder. Encodes fields in order and decodes them into an object of the same shape.
Values are added to the shared context during encode/decode, enabling import("./ref.ts").ref based length references.
It's the user's responsibility to provide a buffer big enough to fit the whole data.
Minimal usage
Minimal usage
import { assertEquals } from "@std/assert"; import { struct } from "@hertzg/binstruct/struct"; import { u16le, u8le } from "@hertzg/binstruct/numeric"; const coder = struct({ id: u16le(), flag: u8le() }); const value = { id: 513, flag: 7 }; const buf = new Uint8Array(32); const written = coder.encode(value, buf); const [decoded, read] = coder.decode(buf); assertEquals(decoded, value); assertEquals(written, read);
f
struct<T extends Record<string, Coder<any>>>(schema: T): Coder<StructDecoded<T>>
Creates a Coder for structured data from an object of property names to coders.
T
StructDecoded<T extends Record<string, Coder<any>>> = [K in keyof T]: T[K] extends Coder<infer U> ? U : never
The decoded object type of a struct schema: each property's coder
Coder<U> contributes a property of type U.
Usage
import * as mod from "struct/struct.ts";