Expand description
This crate provides a Box
-like type that can hold values in-place if small
enough (a.k.a. two machine words).
This type can be superior over the standard Box
if you use many small traits.
The performance gained by skipping the allocator can be great while the overhead
on access is minor.
It uses nightly since it accomplishes this by using unstable features:
layout_for_ptr
,
ptr_metadata
, and
unsize
.
§Demo
This simple demonstration shows small values are stored in-place:
use std::fmt::Debug;
use ssobox::SsoBox;
let debuggables: [SsoBox<dyn Debug>; 5] = [
SsoBox::new_unsized(()),
SsoBox::new_unsized(1.0),
SsoBox::new_unsized([42.0, 99.9]),
SsoBox::new_unsized("test test test"),
SsoBox::new_unsized(vec![1, 2, 3, 4]),
];
for (idx, item) in debuggables.iter().enumerate() {
let inhabits = if SsoBox::inhabited(&item) { "T" } else { "F" };
println!(
"{idx} {inhabits} {:018p} - {:?}",
item.as_ref() as *const dyn Debug as *const (),
item.as_ref(),
);
}
Example output:
0 T 0x000000556a9fef48 - ()
1 T 0x000000556a9fef60 - 1.0
2 T 0x000000556a9fef78 - [42.0, 99.9]
3 T 0x000000556a9fef90 - "test test test"
4 F 0x000001a6cc0d5350 - [1, 2, 3, 4]
Structs§
- SsoBox
- A small-size optimized box.