Struct BitReader

Source
pub struct BitReader<R, E: Endianness> { /* private fields */ }
Expand description

For reading non-aligned bits from a stream of bytes in a given endianness.

This will read exactly as many whole bytes needed to return the requested number of bits. It may cache up to a single partial byte but no more.

Implementations§

Source§

impl<R, E: Endianness> BitReader<R, E>

Source

pub fn new(reader: R) -> BitReader<R, E>

Wraps a BitReader around something that implements Read

Source

pub fn endian(reader: R, _endian: E) -> BitReader<R, E>

Wraps a BitReader around something that implements Read with the given endianness.

Examples found in repository?
examples/flac-metadata-read.rs (line 94)
90fn main() {
91    // test FLAC file data
92    let flac = include_bytes!("data/metadata-only.flac");
93
94    let mut reader = BitReader::endian(flac.as_slice(), BigEndian);
95
96    // stream marker
97    assert_eq!(&reader.read_to::<[u8; 4]>().unwrap(), b"fLaC");
98
99    // metadata block header
100    assert_eq!(
101        reader.parse::<BlockHeader>().unwrap(),
102        BlockHeader {
103            last_block: false,
104            block_type: 0,
105            block_size: 34
106        }
107    );
108
109    // STREAMINFO block
110    assert_eq!(
111        dbg!(reader.parse::<Streaminfo>().unwrap()),
112        Streaminfo {
113            minimum_block_size: 4096,
114            maximum_block_size: 4096,
115            minimum_frame_size: 1542,
116            maximum_frame_size: 8546,
117            sample_rate: 44100,
118            channels: NonZero::new(2).unwrap(),
119            bits_per_sample: NonZero::new(16).unwrap(),
120            total_samples: 304844,
121            md5: *b"\xFA\xF2\x69\x2F\xFD\xEC\x2D\x5B\x30\x01\x76\xB4\x62\x88\x7D\x92",
122        }
123    );
124
125    // metadata block header
126    assert_eq!(
127        dbg!(reader.parse::<BlockHeader>().unwrap()),
128        BlockHeader {
129            last_block: false,
130            block_type: 4,
131            block_size: 122
132        }
133    );
134
135    // VORBIS_COMMENT block
136    assert_eq!(
137        dbg!(reader.parse::<VorbisComment>().unwrap()),
138        VorbisComment {
139            vendor: "reference libFLAC 1.1.4 20070213".to_string(),
140            comment: vec![
141                "title=2ch 44100  16bit".to_string(),
142                "album=Test Album".to_string(),
143                "artist=Assorted".to_string(),
144                "tracknumber=1".to_string(),
145            ],
146        }
147    );
148}
Source

pub fn into_reader(self) -> R

Unwraps internal reader and disposes of BitReader.

§Warning

Any unread partial bits are discarded.

Source§

impl<R: Read, E: Endianness> BitReader<R, E>

Source

pub fn reader(&mut self) -> Option<&mut R>

If stream is byte-aligned, provides mutable reference to internal reader. Otherwise returns None

Source

pub fn aligned_reader(&mut self) -> &mut R

Returns byte-aligned mutable reference to internal reader.

Bytes aligns stream if it is not already aligned.

Source

pub fn into_bytereader(self) -> ByteReader<R, E>

Converts BitReader to ByteReader in the same endianness.

§Warning

Any unread partial bits are discarded.

Source

pub fn bytereader(&mut self) -> Option<ByteReader<&mut R, E>>

If stream is byte-aligned, provides temporary ByteReader in the same endianness. Otherwise returns None

§Warning

Any reader bits left over when ByteReader is dropped are lost.

Source§

impl<R, E> BitReader<R, E>
where E: Endianness, R: Read + Seek,

Source

pub fn seek_bits(&mut self, from: SeekFrom) -> Result<u64>

