Small box optimization via const generics

Thankfully there is a workaround, type aliases to the rescue! playground

oh Rust, why does the more complex case work over the simple case?

edit: after a bit more testing, you can't actually use this type. It runs into an ICE. I think that const-generics just can't handle general expressions just yet. This makes sense, since we only got usable const-generics a little while ago, so general expressions are probably still in the pipeline.

To work around this, you have to use SmallBoxInner directly, and supply the correct size. You can sprinkle asserts around to check the size at the beginning of every function on SmallBoxInner.

This is a bit unfortunate, but that's how it is right now. That kinda kills the usecase of a generic type that can be seemlessly used as either a value unless it is too big, in which case it is boxed.

I guess you could just use the following type for that

struct SmallBox<T> {
    ptr: *const T,
    align: [T; 0],
    dropck: PhantomData<T>
}

edit2:

You may be interested in

2 Likes