stringLP(lengthType: Coder<number>): Coder<string>
Creates a Coder for length-prefixed strings.
The string is encoded with a length prefix followed by the string bytes. The length is encoded using the provided lengthType coder.
Example 1
Example 1
import { assertEquals } from "@std/assert"; import { stringLP } from "@hertzg/binstruct/string"; import { u16le, u32le } from "@hertzg/binstruct/numeric"; import { struct } from "@hertzg/binstruct/struct"; // Define a file metadata structure with length-prefixed strings const fileMetadataCoder = struct({ filename: stringLP(u16le()), // Filename with 16-bit length prefix description: stringLP(u32le()), // Description with 32-bit length prefix author: stringLP(u16le()), // Author name with 16-bit length prefix version: u16le(), // Version number }); // Create sample file metadata const metadata = { filename: "document.txt", description: "A sample text document with metadata", author: "John Doe", version: 1, }; const buffer = new Uint8Array(200); const bytesWritten = fileMetadataCoder.encode(metadata, buffer); const [decoded, bytesRead] = fileMetadataCoder.decode(buffer); assertEquals(decoded, metadata); assertEquals(bytesWritten, bytesRead);
lengthType: Coder<number>
The coder for the string length (typically u32 or u16)
Coder<string>
A Coder that can encode/decode length-prefixed strings