function autoGrowBuffer
autoGrowBuffer<T>(
tryEncodeFn: (buffer: Uint8Array) => T,
autogrowOptions?: AutogrowOptions
): T

Automatically grows a buffer until the encoding function succeeds.

This function creates a buffer and repeatedly calls the provided encoding function, automatically resizing the buffer if a RangeError is thrown due to insufficient space. The buffer grows exponentially by the configured growth factor until either the encoding succeeds or the maximum buffer size is reached.

The function intelligently handles buffer growth by:

  • Respecting the maximum buffer size limit to prevent excessive memory usage
  • Using integer truncation to ensure valid buffer sizes
  • Providing clear error messages when growth limits are reached
  • Propagating non-RangeError exceptions without modification

Examples

Basic usage with automatic buffer growth

import { assertEquals } from "@std/assert";
import { autoGrowBuffer } from "@hertzg/binstruct";

const data = new Uint8Array(10000); // Large data
const result = autoGrowBuffer((buffer) => {
  // Simulate encoding that requires more space than initially provided
  if (buffer.length < data.length) {
    throw new RangeError("Buffer too small");
  }
  buffer.set(data);
  return data.length; // Return bytes written
});

assertEquals(result, 10000);

Custom buffer growth configuration

import { assertEquals } from "@std/assert";
import { autoGrowBuffer } from "@hertzg/binstruct";

const result = autoGrowBuffer(
  (buffer) => {
    if (buffer.length < 1000) {
      throw new RangeError("Buffer too small");
    }
    return "encoded";
  },
  {
    initialSize: 100,
    maxByteLength: 2000,
    growthFactor: 1.5,
  }
);

assertEquals(result, "encoded");

Error handling and maximum size limits

import { assertThrows } from "@std/assert";
import { autoGrowBuffer } from "@hertzg/binstruct";

// Throws when maximum buffer size is reached
assertThrows(() => {
  autoGrowBuffer(
    (_buffer) => {
      throw new RangeError("Always too small");
    },
    {
      initialSize: 100,
      maxByteLength: 500, // Very small limit
    }
  );
}, RangeError, "autoGrowBuffer: Unable to further grow buffer, byteLength is already at maxByteLength");

Error propagation for non-RangeError exceptions

import { assertThrows } from "@std/assert";
import { autoGrowBuffer } from "@hertzg/binstruct";

assertThrows(() => {
  autoGrowBuffer(() => {
    throw new Error("Custom error");
  });
}, Error, "Custom error");

Type Parameters

The return type of the encoding function

Parameters

tryEncodeFn: (buffer: Uint8Array) => T

Function that attempts to encode data into the provided buffer

optional
autogrowOptions: AutogrowOptions

Configuration options for buffer growth behavior

Return Type

The result of the successful encoding operation

Throws

RangeError

When buffer growth reaches the maximum size limit

Error

When initial size is negative or growth factor is less than or equal to 1