Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Found neat way to run compile-time assertions for generic type params #50

Open
AngelicosPhosphoros opened this issue Jul 15, 2022 · 0 comments

Comments

@AngelicosPhosphoros
Copy link

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=50be29638d90a53122b59d7da0cbecf3

pub fn check<T: Sized>(){
    trait CheckableIfTooBigForStack: Sized{
        const IS_TOO_BIG: bool = 
            // Use 1 KiB.
            std::mem::size_of::<Self>() > 1024;
        
        // Compile error can be triggered by `let _ = T::TRIGGER_COMPILE_CHK;`
        const TRIGGER_COMPILE_CHK: u8 = if Self::IS_TOO_BIG {
            panic!("Type is too big")
        }
        else{
            0
        };
    }
    
    impl<T, const N: usize> CheckableIfTooBigForStack for [T; N]{}
    
    let _ = <[T;1024] as CheckableIfTooBigForStack>::TRIGGER_COMPILE_CHK;
}

pub fn two_checks(){
    check::<i8>();
    check::<i64>();
}

Error:

error[[E0080]](https://doc.rust-lang.org/stable/error-index.html#E0080): evaluation of `<[i64; 1024] as check::CheckableIfTooBigForStack>::TRIGGER_COMPILE_CHK` failed
  --> src/lib.rs:11:13
   |
11 |             panic!("Type is too big")
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^ the evaluated program panicked at 'Type is too big', src/lib.rs:11:13
   |
   = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info)

note: the above error was encountered while instantiating `fn check::<i64>`
  --> src/lib.rs:25:5
   |
25 |     check::<i64>();
   |     ^^^^^^^^^^^^^^

For more information about this error, try `rustc --explain E0080`.
error: could not compile `playground` due to previous error

AFAIK, your crate currently cannot check generic type parameters and I help that this example would help you to make it available.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant