#Announcing SmallBox
https://crates.io/crates/smallbox
Box dynamically-sized types on stack
A small crate that allow storing dst on stack and return from function, typically when you want to use dynamically dispatch without heap. Still it has heap fallback in case no enough space for stack allocation.
Example
The simplest usage can be trait object dynamic-dispatch
use smallbox::StackBox;
let val: StackBox<PartialEq<usize>> = StackBox::new(5usize).unwrap();
assert!(*val == 5)
Another use case is to allow returning capturing closures without having to box them. (impl trait
of course!)
use smallbox::StackBox;
fn make_closure(s: String) -> StackBox<Fn()->String> {
StackBox::new(move || format!("Hello, {}", s)).ok().unwrap()
}
let closure = make_closure("world!".to_owned());
assert_eq!(closure(), "Hello, world!");
Heap fallback involved
use smallbox::SmallBox;
let tiny: SmallBox<[u64]> = SmallBox::new([0; 2]);
let big: SmallBox<[u64]> = SmallBox::new([1; 8]);
assert_eq!(tiny.len(), 2);
assert_eq!(big[7], 1);
match tiny {
SmallBox::Stack(val) => assert_eq!(*val, [0; 2]),
_ => unreachable!()
}
match big {
SmallBox::Box(val) => assert_eq!(*val, [1; 8]),
_ => unreachable!()
}