Created
March 19, 2018 02:55
-
-
Save unixpickle/3e311ac7919de418b89548ee8f57d2e1 to your computer and use it in GitHub Desktop.
Generic bit reader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Welcome to hell! | |
pub struct BitReader<T: Shr<usize> + BitAnd + PartialEq + From<u8> + Copy> { | |
value: T, | |
bits_remaining: usize | |
} | |
impl<T: Shr<usize> + BitAnd + PartialEq + From<u8> + Copy> BitReader<T> | |
where <T as BitAnd>::Output: PartialEq<T>, | |
T: From<<T as Shr<usize>>::Output> { | |
pub fn new(value: T) -> Self { | |
BitReader{ | |
value: value, | |
bits_remaining: size_of::<T>() | |
} | |
} | |
pub fn read_bit(&mut self) -> Option<bool> { | |
if self.bits_remaining == 0 { | |
None | |
} else { | |
self.bits_remaining -= 1; | |
let result = (self.value & From::from(1u8)) == From::from(0); | |
self.value = From::from(self.value >> 1usize); | |
Some(result) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment