Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Encoding

The core package provides low-level encoding for all Relish types.

Basic Encoding

Encode a value using .match() to handle the result:

// examples/core/encode-match.ts
// Demonstrates: Basic encoding with .match() for result handling

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

// Encode a string value
const result = encode(String_("hello world"));

// Use .match() to handle success and error cases
result.match(
  (bytes) => {
    console.log("Encoded successfully!");
    console.log("Bytes:", bytes);
    console.log("Length:", bytes.length, "bytes");
  },
  (err) => {
    console.error("Encoding failed:", err.message);
  },
);

Transforming Results

Use .map() to transform successful results without unwrapping:

// examples/core/encode-transform.ts
// Demonstrates: Transforming successful results with .map()

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

// Encode a value and transform the result to hex string
const hexResult = encode(U32(42)).map((bytes) => Buffer.from(bytes).toString("hex"));

// Use .unwrapOr() to get value with fallback
const hex = hexResult.unwrapOr("encoding failed");

console.log("Encoding 42 as U32:");
console.log("Hex:", hex);

// Can also use .match() on the transformed result
hexResult.match(
  (hexString) => console.log("Success! Hex bytes:", hexString),
  (err) => console.error("Failed:", err.message),
);

Collections

Encode arrays and maps:

// examples/core/encode-collections.ts
// Demonstrates: Encoding arrays and maps

import { encode, decode, Array_, Map_, TypeCode } from "@grounds/core";

// Encode an array of values (primitive U8 elements use raw numbers)
const arrayResult = encode(Array_(TypeCode.U8, [1, 2, 3]));

arrayResult.match(
  (bytes) => console.log("Array encoded:", bytes.length, "bytes"),
  (err) => console.error("Array encoding failed:", err.message),
);

// Roundtrip to verify
arrayResult
  .andThen((bytes) => decode(bytes))
  .match(
    (decoded) => console.log("Array decoded:", decoded),
    (err) => console.error("Array decode failed:", err.message),
  );

// Encode a map (primitive String elements use raw strings)
const mapResult = encode(
  Map_(
    TypeCode.String,
    TypeCode.String,
    new Map([
      ["name", "Alice"],
      ["age", "30"],
    ]),
  ),
);

mapResult.match(
  (bytes) => console.log("Map encoded:", bytes.length, "bytes"),
  (err) => console.error("Map encoding failed:", err.message),
);

Tagged Values

Every value is tagged with its type code (see Relish specification for complete details):

TypeCodeJavaScript Type
Null0x00null
Bool0x01boolean
u8-u1280x02-0x06number / bigint
i8-i1280x07-0x0bnumber / bigint
f32/f640x0c-0x0dnumber
String0x0estring
Array0x0fArray<T>
Map0x10Map<K, V>

Next Steps

Learn about Decoding to deserialize bytes back to values.