Last active
May 29, 2019 20:33
-
-
Save DutchGhost/90fae7350fdd82f53fc036c2633cc9f4 to your computer and use it in GitHub Desktop.
Digits10 at compiletime
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
#![feature(const_generics)] | |
struct Range { | |
start: usize, | |
end: usize, | |
} | |
impl Range { | |
pub const fn new(start: usize, end: usize) -> Self { | |
Self { start, end } | |
} | |
pub const fn contains(&self, other: usize) -> bool { | |
(other >= self.start) & (other < self.end) | |
} | |
} | |
struct Digits10<const N: usize>; | |
impl <const N: usize> Digits10<{N}> { | |
pub const fn digits10() -> usize { | |
let _1 = (Range::new(0, 10).contains(N) as u8) << 0; | |
let _2 = (Range::new(10, 100).contains(N) as u8) << 1 ; | |
let _3 = (Range::new(100, 1000).contains(N) as u8) << 2; | |
let _4 = (Range::new(1000, 10000).contains(N) as u8) << 3; | |
[1, 2, 3, 4][((_1 + _2 + _3 + _4) as usize).trailing_zeros() as usize] | |
} | |
} | |
pub fn blah() { | |
assert_eq!(Digits10::<100>::digits10(), 3); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment