A Box like type that keeps small objects on the stack and can allocate bigger objects as
Box, Rc or Arc. DerefMut is copy-on-write when the Smox is backed by Rc or Arc
Rationale
In generic contexts one often does not know how big the objects will be. If they are small enough they can be kept on the stack for better performance. If they are bigger they need to be allocated on the heap. Smox allows to do this in a transparent way.
Example
#
#
#
#
#
Details
- In the current implementation, the given
SIZEis also the size of aSmoxor the size of a box types whatever is bigger. Current stable rust lacks thegeneric_const_exprssupport to constrain the size when heap storage is used to a single pointer. This will change in the future, perhaps with anightlyfeature flag. - The biggest spaces saving are when you can benefit from the copy-on-write behavior of
RcorArc. Use either of these when there is a chance that the objects will be cloned. - When your
Smoxshould stay as small as possible then try theMINIMAL_SIZEas size limit.
Nightly Support
With the nightly feature enabled, Smox uses generic_const_exprs to optimize away unused
in-place storage. When T is larger than SIZE, the in-place storage becomes 0 bytes instead
of wasting SIZE bytes. Because of alignment requirements it will still be sized at least
a pointer size. When stored on heap it is a single pointer, when stored in_place it is
size_of::<T>().next_multiple_of(std::mem::size_of::<usize>()).
Note: Using Smox with generic type parameters in structs requires adding a where bound
[(); optimal_size::<T, SIZE>()]: to propagate the constraint. This is an inherent limitation
of generic_const_exprs.
#
#
#
#
#
#