#in-place #optmization #box-like

nightly ssobox

A Box-like type that avoids allocations by storing small values in-place

2 releases

Uses new Rust 2024

0.1.1 Jun 15, 2025
0.1.0 Jun 14, 2025

#543 in Memory management

MIT license

27KB
526 lines

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]

No runtime deps