1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
//! Trait definitions for bitwise operations.
//!
//! Most traits are only implemented for unsigned integers yet.
/// Common bit operations for integers
// TODO(v0.3): add doc tests
pub trait BitTest {
/// Get the minimum required number of bits to represent this integer
fn bit_len(&self) -> usize;
/// Get the n-th bit of the integer
fn bit(&self, n: usize) -> bool;
/// Get the number of trailing zeros in the integer
fn trailing_zeros(&self) -> Option<usize>;
// TODO(v0.3): add trailing_ones
}
/// Functions related to the power of two.
///
/// # Examples
/// ```
/// use dashu_base::PowerOfTwo;
///
/// let n = 5u32;
/// assert!(!n.is_power_of_two());
/// assert_eq!(n.next_power_of_two(), 8);
/// ```
pub trait PowerOfTwo {
/// Test if self is a power of two (`2^k`)
fn is_power_of_two(&self) -> bool;
/// Get the smallest power of two greater than or equal to self.
fn next_power_of_two(self) -> Self;
}
macro_rules! impl_bit_ops_prim {
($($T:ty)*) => {$(
impl BitTest for $T {
#[inline]
fn bit_len(&self) -> usize {
(<$T>::BITS - self.leading_zeros()) as usize
}
#[inline]
fn bit(&self, position: usize) -> bool {
self & (1 << position) > 0
}
#[inline]
fn trailing_zeros(&self) -> Option<usize> {
if *self == 0 {
None
} else {
Some(<$T>::trailing_zeros(*self) as usize)
}
}
}
impl PowerOfTwo for $T {
#[inline]
fn is_power_of_two(&self) -> bool {
<$T>::is_power_of_two(*self)
}
#[inline]
fn next_power_of_two(self) -> $T {
<$T>::next_power_of_two(self)
}
}
)*}
}
impl_bit_ops_prim!(u8 u16 u32 u64 u128 usize);