Skip to content

Commit

Permalink
Merge #205
Browse files Browse the repository at this point in the history
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 <usr@ltdk.xyz>
  • Loading branch information
bors[bot] and clarfonthey committed Jun 15, 2021
2 parents 305532d + 41a702c commit 93df4ad
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
2 changes: 2 additions & 0 deletions build.rs
Expand Up @@ -16,5 +16,7 @@ fn main() {
"has_to_int_unchecked",
);

ac.emit_expression_cfg("1u32.trailing_ones()", "has_leading_trailing_ones");

autocfg::rerun_path("build.rs");
}
44 changes: 44 additions & 0 deletions src/int.rs
Expand Up @@ -78,6 +78,22 @@ pub trait PrimInt:
/// ```
fn count_zeros(self) -> u32;

/// Returns the number of leading ones in the binary representation
/// of `self`.
///
/// # Examples
///
/// ```
/// use num_traits::PrimInt;
///
/// let n = 0xF00Du16;
///
/// assert_eq!(n.leading_ones(), 4);
/// ```
fn leading_ones(self) -> u32 {
(!self).leading_zeros()
}

/// Returns the number of leading zeros in the binary representation
/// of `self`.
///
Expand All @@ -92,6 +108,22 @@ pub trait PrimInt:
/// ```
fn leading_zeros(self) -> u32;

/// Returns the number of trailing ones in the binary representation
/// of `self`.
///
/// # Examples
///
/// ```
/// use num_traits::PrimInt;
///
/// let n = 0xBEEFu16;
///
/// assert_eq!(n.trailing_ones(), 4);
/// ```
fn trailing_ones(self) -> u32 {
(!self).trailing_zeros()
}

/// Returns the number of trailing zeros in the binary representation
/// of `self`.
///
Expand Down Expand Up @@ -319,11 +351,23 @@ macro_rules! prim_int_impl {
<$T>::count_zeros(self)
}

#[cfg(has_leading_leading_ones)]
#[inline]
fn leading_ones(self) -> u32 {
<$T>::leading_ones(self)
}

#[inline]
fn leading_zeros(self) -> u32 {
<$T>::leading_zeros(self)
}

#[cfg(has_leading_trailing_ones)]
#[inline]
fn trailing_ones(self) -> u32 {
<$T>::trailing_ones(self)
}

#[inline]
fn trailing_zeros(self) -> u32 {
<$T>::trailing_zeros(self)
Expand Down

0 comments on commit 93df4ad

Please sign in to comment.