Skip to content

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

@AngelicosPhosphoros

Description

@AngelicosPhosphoros

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions