string(lengthOrLengthType?: Coder<number> | LengthOrRef | null,decoderEncoding?: string,decoderOptions?: TextDecoderOptions): Coder<string>
Creates a Coder for strings that automatically chooses between length-prefixed, null-terminated, and fixed-length based on the arguments provided.
- If a lengthType coder is provided as the first argument, it creates a length-prefixed string
- If no arguments are provided, it creates a null-terminated string
- If a length value/reference is provided as the first argument, it creates a fixed-length string
Example 1
Example 1
import { assertEquals } from "@std/assert"; import { string } from "@hertzg/binstruct/string"; import { u16le, u8le } from "@hertzg/binstruct/numeric"; import { struct } from "@hertzg/binstruct/struct"; // Create a struct demonstrating length-prefixed and null-terminated strings const personCoder = struct({ name: string(u16le()), // Length-prefixed string (uses u16le as length coder) bio: string(), // Null-terminated string (no arguments) age: u8le(), }); const person = { name: "John Doe", bio: "Software Developer", age: 30, }; const buffer = new Uint8Array(200); const bytesWritten = personCoder.encode(person, buffer); const [decoded, bytesRead] = personCoder.decode(buffer); assertEquals(decoded.name, person.name); assertEquals(decoded.age, person.age); assertEquals(decoded.bio, person.bio); assertEquals(bytesWritten, bytesRead);
optional
lengthOrLengthType: Coder<number> | LengthOrRef | null
Optional length coder (for length-prefixed) or length value/reference (for fixed-length)
Text encoding for decoding (default: "utf-8", only used for fixed-length)
optional
decoderOptions: TextDecoderOptions
Options for the TextDecoder (only used for fixed-length)
Coder<string>
A Coder that can encode/decode strings