Skip to content

Commit b57d721

Browse files
committed
Add NonZero*::count_ones
1 parent 0b8a61b commit b57d721

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
@@ -1153,6 +1153,43 @@ macro_rules! nonzero_unsigned_signed_operations {
11531153
// so the result cannot be zero.
11541154
unsafe { $Ty::new_unchecked(self.get().saturating_pow(other)) }
11551155
}
1156+
1157+
/// Returns the number of ones in the binary representation of `self`.
1158+
///
1159+
/// # Examples
1160+
///
1161+
/// Basic usage:
1162+
///
1163+
/// ```
1164+
/// #![feature(non_zero_count_ones)]
1165+
/// # fn main() { test().unwrap(); }
1166+
/// # fn test() -> Option<()> {
1167+
#[doc = concat!("# use std::num::{self, ", stringify!($Ty), "};")]
1168+
///
1169+
/// let one = num::NonZeroU32::new(1)?;
1170+
/// let three = num::NonZeroU32::new(3)?;
1171+
#[doc = concat!("let a = ", stringify!($Ty), "::new(0b100_0000)?;")]
1172+
#[doc = concat!("let b = ", stringify!($Ty), "::new(0b100_0011)?;")]
1173+
///
1174+
/// assert_eq!(a.count_ones(), one);
1175+
/// assert_eq!(b.count_ones(), three);
1176+
/// # Some(())
1177+
/// # }
1178+
/// ```
1179+
///
1180+
#[unstable(feature = "non_zero_count_ones", issue = "none")]
1181+
#[rustc_const_unstable(feature = "non_zero_count_ones", issue = "none")]
1182+
#[doc(alias = "popcount")]
1183+
#[doc(alias = "popcnt")]
1184+
#[must_use = "this returns the result of the operation, \
1185+
without modifying the original"]
1186+
#[inline(always)]
1187+
pub const fn count_ones(self) -> NonZeroU32 {
1188+
// SAFETY:
1189+
// `self` is non-zero, which means it has at least one bit set, which means
1190+
// that the result is non-zero.
1191+
unsafe { NonZeroU32::new_unchecked(self.get().count_ones()) }
1192+
}
11561193
}
11571194
)+
11581195
}

0 commit comments

Comments
 (0)