scuffle_bytes_util/
bit_write.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
use std::io;

/// A writer that allows you to write bits to a stream
#[derive(Debug)]
#[must_use]
pub struct BitWriter<W> {
    bit_pos: u8,
    current_byte: u8,
    writer: W,
}

impl<W: Default> Default for BitWriter<W> {
    fn default() -> Self {
        Self::new(W::default())
    }
}

impl<W: io::Write> BitWriter<W> {
    /// Writes a single bit to the stream
    pub fn write_bit(&mut self, bit: bool) -> io::Result<()> {
        if bit {
            self.current_byte |= 1 << (7 - self.bit_pos);
        } else {
            self.current_byte &= !(1 << (7 - self.bit_pos));
        }

        self.bit_pos += 1;

        if self.bit_pos == 8 {
            self.writer.write_all(&[self.current_byte])?;
            self.current_byte = 0;
            self.bit_pos = 0;
        }

        Ok(())
    }

    /// Writes a number of bits to the stream (the most significant bit is
    /// written first)
    pub fn write_bits(&mut self, bits: u64, count: u8) -> io::Result<()> {
        let count = count.min(64);

        if count != 64 && bits > (1 << count as u64) - 1 {
            return Err(io::Error::new(io::ErrorKind::InvalidData, "bits too large to write"));
        }

        for i in 0..count {
            let bit = (bits >> (count - i - 1)) & 1 == 1;
            self.write_bit(bit)?;
        }

        Ok(())
    }

    /// Flushes the buffer and returns the underlying writer
    /// This will also align the writer to the byte boundary
    pub fn finish(mut self) -> io::Result<W> {
        self.align()?;
        Ok(self.writer)
    }

    /// Aligns the writer to the byte boundary
    pub fn align(&mut self) -> io::Result<()> {
        if !self.is_aligned() {
            self.write_bits(0, 8 - self.bit_pos())?;
        }

        Ok(())
    }
}

impl<W> BitWriter<W> {
    /// Creates a new BitWriter from a writer
    pub const fn new(writer: W) -> Self {
        Self {
            bit_pos: 0,
            current_byte: 0,
            writer,
        }
    }

    /// Returns the current bit position (0-7)
    #[inline(always)]
    #[must_use]
    pub const fn bit_pos(&self) -> u8 {
        self.bit_pos % 8
    }

    /// Checks if the writer is aligned to the byte boundary
    #[inline(always)]
    #[must_use]
    pub const fn is_aligned(&self) -> bool {
        self.bit_pos % 8 == 0
    }

    /// Returns a reference to the underlying writer
    #[inline(always)]
    #[must_use]
    pub const fn get_ref(&self) -> &W {
        &self.writer
    }
}

impl<W: io::Write> io::Write for BitWriter<W> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        if self.is_aligned() {
            return self.writer.write(buf);
        }

        for byte in buf {
            self.write_bits(*byte as u64, 8)?;
        }

        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        self.writer.flush()
    }
}

#[cfg(test)]
#[cfg_attr(all(test, coverage_nightly), coverage(off))]
mod tests {
    use io::Write;

    use super::*;

    #[test]
    fn test_bit_writer() {
        let mut bit_writer = BitWriter::<Vec<u8>>::default();

        bit_writer.write_bits(0b11111111, 8).unwrap();
        assert_eq!(bit_writer.bit_pos(), 0);
        assert!(bit_writer.is_aligned());

        bit_writer.write_bits(0b0000, 4).unwrap();
        assert_eq!(bit_writer.bit_pos(), 4);
        assert!(!bit_writer.is_aligned());
        bit_writer.align().unwrap();
        assert_eq!(bit_writer.bit_pos(), 0);
        assert!(bit_writer.is_aligned());

        bit_writer.write_bits(0b1010, 4).unwrap();
        assert_eq!(bit_writer.bit_pos(), 4);
        assert!(!bit_writer.is_aligned());

        bit_writer.write_bits(0b101010101010, 12).unwrap();
        assert_eq!(bit_writer.bit_pos(), 0);
        assert!(bit_writer.is_aligned());

        bit_writer.write_bit(true).unwrap();
        assert_eq!(bit_writer.bit_pos(), 1);
        assert!(!bit_writer.is_aligned());

        let err = bit_writer.write_bits(0b10000, 4).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
        assert_eq!(err.to_string(), "bits too large to write");

        assert_eq!(
            bit_writer.finish().unwrap(),
            vec![0b11111111, 0b00000000, 0b10101010, 0b10101010, 0b10000000]
        );
    }

    #[test]
    fn test_flush_buffer() {
        let mut bit_writer = BitWriter::<Vec<u8>>::default();

        bit_writer.write_bits(0b11111111, 8).unwrap();
        assert_eq!(bit_writer.bit_pos(), 0);
        assert!(bit_writer.is_aligned());
        assert_eq!(bit_writer.get_ref(), &[0b11111111], "underlying writer should have one byte");

        bit_writer.write_bits(0b0000, 4).unwrap();
        assert_eq!(bit_writer.bit_pos(), 4);
        assert!(!bit_writer.is_aligned());
        assert_eq!(bit_writer.get_ref(), &[0b11111111], "underlying writer should have one bytes");

        bit_writer.write_bits(0b1010, 4).unwrap();
        assert_eq!(bit_writer.bit_pos(), 0);
        assert!(bit_writer.is_aligned());
        assert_eq!(
            bit_writer.get_ref(),
            &[0b11111111, 0b00001010],
            "underlying writer should have two bytes"
        );
    }

    #[test]
    fn test_io_write() {
        let mut inner = Vec::new();
        let mut bit_writer = BitWriter::new(&mut inner);

        bit_writer.write_bits(0b11111111, 8).unwrap();
        assert_eq!(bit_writer.bit_pos(), 0);
        assert!(bit_writer.is_aligned());
        // We should have buffered the write
        assert_eq!(bit_writer.get_ref().as_slice(), &[255]);

        bit_writer.write_all(&[1, 2, 3]).unwrap();
        assert_eq!(bit_writer.bit_pos(), 0);
        assert!(bit_writer.is_aligned());
        // since we did an io::Write on an aligned bit_writer
        // we should have written directly to the underlying
        // writer
        assert_eq!(bit_writer.get_ref().as_slice(), &[255, 1, 2, 3]);

        bit_writer.write_bit(true).unwrap();

        bit_writer.write_bits(0b1010, 4).unwrap();

        bit_writer
            .write_all(&[0b11111111, 0b00000000, 0b11111111, 0b00000000])
            .unwrap();

        // Since the writer was not aligned we should have buffered the writes
        assert_eq!(
            bit_writer.get_ref().as_slice(),
            &[255, 1, 2, 3, 0b11010111, 0b11111000, 0b00000111, 0b11111000]
        );

        bit_writer.finish().unwrap();

        assert_eq!(
            inner,
            vec![255, 1, 2, 3, 0b11010111, 0b11111000, 0b00000111, 0b11111000, 0b00000000]
        );
    }

    #[test]
    fn test_flush() {
        let mut inner = Vec::new();
        let mut bit_writer = BitWriter::new(&mut inner);

        bit_writer.write_bits(0b10100000, 8).unwrap();

        bit_writer.flush().unwrap();

        assert_eq!(bit_writer.get_ref().as_slice(), &[0b10100000]);
        assert_eq!(bit_writer.bit_pos(), 0);
        assert!(bit_writer.is_aligned());
    }
}