Skip to content

Commit 0b1d7ff

Browse files
committed
Add NonZero*::count_ones
1 parent 5d3d347 commit 0b1d7ff

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
@@ -285,6 +285,43 @@ macro_rules! nonzero_integer {
285285
unsafe { intrinsics::cttz_nonzero(self.get() as $UnsignedPrimitive) as u32 }
286286
}
287287

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

0 commit comments

Comments
 (0)