First Encode
Let’s encode your first value using the low-level core API.
Basic Encoding
The encode function takes a tagged value and returns a 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);
},
);
Run this example:
tsx examples/core/encode-match.ts
Understanding the Result
Grounds uses neverthrow for error handling. The encode function returns Result<Uint8Array, EncodeError>.
Use .match() to handle both success and error cases:
- Success: Receive the encoded
Uint8Array - Error: Receive an
EncodeErrorwith code and message
What’s in the Bytes?
The encoded bytes contain:
- Type byte (1 byte) - identifies the value type (e.g.,
0x0efor String) - Length (1-5 bytes) - varint encoding of the payload length
- Payload - the actual data (e.g., UTF-8 string bytes)
For complete wire format details, see the Relish specification.
Next Steps
Learn about Encoding in depth, or jump to Schema for type-safe serialization.