arnaucube
arnaucube/testudoPublic Self-hosted repository
testudo/src/math.rs
src/math.rsRaw
 1pub trait Math {
 2  fn square_root(self) -> usize;
 3  fn pow2(self) -> usize;
 4  fn log2(self) -> usize;
 5  fn get_bits(self, num_bits: usize) -> Vec<bool>;
 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  #[inline]
21  fn log2(self) -> usize {
22    (self as f64).log2() as usize
23  }
24
25  /// Returns the num_bits from n in a canonical order
26  fn get_bits(self, num_bits: usize) -> Vec<bool> {
27    (0..num_bits)
28      .map(|shift_amount| ((self & (1 << (num_bits - shift_amount - 1))) > 0))
29      .collect::<Vec<bool>>()
30  }
31}