Skip to content

Instantly share code, notes, and snippets.

@unixpickle
Created March 19, 2018 02:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unixpickle/3e311ac7919de418b89548ee8f57d2e1 to your computer and use it in GitHub Desktop.
Save unixpickle/3e311ac7919de418b89548ee8f57d2e1 to your computer and use it in GitHub Desktop.
Generic bit reader
// 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