diff options
| author | Maybe Waffle <waffle.lapkin@tasking.com> | 2023-11-26 16:55:25 +0000 |
|---|---|---|
| committer | Maybe Waffle <waffle.lapkin@gmail.com> | 2024-01-24 00:15:14 +0000 |
| commit | 0b1d7ffbd4d5c0546ccab819971f1d87a2d76d62 (patch) | |
| tree | bd7d3eb96a6d8dc2671810bba168b03418a1478b | |
| parent | 5d3d3479d774754856db2db3e439dfb88ef3c52f (diff) | |
| download | rust-0b1d7ffbd4d5c0546ccab819971f1d87a2d76d62.tar.gz rust-0b1d7ffbd4d5c0546ccab819971f1d87a2d76d62.zip | |
Add `NonZero*::count_ones`
| -rw-r--r-- | library/core/src/num/nonzero.rs | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs index a59195105d6..52edb757ba9 100644 --- a/library/core/src/num/nonzero.rs +++ b/library/core/src/num/nonzero.rs @@ -285,6 +285,43 @@ macro_rules! nonzero_integer { unsafe { intrinsics::cttz_nonzero(self.get() as $UnsignedPrimitive) as u32 } } + /// Returns the number of ones in the binary representation of `self`. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(non_zero_count_ones)] + /// # fn main() { test().unwrap(); } + /// # fn test() -> Option<()> { + #[doc = concat!("# use std::num::{self, ", stringify!($Ty), "};")] + /// + /// let one = num::NonZeroU32::new(1)?; + /// let three = num::NonZeroU32::new(3)?; + #[doc = concat!("let a = ", stringify!($Ty), "::new(0b100_0000)?;")] + #[doc = concat!("let b = ", stringify!($Ty), "::new(0b100_0011)?;")] + /// + /// assert_eq!(a.count_ones(), one); + /// assert_eq!(b.count_ones(), three); + /// # Some(()) + /// # } + /// ``` + /// + #[unstable(feature = "non_zero_count_ones", issue = "120287")] + #[rustc_const_unstable(feature = "non_zero_count_ones", issue = "120287")] + #[doc(alias = "popcount")] + #[doc(alias = "popcnt")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn count_ones(self) -> NonZeroU32 { + // SAFETY: + // `self` is non-zero, which means it has at least one bit set, which means + // that the result of `count_ones` is non-zero. + unsafe { NonZeroU32::new_unchecked(self.get().count_ones()) } + } + nonzero_integer_signedness_dependent_methods! { Self = $Ty, Primitive = $signedness $Int, |
