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):
| Type | Code | JavaScript Type |
|---|---|---|
| Null | 0x00 | null |
| Bool | 0x01 | boolean |
| u8-u128 | 0x02-0x06 | number / bigint |
| i8-i128 | 0x07-0x0b | number / bigint |
| f32/f64 | 0x0c-0x0d | number |
| String | 0x0e | string |
| Array | 0x0f | Array<T> |
| Map | 0x10 | Map<K, V> |
Next Steps
Learn about Decoding to deserialize bytes back to values.