§Example
use std::io::{Read, Cursor, SeekFrom};
use bitstream_io::{BigEndian, BitReader, BitRead};
let data = [0x00, 0xFF];
let mut reader = BitReader::endian(Cursor::new(&data), BigEndian);
assert_eq!(reader.position_in_bits().unwrap(), 0);

let pos = reader.seek_bits(SeekFrom::Start(5)).unwrap();
assert!(pos == 5 && 5 == reader.position_in_bits().unwrap());

let pos = reader.seek_bits(SeekFrom::Current(-2)).unwrap();
assert!(pos == 3 && 3 == reader.position_in_bits().unwrap());

let pos = reader.seek_bits(SeekFrom::End(5)).unwrap();
assert!(pos == 11 && 11 == reader.position_in_bits().unwrap());
Source

pub fn position_in_bits(&mut self) -> Result<u64>

§Example
use std::fs::read;
use std::io::{Read, Cursor, SeekFrom};
use bitstream_io::{BigEndian, BitReader, BitRead};
let data = [0x00, 0xFF];
let mut reader = BitReader::endian(Cursor::new(&data), BigEndian);
assert_eq!(reader.position_in_bits().unwrap(), 0);

let _: i32 = reader.read_signed::<5, _>().unwrap();
assert_eq!(reader.position_in_bits().unwrap(), 5);

reader.read_bit().unwrap();
assert_eq!(reader.position_in_bits().unwrap(), 6);

Trait Implementations§

Source§

impl<R: Read, E: Endianness> BitRead for BitReader<R, E>

Source§

fn skip(&mut self, bits: u32) -> Result<()>

§Examples
use std::io::Read;
use bitstream_io::{BigEndian, BitReader, BitRead};
let data = [0b10110111];
let mut reader = BitReader::endian(data.as_slice(), BigEndian);
assert!(reader.skip(3).is_ok());
assert_eq!(reader.read::<5, u8>().unwrap(), 0b10111);
use std::io::Read;
use bitstream_io::{LittleEndian, BitReader, BitRead};
let data = [0b10110111];
let mut reader = BitReader::endian(data.as_slice(), LittleEndian);
assert!(reader.skip(3).is_ok());
assert_eq!(reader.read::<5, u8>().unwrap(), 0b10110);
Source§

fn read_bytes(&mut self, buf: &mut [u8]) -> Result<()>

§Example
use std::io::Read;
use bitstream_io::{BigEndian, BitReader, BitRead};
let data = b"foobar";
let mut reader = BitReader::endian(data.as_slice(), BigEndian);
assert!(reader.skip(24).is_ok());
let mut buf = [0;3];
assert!(reader.read_bytes(&mut buf).is_ok());
assert_eq!(&buf, b"bar");
Source§

fn read_bit(&mut self) -> Result<bool>

Reads a single bit from the stream. true indicates 1, false indicates 0 Read more
Source§

fn read_unsigned_counted<const BITS: u32, U>( &mut self, bits: BitCount<BITS>, ) -> Result<U>
where U: UnsignedInteger,

Reads an unsigned value from the stream with the given number of bits. Read more
Source§

fn read_unsigned<const BITS: u32, U>(&mut self) -> Result<U>
where U: UnsignedInteger,

Reads an unsigned value from the stream with the given constant number of bits. Read more
Source§

fn read_signed_counted<const MAX: u32, S>( &mut self, bits: impl TryInto<SignedBitCount<MAX>>, ) -> Result<S>
where S: SignedInteger,

Reads a twos-complement signed value from the stream with the given number of bits. Read more
Source§

fn read_signed<const BITS: u32, S>(&mut self) -> Result<S>
where S: SignedInteger,

Reads a twos-complement signed value from the stream with the given constant number of bits. Read more
Source§

fn read_to<V>(&mut self) -> Result<V>
where V: Primitive,

Reads whole value from the stream whose size in bits is equal to its type’s size. Read more
Source§

fn read_as_to<F, V>(&mut self) -> Result<V>
where F: Endianness, V: Primitive,

