Skip to content

Commit 3529d45

Browse files
authored
Rollup merge of #118326 - WaffleLapkin:nz_count_ones, r=scottmcm
Add `NonZero*::count_ones` This PR adds the following APIs to the standard library: ```rust impl NonZero* { pub const fn count_ones(self) -> NonZeroU32; } ``` This is potentially interesting, given that `count_ones` can't ever return 0. r? libs-api
2 parents 61e2b41 + 0b1d7ff commit 3529d45

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

library/core/src/num/nonzero.rs

+37
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,43 @@ macro_rules! nonzero_integer {
288288
unsafe { intrinsics::cttz_nonzero(self.get() as $UnsignedPrimitive) as u32 }
289289
}
290290

291+
/// Returns the number of ones in the binary representation of `self`.
292+
///
293+
/// # Examples
294+
///
295+
/// Basic usage:
296+
///
297+
/// ```
298+
/// #![feature(non_zero_count_ones)]
299+
/// # fn main() { test().unwrap(); }
300+
/// # fn test() -> Option<()> {
301+
#[doc = concat!("# use std::num::{self, ", stringify!($Ty), "};")]
302+
///
303+
/// let one = num::NonZeroU32::new(1)?;
304+
/// let three = num::NonZeroU32::new(3)?;
305+
#[doc = concat!("let a = ", stringify!($Ty), "::new(0b100_0000)?;")]
306+
#[doc = concat!("let b = ", stringify!($Ty), "::new(0b100_0011)?;")]
307+
///
308+
/// assert_eq!(a.count_ones(), one);
309+
/// assert_eq!(b.count_ones(), three);
310+
/// # Some(())
311+
/// # }
312+
/// ```
313+
///
314+
#[unstable(feature = "non_zero_count_ones", issue = "120287")]
315+
#[rustc_const_unstable(feature = "non_zero_count_ones", issue = "120287")]
316+
#[doc(alias = "popcount")]
317+
#[doc(alias = "popcnt")]
318+
#[must_use = "this returns the result of the operation, \
319+
without modifying the original"]
320+
#[inline(always)]
321+
pub const fn count_ones(self) -> NonZeroU32 {
322+
// SAFETY:
323+
// `self` is non-zero, which means it has at least one bit set, which means
324+
// that the result of `count_ones` is non-zero.
325+
unsafe { NonZeroU32::new_unchecked(self.get().count_ones()) }
326+
}
327+
291328
nonzero_integer_signedness_dependent_methods! {
292329
Self = $Ty,
293330
Primitive = $signedness $Int,

0 commit comments

Comments
 (0)