bitwise/
lib.rs

1//! # bitwise-io
2//!
3//! A simple wrapper around the `BufRead` and `Write` Trait for bitwise IO
4//!
5use std::io::{BufRead, Write, ErrorKind};
6use std::fmt::{Display, Formatter};
7use std::collections::VecDeque;
8
9
10/// Bit representation
11#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
12pub enum Bit {
13    Zero = 0,
14    One = 1,
15}
16
17/// Reader for bitwise reading from `BufRead`
18#[derive(Debug)]
19pub struct BitReader<R: BufRead> {
20    inner: R,
21    buf: Box<[u8]>,
22    pos: usize,
23}
24
25const DEFAULT_BUF_SIZE: usize = 1024;
26
27/// Writer to bitwise writing to `Write`
28#[derive(Debug)]
29pub struct BitWriter<W: Write> {
30    inner: W,
31    buf: VecDeque<Bit>,
32    pub pad_zero: bool,
33}
34
35/**************************************************************************************************
36                        BitReader - Implementations
37 *************************************************************************************************/
38impl<R: BufRead> BitReader<R> {
39    /// Creates a new BitReader from a BufRead
40    /// Buffer is not filled on create
41    pub fn new(mut inner: R) -> std::io::Result<BitReader<R>> {
42        let buf = inner.fill_buf()?.to_vec().into_boxed_slice();
43
44        Ok(BitReader { inner, buf, pos: 0})
45    }
46
47    /// Read a single Bit from BufRead
48    pub fn read(&mut self) -> std::io::Result<Bit> {
49        if self.is_empty() {
50            return Err(std::io::Error::new(ErrorKind::Other, "End of File"))
51        }
52
53        let mut byte_offset = self.pos / 8;
54        let mut bit_offset = self.pos % 8;
55
56        let byte = self.buf[byte_offset];
57
58        let mask = 1 << (7 - bit_offset);
59
60        let bit = Bit::from(byte & mask);
61
62        bit_offset += 1;
63        if bit_offset > 7 {
64            let byte_o = reader_update(self, byte_offset + 1)?;
65
66            byte_offset = byte_o;
67            bit_offset = 0;
68        }
69
70        self.pos = byte_offset * 8 + bit_offset;
71
72        Ok(bit)
73    }
74
75    /// Try Reading n Bits from BufRead
76    pub fn read_multi(&mut self, n: usize) -> std::io::Result<Vec<Bit>> {
77        let mut output = Vec::with_capacity(n);
78
79        for _ in 0..n {
80            output.push(self.read()?);
81        }
82
83        Ok(output)
84    }
85
86    /// Returns true if the Buffer is empty
87    pub fn is_empty(&self) -> bool {
88        self.buf_len() - self.pos == 0
89    }
90
91    /// Returns the length of the internal buffer
92    pub fn buf_len(&self) -> usize {
93        self.buf.len() * 8
94    }
95}
96
97/// Consume the Buffer and read from file if byte_offset is buffer_length
98fn reader_update<R: BufRead>(reader: &mut BitReader<R>, byte_offset: usize) -> std::io::Result<usize> {
99    let buf_len = reader.buf.len();
100
101    if byte_offset >= buf_len {
102        reader_fill_buf(reader)?;
103
104        reader.pos = 0;
105
106        Ok(0)
107    } else {
108        Ok(byte_offset)
109    }
110}
111
112/// Consume buf.len() and fill buf
113fn reader_fill_buf<R: BufRead>(reader: &mut BitReader<R>) -> std::io::Result<()> {
114    reader.inner.consume(reader.buf.len());
115
116    let buf = reader.inner.fill_buf()?;
117
118    reader.buf = buf.to_vec().into_boxed_slice();
119
120    Ok(())
121}
122
123
124/**************************************************************************************************
125                        BitReader - Implementations
126 *************************************************************************************************/
127impl<W: Write> BitWriter<W> {
128    /// Create a new BitWriter from a Write Trait with default capacity of 1024 Bytes
129    pub fn new(inner: W, pad_zero: bool) -> Self {
130        BitWriter::with_capacity(DEFAULT_BUF_SIZE, inner, pad_zero)
131    }
132
133    /// Create a new BitWriter with a capacity (in Bytes)
134    pub fn with_capacity(capacity: usize, inner: W, pad_zero: bool) -> Self {
135        BitWriter {
136            inner,
137            buf: VecDeque::with_capacity(capacity * 8),
138            pad_zero,
139        }
140    }
141
142    /// Writes a single Bit into the internal Buffer
143    /// If internal buffer is full -> Call internal write
144    pub fn write(&mut self, bit: Bit) -> std::io::Result<()> {
145        if self.buf.len() == DEFAULT_BUF_SIZE {
146            match self.write_buf() {
147                Ok(_) => {
148                    self.buf.push_back(bit);
149                    Ok(())
150                }
151                Err(err) => Err(err)
152            }
153        } else {
154            self.buf.push_back(bit);
155            Ok(())
156        }
157    }
158
159    /// Writes a vector of Bits into the internal Buffer
160    /// If internal buffer is full -> Call internal write
161    pub fn write_bits(&mut self, bits: &Vec<Bit>) -> std::io::Result<()> {
162        for bit in bits {
163            self.write(bit.clone())?
164        }
165        Ok(())
166    }
167
168    /// Write the internal Buffer and Pad with Zero? If needed
169    pub fn write_buf(&mut self) -> std::io::Result<()> {
170        writer_pad_buf(self);
171
172        let bytes = writer_buf_to_bytes(self);
173        match self.inner.write(&*bytes) {
174            Ok(_) => {
175                self.inner.flush()
176            }
177            Err(err) => Err(err)
178        }
179    }
180
181    /// Removes excess bits that do not form a byte
182    pub fn discard_non_byte(&mut self) {
183        while self.buf.len() % 8 != 0 {
184            let _ = self.buf.pop_back();
185        }
186    }
187
188    /// Returns true if the Buffer is empty
189    pub fn is_empty(&self) -> bool {
190        self.buf.is_empty()
191    }
192
193    /// Returns the length of the internal buffer
194    pub fn buf_len(&self) -> usize {
195        self.buf.len()
196    }
197}
198
199impl<W: Write> Drop for BitWriter<W> {
200    fn drop(&mut self) {
201        let _ = self.write_buf();
202    }
203}
204
205/// Removes all complete bytes from the Buffer and returns them in a Vector
206fn writer_buf_to_bytes<W: Write>(writer: &mut BitWriter<W>) -> Vec<u8> {
207    let mut bytes = Vec::new();
208
209    while writer.buf.len() >= 8 {
210        let mut byte = 0;
211        for i in 0..8 {
212            byte |= writer.buf.pop_front().unwrap() as u8;
213
214            if i < 7 {
215                byte = byte << 1;
216            }
217        }
218        bytes.push(byte);
219    }
220
221    bytes
222}
223
224/// Pad Byte
225fn writer_pad_buf<W: Write>(writer: &mut BitWriter<W>) {
226    let pad_bit = match writer.pad_zero {
227        true => Bit::Zero,
228        false => Bit::One,
229    };
230
231    for _ in 0..(writer.buf.len() % 8) {
232        writer.buf.push_back(pad_bit);
233    }
234}
235
236/**************************************************************************************************
237                        Bit - Implementations
238 *************************************************************************************************/
239impl Display for Bit {
240    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
241        match self {
242            Bit::Zero => write!(f, "0"),
243            Bit::One => write!(f, "1"),
244        }
245    }
246}
247
248impl From<u8> for Bit {
249    fn from(value: u8) -> Self {
250        if value > 0 {
251            return Bit::One;
252        } else {
253            return Bit::Zero;
254        }
255    }
256}
257
258impl From<u16> for Bit {
259    fn from(value: u16) -> Self {
260        if value > 0 {
261            return Bit::One;
262        } else {
263            return Bit::Zero;
264        }
265    }
266}
267
268impl From<u32> for Bit {
269    fn from(value: u32) -> Self {
270        if value > 0 {
271            return Bit::One;
272        } else {
273            return Bit::Zero;
274        }
275    }
276}
277
278impl From<u64> for Bit {
279    fn from(value: u64) -> Self {
280        if value > 0 {
281            return Bit::One;
282        } else {
283            return Bit::Zero;
284        }
285    }
286}
287
288impl From<i8> for Bit {
289    fn from(value: i8) -> Self {
290        if value > 0 {
291            return Bit::One;
292        } else {
293            return Bit::Zero;
294        }
295    }
296}
297
298impl From<i16> for Bit {
299    fn from(value: i16) -> Self {
300        if value > 0 {
301            return Bit::One;
302        } else {
303            return Bit::Zero;
304        }
305    }
306}
307
308impl From<i32> for Bit {
309    fn from(value: i32) -> Self {
310        if value > 0 {
311            return Bit::One;
312        } else {
313            return Bit::Zero;
314        }
315    }
316}
317
318impl From<i64> for Bit {
319    fn from(value: i64) -> Self {
320        if value > 0 {
321            return Bit::One;
322        } else {
323            return Bit::Zero;
324        }
325    }
326}
327
328impl From<usize> for Bit {
329    fn from(value: usize) -> Self {
330        if value > 0 {
331            return Bit::One;
332        } else {
333            return Bit::Zero;
334        }
335    }
336}
337
338impl From<bool> for Bit {
339    fn from(value: bool) -> Self {
340        match value {
341            false => Bit::Zero,
342            true => Bit::One,
343        }
344    }
345}