Reads whole value from the stream whose size in bits is equal to its type’s size in an endianness that may be different from the stream’s endianness. Read more
Source§

fn read_unary<const STOP_BIT: u8>(&mut self) -> Result<u32>

Counts the number of bits in the stream until STOP_BIT and returns the amount read. STOP_BIT must be 0 or 1. Because this field is variably-sized and may be large, its output is always a u32 type. Read more
Source§

fn byte_aligned(&self) -> bool

Returns true if the stream is aligned at a whole byte. Read more
Source§

fn byte_align(&mut self)

Throws away all unread bit values until the next whole byte. Does nothing if the stream is already aligned. Read more
Source§

fn read<const BITS: u32, I>(&mut self) -> Result<I>
where I: Integer,

Reads a signed or unsigned value from the stream with the given constant number of bits. Read more
Source§

fn read_var<I>(&mut self, bits: u32) -> Result<I>
where I: Integer + Sized,

Reads a signed or unsigned value from the stream with the given variable number of bits. Read more
Source§

fn read_count<const MAX: u32>(&mut self) -> Result<BitCount<MAX>>

Given a desired maximum value for a bit count, reads the necessary bits to fill up to that amount. Read more
Source§

fn read_counted<const MAX: u32, I>(&mut self, bits: BitCount<MAX>) -> Result<I>
where I: Integer + Sized,

Reads a signed or unsigned value from the stream with the given number of bits. Read more
Source§

fn read_unsigned_var<U>(&mut self, bits: u32) -> Result<U>
where U: UnsignedInteger,

Reads an unsigned value from the stream with the given number of bits. Read more
Source§

fn read_signed_var<S>(&mut self, bits: u32) -> Result<S>
where S: SignedInteger,

Reads a twos-complement signed value from the stream with the given number of bits. Read more
Source§

fn read_const<const BITS: u32, const VALUE: u32, E>( &mut self, err: E, ) -> Result<(), E>
where E: From<Error>,

Reads the given constant value from the stream with the given number of bits. Read more
Source§

fn read_to_bytes<const SIZE: usize>(&mut self) -> Result<[u8; SIZE]>

👎Deprecated since 1.8.0: use read_to() method instead
Completely fills a whole buffer with bytes and returns it. If the stream is already byte-aligned, it will map to a faster read_exact call. Otherwise it will read bytes individually in 8-bit increments. Read more
Source§

fn read_to_vec(&mut self, bytes: usize) -> Result<Vec<u8>>

Completely fills a vector of bytes and returns it. If the stream is already byte-aligned, it will map to a faster read_exact call. Otherwise it will read bytes individually in 8-bit increments. Read more
Source§

fn parse<F: FromBitStream>(&mut self) -> Result<F, F::Error>

Parses and returns complex type
Source§

fn parse_with<'a, F: FromBitStreamWith<'a>>( &mut self, context: &F::Context, ) -> Result<F, F::Error>

Parses and returns complex type with context
Source§

fn read_huffman<T>(&mut self) -> Result<T::Symbol>
where T: FromBits,

Given a compiled Huffman tree, reads bits from the stream until the next symbol is encountered. Read more
Source§

fn by_ref(&mut self) -> &mut Self

Creates a “by reference” adaptor for this BitRead Read more
Source§

impl<R: Clone, E: Clone + Endianness> Clone for BitReader<R, E>

Source§

fn clone(&self) -> BitReader<R, E>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<R: Debug, E: Debug + Endianness> Debug for BitReader<R, E>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<R, E> Freeze for BitReader<R, E>
where R: Freeze,

§

impl<R, E> RefUnwindSafe for BitReader<R, E>

§

impl<R, E> Send for BitReader<R, E>
where R: Send, E: Send,

§

impl<R, E> Sync for BitReader<R, E>
where R: Sync, E: Sync,

§

impl<R, E> Unpin for BitReader<R, E>
where R: Unpin, E: Unpin,

§

