Created
May 22, 2021 01:12
-
-
Save 0e4ef622/89b5a1a8767fd0435a4125b22d615ba2 to your computer and use it in GitHub Desktop.
Const generics assertions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Usage: `const_assert!(Var1: Ty, Var2: Ty, ... => expression)` | |
macro_rules! const_assert { | |
($($list:ident : $ty:ty),* => $expr:expr) => {{ | |
struct Assert<$(const $list: usize,)*>; | |
impl<$(const $list: $ty,)*> Assert<$($list,)*> { | |
const OK: u8 = 0 - !($expr) as u8; | |
} | |
Assert::<$($list,)*>::OK | |
}}; | |
($expr:expr) => { | |
const OK: u8 = 0 - !($expr) as u8; | |
}; | |
} | |
fn gt<const X: usize, const Y: usize>() { | |
const_assert!(X: usize, Y: usize => X > Y); | |
} | |
const fn is_prime(n: usize) -> bool { | |
let mut i = 2; | |
while i*i <= n { | |
if n % i == 0 { | |
return false; | |
} | |
i += 1; | |
} | |
return true; | |
} | |
fn prime<const N: usize>() { | |
const_assert!(N: usize => is_prime(N)); | |
} | |
fn main() { | |
gt::<5, 4>(); | |
prime::<71>(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment