function encode
encode<T>(
coder: Coder<T>,
data: T,
context?: Context,
target?: Uint8Array,
autogrowOptions?: AutogrowOptions
): Uint8Array

Encodes data using the provided coder, handling buffer allocation automatically.

When no target buffer is provided, this function automatically allocates a resizable buffer using exponential growth strategy. The buffer starts at 4KB and grows by 2x when needed, up to a maximum of 400MB. This approach minimizes memory waste while ensuring efficient encoding.

The returned Uint8Array is a zero-copy view over the allocated buffer, so it keeps the buffer's full capacity alive; call .slice() on the result if you hold onto it long-term and want an exact-size copy instead.

Examples

Auto-allocation for small data

import { assertEquals } from "@std/assert";
import { encode, struct, u16le, u8le } from "@hertzg/binstruct";

const coder = struct({ id: u16le(), flag: u8le() });
const data = { id: 42, flag: 7 };

const encoded = encode(coder, data);
assertEquals(encoded.length, 3);

Using provided target buffer

import { assertEquals } from "@std/assert";
import { encode, struct, u32le } from "@hertzg/binstruct";

const coder = struct({ value: u32le() });
const data = { value: 12345 };
const buffer = new Uint8Array(100);

const encoded = encode(coder, data, undefined, buffer);
assertEquals(encoded.length, 4);
assertEquals(encoded.buffer, buffer.buffer);

Large data requiring buffer growth

import { assertEquals } from "@std/assert";
import { encode, struct, array, u8le, u16le } from "@hertzg/binstruct";

const coder = struct({
  data: array(u8le(), u16le())
});
const largeArray = new Array(10000).fill(42);
const data = { data: largeArray };

const encoded = encode(coder, data);
assertEquals(encoded.length, 10002); // 2 bytes length + 10000 bytes data

Custom buffer growth configuration

import { assertEquals } from "@std/assert";
import { encode, struct, array, u8le, u16le } from "@hertzg/binstruct";

const coder = struct({
  data: array(u8le(), u16le())
});
const largeArray = new Array(50000).fill(42);
const data = { data: largeArray };

// Use custom buffer growth settings
const encoded = encode(coder, data, undefined, undefined, {
  initialSize: 8192,    // Start with 8KB
  maxByteLength: 1024 * 1024 * 200, // Max 200MB
  growthFactor: 1.5,    // Grow by 1.5x each time
});
assertEquals(encoded.length, 50002); // 2 bytes length + 50000 bytes data

Type Parameters

The type of data to encode

Parameters

coder: Coder<T>

The coder to use for encoding

data: T

The data to encode

optional
context: Context

Optional context for encoding (defaults to encode context)

optional
target: Uint8Array

Optional target buffer to encode into

optional
autogrowOptions: AutogrowOptions

Optional configuration for buffer growth behavior

Return Type

A Uint8Array containing the encoded data