impl<R, E> UnwindSafe for BitReader<R, E>
where R: UnwindSafe, E: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<R> BitRead2 for R
where R: BitRead,

Source§

fn read_bit(&mut self) -> Result<bool, Error>

Reads a single bit from the stream. true indicates 1, false indicates 0 Read more
Source§

fn read<I>(&mut self, bits: u32) -> Result<I, Error>
where I: Integer,

Reads an unsigned value from the stream with the given number of bits. Read more
Source§

fn read_in<const BITS: u32, I>(&mut self) -> Result<I, Error>
where I: Integer,

Reads an unsigned value from the stream with the given constant number of bits. Read more
Source§

fn read_signed<S>(&mut self, bits: u32) -> Result<S, Error>
where S: SignedInteger,

Reads a twos-complement signed value from the stream with the given number of bits. Read more
Source§

fn read_signed_in<const BITS: u32, S>(&mut self) -> Result<S, Error>
where S: SignedInteger,

Reads a twos-complement signed value from the stream with the given constant number of bits. Read more
Source§

fn read_to<V>(&mut self) -> Result<V, Error>
where V: Primitive,

Reads whole value from the stream whose size in bits is equal to its type’s size. Read more
Source§

fn read_as_to<F, V>(&mut self) -> Result<V, Error>
where F: Endianness, V: Primitive,

Reads whole value from the stream whose size in bits is equal to its type’s size in an endianness that may be different from the stream’s endianness. Read more
Source§

fn skip(&mut self, bits: u32) -> Result<(), Error>

Skips the given number of bits in the stream. Since this method does not need an accumulator, it may be slightly faster than reading to an empty variable. In addition, since there is no accumulator, there is no upper limit on the number of bits which may be skipped. These bits are still read from the stream, however, and are never skipped via a seek method. Read more
Source§

fn read_bytes(&mut self, buf: &mut [u8]) -> Result<(), Error>

Completely fills the given buffer with whole bytes. If the stream is already byte-aligned, it will map to a faster read_exact call. Otherwise it will read bytes individually in 8-bit increments. Read more
Source§

fn read_unary0(&mut self) -> Result<u32, Error>

Counts the number of 1 bits in the stream until the next 0 bit and returns the amount read. Because this field is variably-sized and may be large, its output is always a u32 type. Read more
Source§

fn read_unary1(&mut self) -> Result<u32, Error>

Counts the number of 0 bits in the stream until the next 1 bit and returns the amount read. Because this field is variably-sized and may be large, its output is always a u32 type. Read more
Source§

fn byte_aligned(&self) -> bool

Returns true if the stream is aligned at a whole byte.
Source§

fn byte_align(&mut self)

Throws away all unread bit values until the next whole byte. Does nothing if the stream is already aligned.
Source§

fn read_to_bytes<const SIZE: usize>(&mut self) -> Result<[u8; SIZE]>

👎Deprecated since 1.8.0: use read_to() method instead
Completely fills a whole buffer with bytes and returns it. If the stream is already byte-aligned, it will map to a faster read_exact call. Otherwise it will read bytes individually in 8-bit increments. Read more
Source§

fn read_to_vec(&mut self, bytes: usize) -> Result<Vec<u8>>

Completely fills a vector of bytes and returns it. If the stream is already byte-aligned, it will map to a faster read_exact call. Otherwise it will read bytes individually in 8-bit increments. Read more
Source§

fn parse<F: FromBitStream>(&mut self) -> Result<F, F::Error>
where Self: BitRead,

Parses and returns complex type
Source§

fn parse_with<'a, F: FromBitStreamWith<'a>>( &mut self, context: &F::Context, ) -> Result<F, F::Error>
where Self: BitRead,

Parses and returns complex type with context
Source§

fn read_huffman<T>(&mut self) -> Result<T::Symbol>
where T: FromBits,

Given a compiled Huffman tree, reads bits from the stream until the next symbol is encountered. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.