@@ -1153,6 +1153,43 @@ macro_rules! nonzero_unsigned_signed_operations {
1153
1153
// so the result cannot be zero.
1154
1154
unsafe { $Ty:: new_unchecked( self . get( ) . saturating_pow( other) ) }
1155
1155
}
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
+ }
1156
1193
}
1157
1194
) +
1158
1195
}
0 commit comments