Add reverse_bits to integer types

This commit is contained in:
Amanieu d'Antras 2018-02-27 04:34:55 +00:00
parent 02e021b6d4
commit 24fb4b7669
3 changed files with 66 additions and 0 deletions

View File

@ -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.
@ -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.

View File

@ -46,6 +46,7 @@
#![feature(try_trait)]
#![feature(exact_chunks)]
#![feature(atomic_nand)]
#![feature(reverse_bits)]
extern crate core;
extern crate test;

View File

@ -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);