2.2 KiB
encode-string
Purpose
Utilities for encoding and decoding length-prefixed UTF-8 strings in the BTF binary format. They provide the wire encoding used by BinaryFontPacker to store font family name, CSS weight, and CSS style as inline strings in the binary header.
Every string is encoded as [uint32 byte-length LE][UTF-8 bytes], which allows safe decoding without a sentinel character and handles arbitrary Unicode content including multi-byte sequences.
Features
encodeString: encodes a JS string as[uint32 LE length][UTF-8 bytes]decodeString: reads a length-prefixed string from a buffer at a given byte offset and returns the decoded value and the new offset after the string
Usage: Basic Example
import { encodeString, decodeString } from "@suaveplan/font-compress/utils/encode-string";
const encoded = encodeString("Arial");
// [5, 0, 0, 0, 65, 114, 105, 97, 108]
const { value, offset } = decodeString(encoded, 0);
// value = "Arial", offset = 9
Usage: Advanced Example
// Chaining multiple string reads during unpack
let off = 0;
const r1 = decodeString(data, off); off = r1.offset;
const r2 = decodeString(data, off); off = r2.offset;
const r3 = decodeString(data, off); off = r3.offset;
// r1.value = familyName, r2.value = cssFontWeight, r3.value = cssFontStyle
API Reference
encodeString(str: string): Uint8Array
Encodes str as [uint32 LE byte-length][UTF-8 bytes].
Parameters: str — any JS string including multi-byte Unicode.
Returns: Uint8Array of 4 + byteLength bytes.
decodeString(data: Uint8Array, offset: number): { value: string; offset: number }
Reads a length-prefixed string at offset in data.
Parameters:
data— source bufferoffset— byte position of the uint32 length prefix
Returns: { value: string; offset: number } where offset is the position immediately after the string bytes.
Implementation Notes
Uses the platform TextEncoder / TextDecoder singletons. The returned offset from decodeString is the cursor position immediately following the string's last byte, suitable for passing directly to the next read operation.