tufazip_arith/
bitstream.rs1use std::fs::File;
2use std::io::{BufWriter, Read, Seek, SeekFrom, Write};
3
4use serde::{Deserialize, Serialize};
5
6use crate::error::ArithError;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
10pub struct BitInputState {
11 pub file_position: u64,
13 pub current_byte: Option<u8>,
15 pub num_bits_remaining: u8,
17}
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21pub struct BitOutputState {
22 pub file_position: u64,
24 pub current_byte: u8,
26 pub num_bits_filled: u8,
28}
29
30#[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 pub fn new(input: R) -> Self {
41 Self {
42 input,
43 current_byte: Some(0),
44 num_bits_remaining: 0,
45 }
46 }
47
48 #[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 pub fn read_bit_no_eof(&mut self) -> Result<u8, ArithError> {
79 self.read_bit()?.ok_or(ArithError::UnexpectedEof)
80 }
81
82 pub fn get_ref(&self) -> &R {
84 &self.input
85 }
86
87 pub fn get_mut(&mut self) -> &mut R {
89 &mut self.input
90 }
91
92 pub fn into_inner(self) -> R {
94 self.input
95 }
96}
97
98impl<R: Read + Seek> BitInputStream<R> {
99 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 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#[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 pub fn new(output: W) -> Self {
144 Self {
145 output,
146 current_byte: 0,
147 num_bits_filled: 0,
148 }
149 }
150
151 #[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 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 pub fn flush(&mut self) -> Result<(), ArithError> {
190 self.output.flush()?;
191 Ok(())
192 }
193
194 pub fn get_ref(&self) -> &W {
196 &self.output
197 }
198
199 pub fn get_mut(&mut self) -> &mut W {
201 &mut self.output
202 }
203
204 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 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 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 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 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}