box_closure
box_closure provides opaque wrappers over Rust closures (Fn, FnMut, FnOnce) for no-alloc environments.
Rust treats closures as unique types, even when their behavior is identical. This can cause compiler errors when passing closures in generic contexts. Normally, Box<dyn Fn> solves this by heap-allocating the closure, but heap allocation isn’t always available—especially in embedded systems.
box_closure offers OpaqueFn, OpaqueFnMut, and OpaqueFnOnce:
- Hide the concrete type of the closure from the compiler.
- Allow stack-only storage in a fixed-size, aligned buffer.
- Provide safe dispatch without heap allocation.
- Prevent opaque type mismatch compiler errors.
Closure Wrappers
| Type | Semantics | Use case |
|---|---|---|
OpaqueFn |
Immutable closure (Fn) |
Shared access, stateless or read-only captures |
OpaqueFnMut |
Mutable closure (FnMut) |
Closures that mutate captured state |
OpaqueFnOnce |
Single-use closure (FnOnce) |
Closures that consume captured state |
Quick Reference
Closures
OpaqueFn
use ;
let y = 10;
let f = new;
assert_eq!;
OpaqueFnMut
use ;
use Cell;
let counter = new;
let f = new;
f.call;
f.call;
assert_eq!;
OpaqueFnOnce
use ;
let s = Stringfrom;
let f = new;
assert_eq!; // consumes closure
Buffer Alignment
| Buffer Type | Alignment | Typical Size |
|---|---|---|
Align1<N> |
1 byte | N bytes |
Align2<N> |
2 bytes | N bytes |
Align4<N> |
4 bytes | N bytes |
Align8<N> |
8 bytes | N bytes |
Align16<N> |
16 bytes | N bytes |
Align32<N> |
32 bytes | N bytes |
Align64<N> |
64 bytes | N bytes |
Benefits
- No heap allocation: everything fits in a fixed buffer.
- Opaque types prevent generic mismatch errors.
- Safe consumption of
FnOnceclosures without double drop. - Designed for embedded and
no-allocenvironments.