Tiny Box optimization #20
Description
It'd help nostd crates if..
There was a TinyBox<T: Sized>
type with two functions:
- Always store
T
inside its data pointer ifsize_of::<T>() <= size_of::<usize>()
andalign_of::<T>() <= align_of::<usize>()
but otherwise acts likeBox
by using the pointer for an allocation if alloc exists, or panics if alloc does not exist. - After creation, always determines whether its data pointer is the data or a pointer to an allocation by invoking roughly
size_of_val(self) <= size_of::<usize>()
andalign_of_val(self) <= align_of::<usize>()
.
In this way, TinyBox<dyn Trait>
should works fine without alloc, provided the original type T
occupies less than size_of::<usize>()
bytes.
Afaik, we do not need rustc modification or std support for this because rustc already requires that size_of_val(self)
and align_of_val(self)
never deference the self data pointer, and only reads fat pointer metadata like size or vtable. I'm unsure if TinyBox<T: !Sized>
makes sense, but initial experiments ran into hiccups there.
After this, one could create a SimpleError
trait for error types that avoid allocations, so then some alias type TinyError = TinyBox<dyn SimpleError>;
provides almost zero cost dynamically typed errors without alloc. In particular TinyError
sounds useful inside Read
and Write
like trait, which helps #7, but..
We'd want a clean story for promoting TinyError
to larger generic error types with backtrace, etc.