Skip to content

Commit

Permalink
Encode: Add BitWriter::vec
Browse files Browse the repository at this point in the history
We often write bits to a byte vector.
BitWriter::vec generalizes this workflow by writing the result of any
bit operation into a byte vector, which it returns.
The caller doesn't have to worry about I/O errors that can never occur.
  • Loading branch information
uncomputable committed Dec 5, 2023
1 parent a950906 commit fc91f4e
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/bit_encoding/bitwriter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,42 @@ impl<W: io::Write> BitWriter<W> {
Ok(len)
}
}

// Implement for io::Sink to make vec() an associated function
// Implementing for a generic W would require callers to specify W, which is annoying
impl BitWriter<io::Sink> {
/// Write the result of a bit operation into a byte vector and return the vector.
///
/// I/O to a vector never fails.
pub fn vec<F>(f: F) -> Vec<u8>
where
F: FnOnce(&mut BitWriter<&mut Vec<u8>>) -> io::Result<usize>,
{
let mut bytes = Vec::new();
let mut bits = BitWriter::new(&mut bytes);
f(&mut bits).expect("I/O to vector never fails");
bits.flush_all().expect("I/O to vector never fails");
bytes
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::jet::Core;
use crate::node::CoreConstructible;
use crate::ConstructNode;
use std::sync::Arc;

#[test]
fn vec() {
let program = Arc::<ConstructNode<Core>>::unit();
let _ = BitWriter::vec(|w| program.encode(w));
}

#[test]
fn empty_vec() {
let vec = BitWriter::vec(|_| Ok(0));
assert!(vec.is_empty());
}
}

0 comments on commit fc91f4e

Please sign in to comment.