Crates.io | bitbuffer |
lib.rs | bitbuffer |
version | 0.11.0 |
source | src |
created_at | 2020-02-12 22:57:57.767102 |
updated_at | 2024-04-04 21:17:36.353988 |
description | Reading bit sequences from a byte slice |
homepage | |
repository | https://github.com/icewind1991/bitbuffer |
max_upload_size | |
id | 207852 |
size | 196,739 |
Tools for reading and writing data types of arbitrary bit length and might not be byte-aligned in the source data
The main way of reading the binary data is to first create a BitReadBuffer
,wrap it into a BitReadStream
and then read from the stream.
Once you have a BitStream, there are 2 different approaches of reading data
read_bool
, read_int
, read_float
, read_bytes
and read_string
BitRead
or BitReadSized
traits using read
and read_sized
BitRead
is for types that can be read without requiring any size info (e.g. null-terminal strings, floats, whole integers, etc)BitReadSized
is for types that require external sizing information to be read (fixed length strings, arbitrary length integersThe BitRead
and BitReadSized
traits can be used with #[derive]
if all fields implement BitRead
or BitReadSized
.
For writing the data you wrap the output Vec
into a BitWriteStream
which can then be used in a manner similar to the BitReadStream
write_bool
, write_int
, write_float
, write_bytes
and write_string
BitWrite
or BitWriteSized
traits using write
and write_sized
BitWrite
is for types that can be written without requiring any size info (e.g. null-terminal strings, floats, whole integers, etc)BitWriteSized
is for types that require external sizing information to be written (fixed length strings, arbitrary length integersJust like the read counterparts, BitWrite
and BitWriteSized
traits can be used with #[derive]
if all fields implement BitWrite
or BitWriteSized
.
use bitbuffer::{BitReadBuffer, LittleEndian, BitReadStream, BitRead, BitWrite, BitWriteStream};
#[derive(BitRead, BitWrite)]
struct ComplexType {
first: u8,
#[size = 15]
second: u16,
third: bool,
}
let bytes = vec![
0b1011_0101, 0b0110_1010, 0b1010_1100, 0b1001_1001,
0b1001_1001, 0b1001_1001, 0b1001_1001, 0b1110_0111
];
let buffer = BitReadBuffer::new(&bytes, LittleEndian);
let mut stream = BitReadStream::new(buffer);
let value: u8 = stream.read_int(7)?;
let complex: ComplexType = stream.read()?;
let mut write_bytes = vec![];
let mut write_stream = BitWriteStream::new(&mut write_bytes, LittleEndian);
write_stream.write_int(12, 7)?;
write_stream.write(&ComplexType {
first: 55,
second: 12,
third: true
})?;
Licensed under either of
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.