Grounds
    Preparing search index...

    Function encode

    • Encodes a Relish value to binary bytes in wire format.

      Converts a typed Relish value into its binary representation using the Relish wire format. Uses a reusable internal Encoder with a pre-allocated buffer for efficient encoding.

      Parameters

      • value: RelishValue

        The RelishValue to encode (discriminated union of all Relish types)

      Returns Result<Uint8Array<ArrayBufferLike>, EncodeError>

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

      import { encode, U32, String_ } from '@grounds/core';

      // Encode a simple value
      const result = encode(U32(42));
      result.match(
      (bytes) => console.log('Encoded:', Array.from(bytes)),
      (error) => console.error('Failed:', error.message)
      );

      // Encode a string
      encode(String_('hello')).match(
      (bytes) => console.log('String encoded to', bytes.length, 'bytes'),
      (error) => console.error(error)
      );

      The function uses neverthrow's Result type for error handling. All errors are captured in the Result and never thrown. The signature is never -> throws (uses error handling at callsite, not exceptions).

      Defense-in-depth validation: The encoder re-validates integer ranges even if a value somehow bypasses constructor validation. This ensures wire format correctness by catching non-integer floats (e.g., 3.14) and out-of-range values before they are encoded.

      For encoding composite types, ensure:

      • Struct fields are in ascending field ID order (0-127)
      • Array/Map element types match the type specification
      • All values are readonly RelishValue objects
      • Encoder for reusable encoding with performance tuning
      • decode for the inverse operation (bytes to value)