From b57d721ad6af02987709c56785d4cd7b12d22d01 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Sun, 26 Nov 2023 16:55:25 +0000 Subject: [PATCH] Add `NonZero*::count_ones` --- library/core/src/num/nonzero.rs | 37 +++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs index cc94ee280c684..1e8923aabde9b 100644 --- a/library/core/src/num/nonzero.rs +++ b/library/core/src/num/nonzero.rs @@ -1153,6 +1153,43 @@ macro_rules! nonzero_unsigned_signed_operations { // so the result cannot be zero. unsafe { $Ty::new_unchecked(self.get().saturating_pow(other)) } } + + /// 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 = "none")] + #[rustc_const_unstable(feature = "non_zero_count_ones", issue = "none")] + #[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 is non-zero. + unsafe { NonZeroU32::new_unchecked(self.get().count_ones()) } + } } )+ }