Compile time assert enum/struct has size <= T?

Is there a way to, at compile time, assert that an enum / struct has size <= T ?

XY problem: Trying to build high performance game server. Want to have upper bound of how much traffic I'm using. Need to upper bound the size of enums / structs I'm dealing with.

It is okay if, for an Arc/Rc , it only counts the size of the ptr.

Define a const and evaluate to panic if size too large.

1 Like

just use assert!() in a const context:

const _: () = {
    assert!(1 == 2);

Three styles for your choice Rust Playground

// check at compile time
const _: () = {
    // style 1: plain const fn call
    // error[E0080]: evaluation of constant value failed

    // style 2: better error msg
    // error[E0080]: evaluation of `<std::vec::Vec<u8> as CheckSize>::NoMoreThan16` failed

// style 3: custom macro with multiple types checked at one time
// error[E0080]: evaluation of `<[u8; 17] as CheckSize>::NoMoreThan16` failed
check_size!((u8, u8), [u8; 17], Vec::<u8>, String);

I like this solution of yours:

const fn check_size<T>() {
    if std::mem::size_of::<T>() > 16 {

Can we slightly generalize this by replacing the 16 with N ?

const fn check_size<T, const N: usize>() {
    if std::mem::size_of::<T>() > N {
        panic!("the size of type shouldn't be greater than 16")

^-- are there any hidden traps of the above I should be aware of ?

I wrote the const generics first, then to be straightforward, the const generics is removed.

So I don't think there are traps here. The final code depends on how generic / simplified you want it to be.

Update: I forgot to say formatting is not allowed in const eval, like:

const fn check_size<T>() {
    let size = std::mem::size_of::<T>();
    if  size > 16 {
        panic!("the size of type is {size}, and shouldn't be greater than 16")

// error[E0015]: cannot call non-const formatting macro in constant functions
  --> src/
30 |         panic!("the size of type is {size}, and shouldn't be greater than 16")
   |                                      ^^^^

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.