提交 24fb4b76 编写于 作者: A Amanieu d'Antras

Add reverse_bits to integer types

上级 02e021b6
......@@ -321,6 +321,33 @@ pub fn swap_bytes(self) -> Self {
(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 @@ pub fn swap_bytes(self) -> Self {
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.
......
......@@ -46,6 +46,7 @@
#![feature(try_trait)]
#![feature(exact_chunks)]
#![feature(atomic_nand)]
#![feature(reverse_bits)]
extern crate core;
extern crate test;
......
......@@ -97,6 +97,17 @@ fn test_swap_bytes() {
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);
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册