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
Basic usage with automatic buffer growth
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
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
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");
tryEncodeFn: (buffer: Uint8Array) => T
Function that attempts to encode data into the provided buffer
optional
autogrowOptions: AutogrowOptions
Configuration options for buffer growth behavior
The result of the successful encoding operation