binary-codec 0.4.8

A binary codec for Rust that provides serialization and deserialization of data structures to and from binary formats.
Documentation
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use std::cmp::min;

use crate::{DeserializationError, bitstream::CryptoStream, encoding::fixed_int::FixedInt};

pub struct BitStreamReader<'a> {
    buffer: &'a [u8],
    bit_pos: usize,
    last_read_byte: Option<u8>,
    crypto: Option<Box<dyn CryptoStream>>,
}

impl<'a> BitStreamReader<'a> {
    /// Create a new LSB-first reader
    pub fn new(buffer: &'a [u8]) -> Self {
        Self {
            buffer,
            bit_pos: 0,
            crypto: None,
            last_read_byte: None,
        }
    }

    /// Set crypto stream
    pub fn set_crypto(&mut self, crypto: Option<Box<dyn CryptoStream>>) {
        self.crypto = crypto;
    }

    /// Get byte position of reader
    pub fn byte_pos(&self) -> usize {
        self.bit_pos / 8
    }

    /// Get current byte, from last_read_byte cache or from buffer
    fn current_byte(&mut self) -> u8 {
        if let Some(b) = self.last_read_byte {
            b
        } else {
            let mut b = self.buffer[self.byte_pos()];
            if let Some(crypto) = self.crypto.as_mut() {
                b = crypto.apply_keystream_byte(b);
            }

            self.last_read_byte = Some(b);
            b
        }
    }

    /// Read a single bit
    pub fn read_bit(&mut self) -> Result<bool, DeserializationError> {
        self.read_small(1).map(|v| v != 0)
    }

    /// Read 1-8 bits as u8 (LSB-first)
    pub fn read_small(&mut self, mut bits: u8) -> Result<u8, DeserializationError> {
        assert!(bits > 0 && bits < 8);

        let mut result: u8 = 0;
        let mut shift = 0;

        while bits > 0 {
            if self.byte_pos() >= self.buffer.len() {
                return Err(DeserializationError::NotEnoughBytes(1));
            }

            // Find the bit position inside the current byte (0..7)
            let bit_offset = self.bit_pos % 8;

            // Determine how many bytes left to read. Min(bits left in this byte, bits to read)
            let bits_in_current_byte = min(8 - bit_offset as u8, bits);

            // Create a mask to isolate the bits we want from this byte.
            // Example: if bit_offset = 2 and bits_in_current_byte = 3,
            // mask = 00011100 (only bits 2,3,4 are 1)
            let mask = ((1 << bits_in_current_byte) - 1) << bit_offset;
            let byte_val = self.current_byte();

            // Apply the mask to isolate the bits and shift them to LSB
            // Example: byte_val = 10101100, mask = 00011100
            // (10101100 & 00011100) >> 2 = 00000101
            let val = (byte_val & mask) >> bit_offset;

            // Merge the extracted bits into the final result.
            // Shift them to the correct position based on how many bits we already read.
            result |= val << shift;

            // Decrease the remaining bits we need to read
            bits -= bits_in_current_byte;

            // Update the shift for the next batch of bits (if crossing byte boundary)
            shift += bits_in_current_byte;

            self.bit_pos += bits_in_current_byte as usize;

            // If crossed byte boundary, reset last read byte
            if self.bit_pos % 8 == 0 {
                self.last_read_byte = None;
            }
        }

        Ok(result)
    }

    /// Read a full byte, aligning to the next byte boundary
    pub fn read_byte(&mut self) -> Result<u8, DeserializationError> {
        self.align_byte();

        if self.byte_pos() >= self.buffer.len() {
            return Err(DeserializationError::NotEnoughBytes(1));
        }

        let byte = self.current_byte();
        self.bit_pos += 8;
        self.last_read_byte = None;
        
        Ok(byte)
    }

    /// Read a slice of bytes, aligning first
    pub fn read_bytes(&mut self, count: usize) -> Result<&[u8], DeserializationError> {
        self.align_byte();

        let start = self.byte_pos();
        if start + count > self.buffer.len() {
            return Err(DeserializationError::NotEnoughBytes(
                start + count - self.buffer.len(),
            ));
        }

        self.bit_pos += 8 * count;
        self.last_read_byte = None;

        let slice = &self.buffer[start..start + count];
        if let Some(crypto) = self.crypto.as_mut() {
            Ok(crypto.apply_keystream(slice))
        } else {
            Ok(slice)
        }
    }

