Grounds
    Preparing search index...

    Reusable binary encoder with pre-allocated buffer for high-performance encoding.

    The Encoder class provides stateful encoding with an internal buffer that grows dynamically as needed. Reusing a single Encoder instance avoids repeated buffer allocation overhead for batch encoding operations.

    import { Encoder, U8, String_ } from '@grounds/core';

    // Create encoder once, reuse for multiple values
    const encoder = new Encoder();

    const val1 = encoder.encode(U8(42));
    const val2 = encoder.encode(String_('hello'));
    const val3 = encoder.encode(U8(255));

    // Each .encode() call resets the internal position and returns fresh bytes
    val1.match(
    (bytes1) => console.log('First:', bytes1.length),
    (error) => console.error(error)
    );

    The Encoder maintains a resizable internal buffer that grows when needed to accommodate larger values. The buffer is NOT cleared between calls; only the position is reset. This design prioritizes performance over memory footprint for the common case of encoding multiple similar-sized values.

    Integer validation: The encoder performs defense-in-depth validation on all integer values, re-checking ranges and rejecting non-integer floats even if value constructors are somehow bypassed. This ensures wire format integrity.

    Initialize with a custom size for better memory efficiency if encoding many small values: new Encoder(256) instead of the default 1024 bytes.

    Index

    Constructors

    Methods

    Constructors

    • Parameters

      • initialSize: number = 1024

      Returns Encoder

    Methods

    • Encodes a single RelishValue to bytes.

      Resets the internal position and encodes the value, returning a slice of the internal buffer containing only the bytes needed for this value. Each call produces fresh bytes independent of previous calls.

      Parameters

      Returns Result<Uint8Array<ArrayBufferLike>, EncodeError>

      A Result containing the encoded bytes, or an EncodeError on failure

      The returned bytes are a fresh slice, not a view into the internal buffer. Safe to retain across multiple .encode() calls without risk of data corruption.