Can I limit the size of a Rust enum?

Viewed 562

I have an enum type in my Rust program of which some variants may contain inner data.

enum MyEnum {
    A,
    B(u64),
    C(SmallStruct),
    D(Box<LargeStruct>)
}

This enum is going to be stored tens of thousands of times and memory usage is an issue. I would like to avoid accidentally adding a very large variant for the enum. Is there a way that I can tell the compiler to limit the size of an enum instance in memory?

2 Answers

As noted in the other answer, you can use the const_assert! macro, but it will require an external crate, static_assertions. If you're looking for a std-only solution and can live with the uglier error message when the assertion fails, you can use this (playground):

#[deny(const_err)]
const fn const_assert(ok: bool) {
    0 - !ok as usize;
}

// assert that MyEnum is no larger than 16 bytes
const _ASSERT_SMALL: () = const_assert(mem::size_of::<MyEnum>() <= 16);

You can read about this technique, along with ways to improve it, in the article written by the author of the static_assertions crate.

Related