    /// Read a dynamic int, starting at the next byte bounary
    /// The last bit is used as a continuation flag for the next byte
    pub fn read_dyn_int(&mut self) -> Result<u128, DeserializationError> {
        self.align_byte();
        let mut num: u128 = 0;
        let mut multiplier: u128 = 1;

        loop {
            let byte = self.read_byte()?; // None if EOF
            num += ((byte & 127) as u128) * multiplier;

            // If no continuation bit, stop
            if (byte & 1 << 7) == 0 {
                break;
            }

            multiplier *= 128;
        }

        Ok(num)
    }

    /// Read a integer of fixed size from the buffer
    pub fn read_fixed_int<const S: usize, T: FixedInt<S>>(
        &mut self,
    ) -> Result<T, DeserializationError> {
        let data = self.read_bytes(S)?;
        Ok(FixedInt::deserialize(data))
    }

    /// Align the reader to the next byte boundary
    pub fn align_byte(&mut self) {
        let rem = self.bit_pos % 8;
        if rem != 0 {
            self.bit_pos += 8 - rem;
            self.last_read_byte = None;
        }
    }

    /// Get bytes left
    pub fn bytes_left(&self) -> usize {
        let left = self.buffer.len() - self.byte_pos();
        if self.bit_pos % 8 != 0 {
            left - 1 // If not aligned, we can't read the last byte fully
        } else {
            left
        }
    }

    /// Reset reading position
    pub fn reset(&mut self) {
        self.bit_pos = 0;
    }
}

#[cfg(test)]
mod tests {
    use crate::{DeserializationError, bitstream::CryptoStream};

    use super::BitStreamReader;

    struct PlusOneDecrypter {
        plain: Vec<u8>
    }

    impl CryptoStream for PlusOneDecrypter {
        fn apply_keystream_byte(&mut self, b: u8) -> u8 {
            self.plain.push(b + 1);
            *self.plain.last().unwrap()
        }
    
        fn apply_keystream(&mut self, slice: &[u8]) -> &[u8] {
            let d = slice.iter().map(|s|s + 1);
            self.plain.extend(d);
            &self.plain[self.plain.len() - slice.len()..]
        }
    }

    #[test]
    fn test_decrypt_bytes() {
        let buf = vec![1,2,3,4,5,6,7,8,9,10];
        let mut reader = BitStreamReader::new(&buf);
        reader.crypto = Some(Box::new(PlusOneDecrypter { plain: Vec::new() }));
        
        assert_eq!(reader.read_byte(), Ok(2));
        assert_eq!(reader.read_byte(), Ok(3));
        assert_eq!(reader.read_byte(), Ok(4));
        // 4 = 00000100, +1 = 00000101
        assert_eq!(reader.read_bit(), Ok(true));
        assert_eq!(reader.read_bit(), Ok(false));
        assert_eq!(reader.read_bit(), Ok(true));
        assert_eq!(reader.read_bytes(5), Ok(&[6,7,8,9,10][..]));
        assert_eq!(reader.read_byte(), Ok(11));
    }

    /// Helper to build buffers
    fn make_buffer() -> Vec<u8> {
        vec![0b10101100, 0b11010010, 0xFF, 0x00]
    }

    #[test]
    fn test_read_single_bits() {
        let buf = make_buffer();
        let mut reader = BitStreamReader::new(&buf);

        // LSB-first: read bits starting from least significant
        assert_eq!(reader.read_bit(), Ok(false));
        assert_eq!(reader.read_bit(), Ok(false));
        assert_eq!(reader.read_bit(), Ok(true));
        assert_eq!(reader.read_bit(), Ok(true));
        assert_eq!(reader.read_bit(), Ok(false));
        assert_eq!(reader.read_bit(), Ok(true));
        assert_eq!(reader.read_bit(), Ok(false));
        assert_eq!(reader.read_bit(), Ok(true));
    }

    #[test]
    fn test_read_small() {
        let buf = [0b10101100, 0b11010010];
        let mut reader = BitStreamReader::new(&buf);

        assert_eq!(reader.read_small(3), Ok(0b100));
        assert_eq!(reader.read_small(4), Ok(0b0101));
        assert_eq!(reader.read_small(1), Ok(0b1));
        assert_eq!(reader.read_small(4), Ok(0b0010));
    }

    #[test]
    fn test_read_cross_byte() {
        let buf = [0b10101100, 0b11010001];
        let mut reader = BitStreamReader::new(&buf);

        // Read first 10 bits (crosses into second byte)
        assert_eq!(reader.read_small(7), Ok(0b00101100));
        assert_eq!(reader.read_small(3), Ok(0b011));
    }

    #[test]
    fn test_read_byte() {
        let buf = [0b10101100, 0b11010010];
        let mut reader = BitStreamReader::new(&buf);

        reader.read_small(3).unwrap(); // advance 3 bits
        assert_eq!(reader.read_byte(), Ok(0b11010010)); // full second byte
    }

