From 8d03d20e8bf6f487779e31ff4bd8daa059cb594e Mon Sep 17 00:00:00 2001 From: Christian Lewe Date: Tue, 21 Nov 2023 22:05:15 +0100 Subject: [PATCH] Encode: Add BitWriter::vec 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. --- src/bit_encoding/bitwriter.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/bit_encoding/bitwriter.rs b/src/bit_encoding/bitwriter.rs index a6a38fc0..8159a192 100644 --- a/src/bit_encoding/bitwriter.rs +++ b/src/bit_encoding/bitwriter.rs @@ -109,3 +109,36 @@ impl BitWriter { 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 { + /// 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) -> Vec + where + F: FnOnce(&mut BitWriter<&mut Vec>) -> io::Result, + { + let mut bytes = Vec::new(); + let mut bits = BitWriter::new(&mut bytes); + f(&mut bits).expect("I/O to vector never fails"); + debug_assert!(!bytes.is_empty()); + 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::>::unit(); + let _ = BitWriter::vec(|w| program.encode(w)); + } +}