A single-header, freestanding C implementation of an Optional-style type — a uint64_t that may or may not be present, without relying on sentinel values, null pointers, or exceptions.
C has no built-in way to express "this value might not exist" beyond conventions like returning NULL, a magic sentinel, or an out-of-band error code — all of which are easy to misuse or forget to check. optional.h gives bare-metal/freestanding C code (bootloaders, kernels, low-level tooling) a small, explicit optional_t type instead, without pulling in libc or a runtime.
It's header-only and dependency-free: drop it in with #include "optional.h" and use it directly, no build system or linking required.
typedef struct {
uint64_t value;
bool has_value;
} optional_t;
optional_t some(uint64_t value); // wrap a present value
optional_t none(void); // represent absence
uint64_t value_or(optional_t optional, uint64_t default_value); // unwrap, or fall back#include "optional.h"
optional_t find_value(uint64_t key) {
if (key == 42) {
return some(100);
}
return none();
}
void example(void) {
optional_t result = find_value(42);
uint64_t v = value_or(result, 0); // 100 if present, 0 otherwise
}Work in progress. Currently fixed to uint64_t — genericity, additional combinators (e.g. is_some/is_none, map), and broader integration across the bootloader/kernel are likely next steps. Issues and PRs welcome.