Skip to content

Commit 93df4ad

Browse files
Merge #205
205: Add leading_ones and trailing_ones to PrimInt r=cuviper a=clarfonthey Since this was only stabilised in 1.46.0, it falls back to a naïve version on older versions. It seems unlikely that the version in libstd will ever be different from calling the zeros versions on !self, but for future-proofing, this defers to the libstd versions anyway. Co-authored-by: ltdk <[email protected]>
2 parents 305532d + 41a702c commit 93df4ad

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

build.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,5 +16,7 @@ fn main() {
1616
"has_to_int_unchecked",
1717
);
1818

19+
ac.emit_expression_cfg("1u32.trailing_ones()", "has_leading_trailing_ones");
20+
1921
autocfg::rerun_path("build.rs");
2022
}

src/int.rs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,22 @@ pub trait PrimInt:
7878
/// ```
7979
fn count_zeros(self) -> u32;
8080

81+
/// Returns the number of leading ones in the binary representation
82+
/// of `self`.
83+
///
84+
/// # Examples
85+
///
86+
/// ```
87+
/// use num_traits::PrimInt;
88+
///
89+
/// let n = 0xF00Du16;
90+
///
91+
/// assert_eq!(n.leading_ones(), 4);
92+
/// ```
93+
fn leading_ones(self) -> u32 {
94+
(!self).leading_zeros()
95+
}
96+
8197
/// Returns the number of leading zeros in the binary representation
8298
/// of `self`.
8399
///
@@ -92,6 +108,22 @@ pub trait PrimInt:
92108
/// ```
93109
fn leading_zeros(self) -> u32;
94110

111+
/// Returns the number of trailing ones in the binary representation
112+
/// of `self`.
113+
///
114+
/// # Examples
115+
///
116+
/// ```
117+
/// use num_traits::PrimInt;
118+
///
119+
/// let n = 0xBEEFu16;
120+
///
121+
/// assert_eq!(n.trailing_ones(), 4);
122+
/// ```
123+
fn trailing_ones(self) -> u32 {
124+
(!self).trailing_zeros()
125+
}
126+
95127
/// Returns the number of trailing zeros in the binary representation
96128
/// of `self`.
97129
///
@@ -319,11 +351,23 @@ macro_rules! prim_int_impl {
319351
<$T>::count_zeros(self)
320352
}
321353

354+
#[cfg(has_leading_leading_ones)]
355+
#[inline]
356+
fn leading_ones(self) -> u32 {
357+
<$T>::leading_ones(self)
358+
}
359+
322360
#[inline]
323361
fn leading_zeros(self) -> u32 {
324362
<$T>::leading_zeros(self)
325363
}
326364

365+
#[cfg(has_leading_trailing_ones)]
366+
#[inline]
367+
fn trailing_ones(self) -> u32 {
368+
<$T>::trailing_ones(self)
369+
}
370+
327371
#[inline]
328372
fn trailing_zeros(self) -> u32 {
329373
<$T>::trailing_zeros(self)

0 commit comments

Comments
 (0)