Skip to content

Commit

Permalink
Add reverse_bits to integer types
Browse files Browse the repository at this point in the history
  • Loading branch information
Amanieu committed Mar 6, 2018
1 parent 02e021b commit 24fb4b7
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
54 changes: 54 additions & 0 deletions src/libcore/num/mod.rs
Expand Up @@ -321,6 +321,33 @@ $EndFeature, "
(self as $UnsignedT).swap_bytes() as Self
}

/// Reverses the bit pattern of the integer.
///
/// # Examples
///
/// Please note that this example is shared between integer types.
/// Which explains why `i16` is used here.
///
/// Basic usage:
///
/// ```
/// #![feature(reverse_bits)]
///
/// let n: i16 = 0b0000000_01010101;
/// assert_eq!(n, 85);
///
/// let m = n.reverse_bits();
///
/// assert_eq!(m as u16, 0b10101010_00000000);
/// assert_eq!(m, -22016);
/// ```
#[unstable(feature = "reverse_bits", issue = "48763")]
#[cfg(not(stage0))]
#[inline]
pub fn reverse_bits(self) -> Self {
(self as $UnsignedT).reverse_bits() as Self
}

doc_comment! {
concat!("Converts an integer from big endian to the target's endianness.
Expand Down Expand Up @@ -1773,6 +1800,33 @@ assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
unsafe { intrinsics::bswap(self as $ActualT) as Self }
}

/// Reverses the bit pattern of the integer.
///
/// # Examples
///
/// Basic usage:
///
/// Please note that this example is shared between integer types.
/// Which explains why `u16` is used here.
///
/// ```
/// #![feature(reverse_bits)]
///
/// let n: u16 = 0b0000000_01010101;
/// assert_eq!(n, 85);
///
/// let m = n.reverse_bits();
///
/// assert_eq!(m, 0b10101010_00000000);
/// assert_eq!(m, 43520);
/// ```
#[unstable(feature = "reverse_bits", issue = "48763")]
#[cfg(not(stage0))]
#[inline]
pub fn reverse_bits(self) -> Self {
unsafe { intrinsics::bitreverse(self as $ActualT) as Self }
}

doc_comment! {
concat!("Converts an integer from big endian to the target's endianness.
Expand Down
1 change: 1 addition & 0 deletions src/libcore/tests/lib.rs
Expand Up @@ -46,6 +46,7 @@
#![feature(try_trait)]
#![feature(exact_chunks)]
#![feature(atomic_nand)]
#![feature(reverse_bits)]

extern crate core;
extern crate test;
Expand Down
11 changes: 11 additions & 0 deletions src/libcore/tests/num/uint_macros.rs
Expand Up @@ -97,6 +97,17 @@ mod tests {
assert_eq!(_1.swap_bytes(), _1);
}

#[test]
fn test_reverse_bits() {
assert_eq!(A.reverse_bits().reverse_bits(), A);
assert_eq!(B.reverse_bits().reverse_bits(), B);
assert_eq!(C.reverse_bits().reverse_bits(), C);

// Swapping these should make no difference
assert_eq!(_0.reverse_bits(), _0);
assert_eq!(_1.reverse_bits(), _1);
}

#[test]
fn test_le() {
assert_eq!($T::from_le(A.to_le()), A);
Expand Down

0 comments on commit 24fb4b7

Please sign in to comment.