mirror of
https://codeberg.org/icewind/bitbuffer.git
synced 2026-06-03 16:44:06 +02:00
add reserve_byte_length
This commit is contained in:
parent
ceea28d500
commit
c090180a14
3 changed files with 26 additions and 2 deletions
|
|
@ -1,6 +1,6 @@
|
||||||
[package]
|
[package]
|
||||||
name = "bitbuffer"
|
name = "bitbuffer"
|
||||||
version = "0.9.4"
|
version = "0.9.5"
|
||||||
authors = ["Robin Appelman <robin@icewind.nl>"]
|
authors = ["Robin Appelman <robin@icewind.nl>"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
description = "Reading bit sequences from a byte slice"
|
description = "Reading bit sequences from a byte slice"
|
||||||
|
|
|
||||||
|
|
@ -329,6 +329,9 @@ impl<'a, E: Endianness> FixedWriteBuffer<'a, E> {
|
||||||
|
|
||||||
/// Push up to an usize worth of bits
|
/// Push up to an usize worth of bits
|
||||||
fn push_bits(&mut self, bits: usize, count: usize) {
|
fn push_bits(&mut self, bits: usize, count: usize) {
|
||||||
|
if count == 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
debug_assert!(count < USIZE_BITS - 8);
|
debug_assert!(count < USIZE_BITS - 8);
|
||||||
assert!(self.bit_len + count <= self.bit_size);
|
assert!(self.bit_len + count <= self.bit_size);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -305,6 +305,27 @@ where
|
||||||
let start = tail.bit_len();
|
let start = tail.bit_len();
|
||||||
body_fn(&mut tail)?;
|
body_fn(&mut tail)?;
|
||||||
let end = tail.bit_len();
|
let end = tail.bit_len();
|
||||||
head.write_sized(&(end - start), length_bit_size)
|
let bit_len = end - start;
|
||||||
|
head.write_sized(&bit_len, length_bit_size)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write the length in bytes of a section before the section, the section will be 0 padded to an even byte length
|
||||||
|
pub fn reserve_byte_length<F: Fn(&mut BitWriteStream<E>) -> Result<()>>(
|
||||||
|
&mut self,
|
||||||
|
length_bit_size: usize,
|
||||||
|
body_fn: F,
|
||||||
|
) -> Result<()> {
|
||||||
|
let (mut head, mut tail) = self.reserve(length_bit_size);
|
||||||
|
let start = tail.bit_len();
|
||||||
|
body_fn(&mut tail)?;
|
||||||
|
let end = tail.bit_len();
|
||||||
|
let bit_len = end - start;
|
||||||
|
|
||||||
|
let pad_len = (8 - (bit_len & 7)) & 7;
|
||||||
|
tail.push_bits(0, pad_len);
|
||||||
|
|
||||||
|
let byte_len = (bit_len + pad_len) / 8;
|
||||||
|
|
||||||
|
head.write_sized(&byte_len, length_bit_size)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue