Skip to content

Instantly share code, notes, and snippets.

@0e4ef622
Created May 22, 2021 01:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0e4ef622/89b5a1a8767fd0435a4125b22d615ba2 to your computer and use it in GitHub Desktop.
Save 0e4ef622/89b5a1a8767fd0435a4125b22d615ba2 to your computer and use it in GitHub Desktop.
Const generics assertions.
/// 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