From ff3b5ad71e47195167ea807794e8adea23badbd0 Mon Sep 17 00:00:00 2001 From: ltdk Date: Sun, 14 Mar 2021 19:02:34 -0400 Subject: [PATCH] Add leading_ones and trailing_ones to PrimInt --- build.rs | 2 ++ src/int.rs | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/build.rs b/build.rs index 816ddadd..a0bca14b 100644 --- a/build.rs +++ b/build.rs @@ -16,5 +16,7 @@ fn main() { "has_to_int_unchecked", ); + ac.emit_path_cfg("1.trailing_ones()", "has_leading_trailing_ones"); + autocfg::rerun_path("build.rs"); } diff --git a/src/int.rs b/src/int.rs index 10e751a9..e51d6bc4 100644 --- a/src/int.rs +++ b/src/int.rs @@ -78,6 +78,22 @@ pub trait PrimInt: /// ``` fn count_zeros(self) -> u32; + /// Returns the number of leading ones in the binary representation + /// of `self`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0xF00Du16; + /// + /// assert_eq!(n.leading_ones(), 4); + /// ``` + fn leading_ones(self) -> u32 { + (!self).leading_zeros() + } + /// Returns the number of leading zeros in the binary representation /// of `self`. /// @@ -92,6 +108,22 @@ pub trait PrimInt: /// ``` fn leading_zeros(self) -> u32; + /// Returns the number of trailing ones in the binary representation + /// of `self`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0xBEEFu16; + /// + /// assert_eq!(n.trailing_ones(), 4); + /// ``` + fn trailing_ones(self) -> u32 { + (!self).trailing_zeros() + } + /// Returns the number of trailing zeros in the binary representation /// of `self`. /// @@ -319,11 +351,23 @@ macro_rules! prim_int_impl { <$T>::count_zeros(self) } + #[cfg(has_leading_leading_ones)] + #[inline] + fn leading_ones(self) -> u32 { + <$T>::leading_ones(self) + } + #[inline] fn leading_zeros(self) -> u32 { <$T>::leading_zeros(self) } + #[cfg(has_leading_trailing_ones)] + #[inline] + fn trailing_ones(self) -> u32 { + <$T>::trailing_ones(self) + } + #[inline] fn trailing_zeros(self) -> u32 { <$T>::trailing_zeros(self)