cuprate icon indicating copy to clipboard operation
cuprate copied to clipboard

Usage of inline `const` for static assertions

Open hinto-janai opened this issue 7 months ago • 0 comments

What

Rust 1.79 brought inline const expressions.

These can be used to conditionally make static assertions (among other things).

Why

Turns runtime panics into compile time errors.

Where/How

Certain runtime panics can be replaced with these new inline const expressions, e.g.:

https://github.com/Cuprate/cuprate/blob/929d19c4508a84d886ece03009a6fcdc5edea5c2/storage/database/src/env.rs#L126-L128

Can be turned into:

fn resize_map(&self, resize_algorithm: Option<ResizeAlgorithm>) -> NonZeroUsize {
    const {
        assert!(
            Self::MANUAL_RESIZE,
            "This function should not be called as this database backend automatically resizes.",
        )
    }
}

This will make calling resize() from database backends that shouldn't be calling resize_map() in the first place to fail at compile time instead of at runtime.

The const expression will only be evaluated if resize() is called, e.g.:

fn main() {}

fn f<const B: bool>() {
    const {
        assert!(B);
    }
}

This program will only fail if f::<false>() is called. It is commented out (not called) so it compiles fine.

hinto-janai avatar Jul 25 '24 20:07 hinto-janai