decode<T>(): T
Decodes data using the provided coder, returning the decoded value.
This function decodes data from the provided buffer and returns only the decoded value, making it simple to use when you don't need to know how many bytes were consumed during decoding.
Basic decoding
Basic decoding
import { assertEquals } from "@std/assert"; import { decode, struct, u16le, u8le } from "@hertzg/binstruct"; const coder = struct({ id: u16le(), flag: u8le() }); const buffer = new Uint8Array([42, 0, 7]); // Little-endian: id=42, flag=7 const decodedData = decode(coder, buffer); assertEquals(decodedData.id, 42); assertEquals(decodedData.flag, 7);
Processing multiple values from a buffer
Processing multiple values from a buffer
import { assertEquals } from "@std/assert"; import { decode, encode, struct, u16le } from "@hertzg/binstruct"; const coder = struct({ value: u16le() }); // Create a buffer with multiple encoded values const value1 = encode(coder, { value: 100 }); const value2 = encode(coder, { value: 200 }); const combinedBuffer = new Uint8Array(value1.length + value2.length); combinedBuffer.set(value1, 0); combinedBuffer.set(value2, value1.length); // Decode first value const decoded1 = decode(coder, combinedBuffer); assertEquals(decoded1.value, 100); // Decode second value from remaining buffer (need to know size) const remaining = combinedBuffer.subarray(2); // Skip first 2 bytes const decoded2 = decode(coder, remaining); assertEquals(decoded2.value, 200);
Using custom context
Using custom context
import { assertEquals } from "@std/assert"; import { decode, createContext, struct, u32le } from "@hertzg/binstruct"; const coder = struct({ value: u32le() }); const buffer = new Uint8Array([42, 0, 0, 0]); // Little-endian: value=42 const context = createContext("decode"); const decodedData = decode(coder, buffer, context); assertEquals(decodedData.value, 42);
coder: Coder<T>
The coder to use for decoding
buffer: Uint8Array
The buffer containing encoded data
The decoded value