lib.rs |
BitReader is a helper type to extract strings of bits from a slice of bytes.
Here is how you read first a single bit, then three bits and finally four bits from a byte
buffer:
```
use bitreader::BitReader;
let slice_of_u8 = &[0b1000_1111];
let mut reader = BitReader::new(slice_of_u8);
// You probably should use try! or some other error handling mechanism in real code if the
// length of the input is not known in advance.
let a_single_bit = reader.read_u8(1).unwrap();
assert_eq!(a_single_bit, 1);
let more_bits = reader.read_u8(3).unwrap();
assert_eq!(more_bits, 0);
let last_bits_of_byte = reader.read_u8(4).unwrap();
assert_eq!(last_bits_of_byte, 0b1111);
```
You can naturally read bits from longer buffer of data than just a single byte.
As you read bits, the internal cursor of BitReader moves on along the stream of bits. Big
endian format is assumed when reading the multi-byte values. BitReader supports reading maximum
of 64 bits at a time (with read_u64). Reading signed values directly is not supported at the
moment.
The reads do not need to be aligned in any particular way.
Reading zero bits is a no-op.
You can also skip over a number of bits, in which case there is no arbitrary small limits like
when reading the values to a variable. However, you can not seek past the end of the slice,
either when reading or when skipping bits.
Note that the code will likely not work correctly if the slice is longer than 2^61 bytes, but
exceeding that should be pretty unlikely. Let's get back to this when people read exabytes of
information one bit at a time. |
17157 |