Trait twiddle::Twiddle [] [src]

pub trait Twiddle {
    fn mask(range: Range<usize>) -> Self;
    fn bit(self, bit: usize) -> bool;
    fn bits(self, range: Range<usize>) -> Self;
    fn replace(self, range: Range<usize>, bits: Self) -> Self;
    fn split<I>(self, lengths: I) -> Split<Self, I::IntoIter> where I: IntoIterator<Item=usize>, Self: Sized;
}

A trait for bit-twiddling utility functions.

Required Methods

Creates a bitmask from a range.

Example

let mask = u32::mask(9..0);
assert_eq!(mask, 0x3ff);

Returns a given bit as a boolean.

Example

let byte: u8 = 0b0100_0000;
if byte.bit(6) {
    println!("Bit 6 is set!")
}

Returns a set of bits.

Example

let word: u16 = 0b0011_0101_1000_0000;
assert_eq!(word.bits(12..8), 0b10101);

Replaces a set of bits with another.

Example

let word: u16 = 0b0000_1010_1010_0000;
assert_eq!(word.replace(7..4, 0b0001), 0b0000_1010_0001_0000);

Notes

  • If too many bits are given, the highest bits will be truncated.

Splits a number into an iterator over sets of bits.

Example

let byte: u8 = 0b1100_0111;
let vec: Vec<u8> = byte.split(vec![2, 3, 5]).collect();

assert_eq!(vec, vec![0b11, 0b000, 0b11100]);

Notes

  • The last set of bits will be zero-padded on the right end if there are not enough bits remaining in the number.

  • Once there are no more bits remaining, the iterator will return None even if there are more lengths remaining.

Implementors