Skip to main content

tufazip_arith/
bitstream.rs

1use std::fs::File;
2use std::io::{BufWriter, Read, Seek, SeekFrom, Write};
3
4use serde::{Deserialize, Serialize};
5
6use crate::error::ArithError;
7
8/// Exact serializable state of a [`BitInputStream`].
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
10pub struct BitInputState {
11    /// Byte offset of the underlying reader.
12    pub file_position: u64,
13    /// Currently buffered byte, or `None` once EOF has been reached.
14    pub current_byte: Option<u8>,
15    /// Number of unread bits remaining in `current_byte` (`0..=8`).
16    pub num_bits_remaining: u8,
17}
18
19/// Exact serializable state of a [`BitOutputStream`].
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21pub struct BitOutputState {
22    /// Byte offset of the underlying writer.
23    pub file_position: u64,
24    /// Bits currently accumulated for the next output byte.
25    pub current_byte: u8,
26    /// Number of bits accumulated in `current_byte` (`0..=7`).
27    pub num_bits_filled: u8,
28}
29
30/// Big-endian bit reader backed by a byte stream.
31#[derive(Debug)]
32pub struct BitInputStream<R> {
33    input: R,
34    current_byte: Option<u8>,
35    num_bits_remaining: u8,
36}
37
38impl<R: Read> BitInputStream<R> {
39    /// Constructs a bit input stream reading big-endian bits from `input`.
40    pub fn new(input: R) -> Self {
41        Self {
42            input,
43            current_byte: Some(0),
44            num_bits_remaining: 0,
45        }
46    }
47
48    /// Reads the next bit (`0` or `1`), or `None` once EOF is reached.
49    ///
50    /// # Errors
51    ///
52    /// Returns [`ArithError::Io`] if reading from the underlying byte stream fails.
53    #[inline]
54    pub fn read_bit(&mut self) -> Result<Option<u8>, ArithError> {
55        let Some(mut byte) = self.current_byte else {
56            return Ok(None);
57        };
58        if self.num_bits_remaining == 0 {
59            let mut buf = [0u8; 1];
60            let n = read_one_byte(&mut self.input, &mut buf)?;
61            if n == 0 {
62                self.current_byte = None;
63                return Ok(None);
64            }
65            byte = buf[0];
66            self.current_byte = Some(byte);
67            self.num_bits_remaining = 8;
68        }
69        self.num_bits_remaining -= 1;
70        Ok(Some((byte >> self.num_bits_remaining) & 1))
71    }
72
73    /// Reads the next bit (`0` or `1`), returning [`ArithError::UnexpectedEof`] at EOF.
74    ///
75    /// # Errors
76    ///
77    /// Returns [`ArithError::UnexpectedEof`] at EOF or [`ArithError::Io`] on read failure.
78    pub fn read_bit_no_eof(&mut self) -> Result<u8, ArithError> {
79        self.read_bit()?.ok_or(ArithError::UnexpectedEof)
80    }
81
82    /// Returns a shared reference to the underlying reader.
83    pub fn get_ref(&self) -> &R {
84        &self.input
85    }
86
87    /// Returns a mutable reference to the underlying reader.
88    pub fn get_mut(&mut self) -> &mut R {
89        &mut self.input
90    }
91
92    /// Consumes this stream and returns the underlying reader.
93    pub fn into_inner(self) -> R {
94        self.input
95    }
96}
97
98impl<R: Read + Seek> BitInputStream<R> {
99    /// Captures the exact stream position and buffered byte state for checkpointing.
100    ///
101    /// # Errors
102    ///
103    /// Returns [`ArithError::Io`] if querying the reader's stream position fails.
104    pub fn state(&mut self) -> Result<BitInputState, ArithError> {
105        let file_position = self.input.stream_position()?;
106        Ok(BitInputState {
107            file_position,
108            current_byte: self.current_byte,
109            num_bits_remaining: self.num_bits_remaining,
110        })
111    }
112
113    /// Restores a previously captured [`BitInputState`].
114    ///
115    /// # Errors
116    ///
117    /// Returns [`ArithError::InvalidStreamState`] if `num_bits_remaining > 8` or
118    /// [`ArithError::Io`] if seeking fails.
119    pub fn restore_state(&mut self, state: BitInputState) -> Result<(), ArithError> {
120        if state.num_bits_remaining > 8 {
121            return Err(ArithError::InvalidStreamState(format!(
122                "num_bits_remaining {} exceeds 8",
123                state.num_bits_remaining
124            )));
125        }
126        self.input.seek(SeekFrom::Start(state.file_position))?;
127        self.current_byte = state.current_byte;
128        self.num_bits_remaining = state.num_bits_remaining;
129        Ok(())
130    }
131}
132
133/// Big-endian bit writer backed by a byte stream.
134#[derive(Debug)]
135pub struct BitOutputStream<W> {
136    output: W,
137    current_byte: u8,
138    num_bits_filled: u8,
139}
140
141impl<W: Write> BitOutputStream<W> {
142    /// Constructs a bit output stream writing big-endian bits to `output`.
143    pub fn new(output: W) -> Self {
144        Self {
145            output,
146            current_byte: 0,
147            num_bits_filled: 0,
148        }
149    }
150
151    /// Writes a single bit (`0` or `1`) to the stream.
152    ///
153    /// # Errors
154    ///
155    /// Returns [`ArithError::InvalidBit`] if `bit > 1`, or [`ArithError::Io`] on write failure.
156    #[inline]
157    pub fn write_bit(&mut self, bit: u8) -> Result<(), ArithError> {
158        if bit > 1 {
159            return Err(ArithError::InvalidBit(bit));
160        }
161        self.current_byte = (self.current_byte << 1) | bit;
162        self.num_bits_filled += 1;
163        if self.num_bits_filled == 8 {
164            self.output.write_all(&[self.current_byte])?;
165            self.current_byte = 0;
166            self.num_bits_filled = 0;
167        }
168        Ok(())
169    }
170
171    /// Zero-pads any partial byte up to the next byte boundary and flushes the underlying writer.
172    ///
173    /// # Errors
174    ///
175    /// Returns [`ArithError::Io`] if writing or flushing fails.
176    pub fn finish_padding(&mut self) -> Result<(), ArithError> {
177        while self.num_bits_filled != 0 {
178            self.write_bit(0)?;
179        }
180        self.output.flush()?;
181        Ok(())
182    }
183
184    /// Flushes the underlying writer without padding the current partial byte.
185    ///
186    /// # Errors
187    ///
188    /// Returns [`ArithError::Io`] if flushing fails.
189    pub fn flush(&mut self) -> Result<(), ArithError> {
190        self.output.flush()?;
191        Ok(())
192    }
193
194    /// Returns a shared reference to the underlying writer.
195    pub fn get_ref(&self) -> &W {
196        &self.output
197    }
198
199    /// Returns a mutable reference to the underlying writer.
200    pub fn get_mut(&mut self) -> &mut W {
201        &mut self.output
202    }
203
204    /// Finishes padding, flushes, and returns the underlying writer.
205    ///
206    /// # Errors
207    ///
208    /// Returns [`ArithError::Io`] if padding or flushing fails.
209    pub fn into_inner(mut self) -> Result<W, ArithError> {
210        self.finish_padding()?;
211        Ok(self.output)
212    }
213}
214
215impl<W: Write + Seek> BitOutputStream<W> {
216    /// Flushes buffered full bytes and captures the exact output stream state for checkpointing.
217    ///
218    /// # Errors
219    ///
220    /// Returns [`ArithError::Io`] if flushing or querying stream position fails.
221    pub fn state(&mut self) -> Result<BitOutputState, ArithError> {
222        self.output.flush()?;
223        let file_position = self.output.stream_position()?;
224        Ok(BitOutputState {
225            file_position,
226            current_byte: self.current_byte,
227            num_bits_filled: self.num_bits_filled,
228        })
229    }
230
231    /// Restores a previously captured [`BitOutputState`] by seeking to `state.file_position`.
232    ///
233    /// When resuming onto an existing file on disk, prefer [`Self::restore_file_state`]
234    /// so any bytes written after the checkpoint are truncated.
235    ///
236    /// # Errors
237    ///
238    /// Returns [`ArithError::InvalidStreamState`] if `num_bits_filled >= 8`, or
239    /// [`ArithError::Io`] on flush/seek errors.
240    pub fn restore_state(&mut self, state: BitOutputState) -> Result<(), ArithError> {
241        if state.num_bits_filled >= 8 {
242            return Err(ArithError::InvalidStreamState(format!(
243                "num_bits_filled {} must be < 8",
244                state.num_bits_filled
245            )));
246        }
247        self.output.flush()?;
248        self.output.seek(SeekFrom::Start(state.file_position))?;
249        self.current_byte = state.current_byte;
250        self.num_bits_filled = state.num_bits_filled;
251        Ok(())
252    }
253}
254
255impl BitOutputStream<File> {
256    /// Restores a [`BitOutputState`] on a file, truncating any bytes beyond `file_position`.
257    ///
258    /// # Errors
259    ///
260    /// Returns [`ArithError::InvalidStreamState`] or [`ArithError::Io`].
261    pub fn restore_file_state(&mut self, state: BitOutputState) -> Result<(), ArithError> {
262        if state.num_bits_filled >= 8 {
263            return Err(ArithError::InvalidStreamState(format!(
264                "num_bits_filled {} must be < 8",
265                state.num_bits_filled
266            )));
267        }
268        self.output.flush()?;
269        self.output.set_len(state.file_position)?;
270        self.output.seek(SeekFrom::Start(state.file_position))?;
271        self.current_byte = state.current_byte;
272        self.num_bits_filled = state.num_bits_filled;
273        Ok(())
274    }
275}
276
277impl BitOutputStream<BufWriter<File>> {
278    /// Restores a [`BitOutputState`] on a buffered file, truncating any bytes beyond `file_position`.
279    ///
280    /// # Errors
281    ///
282    /// Returns [`ArithError::InvalidStreamState`] or [`ArithError::Io`].
283    pub fn restore_file_state(&mut self, state: BitOutputState) -> Result<(), ArithError> {
284        if state.num_bits_filled >= 8 {
285            return Err(ArithError::InvalidStreamState(format!(
286                "num_bits_filled {} must be < 8",
287                state.num_bits_filled
288            )));
289        }
290        self.output.flush()?;
291        self.output.get_mut().set_len(state.file_position)?;
292        self.output.seek(SeekFrom::Start(state.file_position))?;
293        self.current_byte = state.current_byte;
294        self.num_bits_filled = state.num_bits_filled;
295        Ok(())
296    }
297}
298
299fn read_one_byte<R: Read>(reader: &mut R, buf: &mut [u8; 1]) -> Result<usize, std::io::Error> {
300    loop {
301        match reader.read(buf) {
302            Ok(n) => return Ok(n),
303            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
304            Err(e) => return Err(e),
305        }
306    }
307}