rutil/number_traits/integer_ops/
bit_counting.rs

1/// Bit counting operations.
2pub trait BitCountingOps {
3    /// Returns the number of ones in the binary representation of `self`.
4    fn count_ones(self) -> u32;
5
6    /// Returns the number of zeros in the binary representation of `self`.
7    fn count_zeros(self) -> u32;
8
9    /// Returns the number of leading zeros in the binary representation of `self`.
10    fn leading_zeros(self) -> u32;
11
12    /// Returns the number of trailing zeros in the binary representation of `self`.
13    fn trailing_zeros(self) -> u32;
14
15    /// Returns the number of leading ones in the binary representation of `self`.
16    fn leading_ones(self) -> u32;
17
18    /// Returns the number of trailing ones in the binary representation of `self`.
19    fn trailing_ones(self) -> u32;
20}
21
22/// Implements [`BitCountingOps`].
23macro_rules! impl_bit_counting {
24    ($($t:ty),*) => {
25        $(impl BitCountingOps for $t {
26            #[inline] fn count_ones(self) -> u32 { self.count_ones() }
27            #[inline] fn count_zeros(self) -> u32 { self.count_zeros() }
28            #[inline] fn leading_zeros(self) -> u32 { self.leading_zeros() }
29            #[inline] fn trailing_zeros(self) -> u32 { self.trailing_zeros() }
30            #[inline] fn leading_ones(self) -> u32 { self.leading_ones() }
31            #[inline] fn trailing_ones(self) -> u32 { self.trailing_ones() }
32        })*
33    };
34}
35
36impl_bit_counting!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);