testudo/src/math.rs
src/math.rsRaw
1pub trait Math {
2 fn square_root(self) -> usize;
3 fn pow2(self) -> usize;
4 fn get_bits(self, num_bits: usize) -> Vec<bool>;
5 fn log_2(self) -> usize;
6}
7
8impl Math for usize {
9 #[inline]
10 fn square_root(self) -> usize {
11 (self as f64).sqrt() as usize
12 }
13
14 #[inline]
15 fn pow2(self) -> usize {
16 let base: usize = 2;
17 base.pow(self as u32)
18 }
19
20 /// Returns the num_bits from n in a canonical order
21 fn get_bits(self, num_bits: usize) -> Vec<bool> {
22 (0..num_bits)
23 .map(|shift_amount| ((self & (1 << (num_bits - shift_amount - 1))) > 0))
24 .collect::<Vec<bool>>()
25 }
26
27 fn log_2(self) -> usize {
28 assert_ne!(self, 0);
29
30 if self.is_power_of_two() {
31 (1usize.leading_zeros() - self.leading_zeros()) as usize
32 } else {
33 (0usize.leading_zeros() - self.leading_zeros()) as usize
34 }
35 }
36}