    #[test]
    fn test_read_bytes() {
        let buf = [0x01, 0xAA, 0xBB, 0xCC];
        let mut reader = BitStreamReader::new(&buf);

        reader.read_bit().unwrap(); // first bit
        let slice = reader.read_bytes(3).unwrap();
        assert_eq!(slice, &[0xAA, 0xBB, 0xCC]);
    }

    #[test]
    fn test_align_byte() {
        let buf = [0b10101100, 0b11010010];
        let mut reader = BitStreamReader::new(&buf);

        reader.read_small(3).unwrap(); // 3 bits
        reader.align_byte(); // move to next byte
        assert_eq!(reader.read_byte(), Ok(0b11010010));
    }

    #[test]
    fn test_eof_behavior() {
        let buf = [0xFF];
        let mut reader = BitStreamReader::new(&buf);

        assert_eq!(reader.read_byte(), Ok(0xFF));
        assert_eq!(
            reader.read_bit(),
            Err(DeserializationError::NotEnoughBytes(1))
        );
        assert_eq!(
            reader.read_byte(),
            Err(DeserializationError::NotEnoughBytes(1))
        );
        assert_eq!(
            reader.read_bytes(2),
            Err(DeserializationError::NotEnoughBytes(2))
        );
    }

    #[test]
    fn test_multiple_operations() {
        let buf = [0b10101010, 0b11001100, 0xFF, 0x00];
        let mut reader = BitStreamReader::new(&buf);

        assert_eq!(reader.read_bit(), Ok(false)); // bit 0
        assert_eq!(reader.read_small(3), Ok(0b101)); // bits 1-3
        assert_eq!(reader.read_byte(), Ok(0b11001100)); // aligned full byte
        assert_eq!(reader.read_bytes(2), Ok(&[0xFF, 0x00][..]));
        assert_eq!(
            reader.read_bit(),
            Err(DeserializationError::NotEnoughBytes(1))
        );
    }

    #[test]
    fn test_read_dyn_int() {
        let buf = vec![0, 127, 128, 1, 255, 255, 255, 127];
        let mut stream = BitStreamReader::new(&buf);

        assert_eq!(Ok(0), stream.read_byte());
        assert_eq!(Ok(127), stream.read_dyn_int());
        assert_eq!(Ok(128), stream.read_dyn_int());
        assert_eq!(Ok(268435455), stream.read_dyn_int());
        assert_eq!(
            Err(DeserializationError::NotEnoughBytes(1)),
            stream.read_dyn_int()
        );
    }

    #[test]
    fn test_read_fixed_int() {
        let buf = vec![
            1, 2, 0, 2, 0, 4, 0, 0, 0, 3, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0,
            8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 10,
        ];

        let mut stream = BitStreamReader::new(&buf);
        let v1: u8 = stream.read_fixed_int().unwrap();
        let v2: i8 = stream.read_fixed_int().unwrap();
        let v3: u16 = stream.read_fixed_int().unwrap();
        let v4: i16 = stream.read_fixed_int().unwrap();
        let v5: u32 = stream.read_fixed_int().unwrap();
        let v6: i32 = stream.read_fixed_int().unwrap();
        let v7: u64 = stream.read_fixed_int().unwrap();
        let v8: i64 = stream.read_fixed_int().unwrap();
        let v9: u128 = stream.read_fixed_int().unwrap();
        let v10: i128 = stream.read_fixed_int().unwrap();

        assert_eq!(v1, 1);
        assert_eq!(v2, 1);
        assert_eq!(v3, 2);
        assert_eq!(v4, 2);
        assert_eq!(v5, 3);
        assert_eq!(v6, 3);
        assert_eq!(v7, 4);
        assert_eq!(v8, 4);
        assert_eq!(v9, 5);
        assert_eq!(v10, 5);
    }

    #[test]
    fn test_bytes_left() {
        let buf = [0b10101100, 0b11010010, 0xFF, 0x00];
        let mut reader = BitStreamReader::new(&buf);

        assert_eq!(reader.bytes_left(), 4);
        reader.read_small(3).unwrap(); // read 3 bits
        assert_eq!(reader.bytes_left(), 3); // 3 full bytes left
        reader.read_byte().unwrap(); // read one byte
        assert_eq!(reader.bytes_left(), 2); // now 2 bytes left
        reader.read_byte().unwrap(); // read another byte
        assert_eq!(reader.bytes_left(), 1); // now 1 bytes left
        reader.read_bit().unwrap(); // read one bit
        assert_eq!(reader.bytes_left(), 0); // no full bytes left
    }
}