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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
use std::cmp::min;
use std::fmt;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::mem::size_of;
use std::ops::{BitOrAssign, BitXor};
use std::rc::Rc;

use num_traits::{Float, PrimInt};

use crate::endianness::Endianness;
use crate::is_signed::IsSigned;
use crate::unchecked_primitive::{UncheckedPrimitiveFloat, UncheckedPrimitiveInt};
use crate::{ReadError, Result};
use std::convert::TryInto;

const USIZE_SIZE: usize = size_of::<usize>();

/// Buffer that allows reading integers of arbitrary bit length and non byte-aligned integers
///
/// # Examples
///
/// ```
/// use bitbuffer::{BitReadBuffer, LittleEndian, Result};
///
/// # fn main() -> Result<()> {
/// let bytes = vec![
///     0b1011_0101, 0b0110_1010, 0b1010_1100, 0b1001_1001,
///     0b1001_1001, 0b1001_1001, 0b1001_1001, 0b1110_0111
/// ];
/// let buffer = BitReadBuffer::new(bytes, LittleEndian);
/// // read 7 bits as u8, starting from bit 3
/// let result: u8 = buffer.read_int(3, 7)?;
/// #
/// #     Ok(())
/// # }
/// ```
pub struct BitReadBuffer<E>
where
    E: Endianness,
{
    bytes: Rc<Vec<u8>>,
    bit_len: usize,
    endianness: PhantomData<E>,
}

impl<E> BitReadBuffer<E>
where
    E: Endianness,
{
    /// Create a new BitBuffer from a byte vector
    ///
    /// # Examples
    ///
    /// ```
    /// use bitbuffer::{BitReadBuffer, LittleEndian};
    ///
    /// let bytes = vec![
    ///     0b1011_0101, 0b0110_1010, 0b1010_1100, 0b1001_1001,
    ///     0b1001_1001, 0b1001_1001, 0b1001_1001, 0b1110_0111
    /// ];
    /// let buffer = BitReadBuffer::new(bytes, LittleEndian);
    /// ```
    pub fn new(mut bytes: Vec<u8>, _endianness: E) -> Self {
        let byte_len = bytes.len();

        // pad with usize worth of bytes to ensure we can always read a full usize
        bytes.extend_from_slice(&0usize.to_le_bytes());
        BitReadBuffer {
            bytes: Rc::new(bytes),
            bit_len: byte_len * 8,
            endianness: PhantomData,
        }
    }
}

impl<E> BitReadBuffer<E>
where
    E: Endianness,
{
    /// The available number of bits in the buffer
    pub fn bit_len(&self) -> usize {
        self.bit_len
    }

    /// The available number of bytes in the buffer
    pub fn byte_len(&self) -> usize {
        self.bytes.len()
    }

    unsafe fn read_usize_bytes(&self, byte_index: usize) -> [u8; USIZE_SIZE] {
        debug_assert!(byte_index + USIZE_SIZE <= self.bytes.len());
        // this is safe because all calling paths check that byte_index is less than the unpadded
        // length (because they check based on bit_len), so with padding byte_index + USIZE_SIZE is
        // always within bounds
        self.bytes
            .get_unchecked(byte_index..byte_index + USIZE_SIZE)
            .try_into()
            .unwrap()
    }

    /// note that only the bottom USIZE - 1 bytes are usable
    unsafe fn read_shifted_usize(&self, byte_index: usize, shift: usize) -> usize {
        let raw_bytes: [u8; USIZE_SIZE] = self.read_usize_bytes(byte_index);
        let raw_usize: usize = usize::from_le_bytes(raw_bytes);
        raw_usize >> shift
    }

    unsafe fn read_usize(&self, position: usize, count: usize) -> usize {
        let byte_index = position / 8;
        let bit_offset = position & 7;
        let usize_bit_size = size_of::<usize>() * 8;

        let bytes: [u8; USIZE_SIZE] = self.read_usize_bytes(byte_index);

        let container = if E::is_le() {
            usize::from_le_bytes(bytes)
        } else {
            usize::from_be_bytes(bytes)
        };

        let shifted = if E::is_le() {
            container >> bit_offset
        } else {
            container >> (usize_bit_size - bit_offset - count)
        };
        let mask = !(std::usize::MAX << count);
        shifted & mask
    }

    /// Read a single bit from the buffer as boolean
    ///
    /// # Errors
    ///
    /// - [`ReadError::NotEnoughData`]: not enough bits available in the buffer
    ///
    /// # Examples
    ///
    /// ```
    /// # use bitbuffer::{BitReadBuffer, LittleEndian, Result};
    /// #
    /// # fn main() -> Result<()> {
    /// # let bytes = vec![
    /// #     0b1011_0101, 0b0110_1010, 0b1010_1100, 0b1001_1001,
    /// #     0b1001_1001, 0b1001_1001, 0b1001_1001, 0b1110_0111
    /// # ];
    /// # let buffer = BitReadBuffer::new(bytes, LittleEndian);
    /// let result = buffer.read_bool(5)?;
    /// assert_eq!(result, true);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// [`ReadError::NotEnoughData`]: enum.ReadError.html#variant.NotEnoughData
    #[inline]
    pub fn read_bool(&self, position: usize) -> Result<bool> {
        let byte_index = position / 8;
        let bit_offset = position & 7;

        if position < self.bit_len() {
            let byte = self.bytes[byte_index];
            let shifted = byte >> bit_offset;
            Ok(shifted & 1u8 == 1)
        } else {
            Err(ReadError::NotEnoughData {
                requested: 1,
                bits_left: self.bit_len().saturating_sub(position),
            })
        }
    }

    #[doc(hidden)]
    #[inline]
    pub unsafe fn read_bool_unchecked(&self, position: usize) -> bool {
        let byte_index = position / 8;
        let bit_offset = position & 7;

        let byte = self.bytes.get_unchecked(byte_index);
        let shifted = byte >> bit_offset;
        shifted & 1u8 == 1
    }

    /// Read a sequence of bits from the buffer as integer
    ///
    /// # Errors
    ///
    /// - [`ReadError::NotEnoughData`]: not enough bits available in the buffer
    /// - [`ReadError::TooManyBits`]: to many bits requested for the chosen integer type
    ///
    /// # Examples
    ///
    /// ```
    /// # use bitbuffer::{BitReadBuffer, LittleEndian, Result};
    /// #
    /// # fn main() -> Result<()> {
    /// # let bytes = vec![
    /// #     0b1011_0101, 0b0110_1010, 0b1010_1100, 0b1001_1001,
    /// #     0b1001_1001, 0b1001_1001, 0b1001_1001, 0b1110_0111
    /// # ];
    /// # let buffer = BitReadBuffer::new(bytes, LittleEndian);
    /// let result = buffer.read_int::<u16>(10, 9)?;
    /// assert_eq!(result, 0b100_0110_10);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// [`ReadError::NotEnoughData`]: enum.ReadError.html#variant.NotEnoughData
    /// [`ReadError::TooManyBits`]: enum.ReadError.html#variant.TooManyBits
    #[inline]
    pub fn read_int<T>(&self, position: usize, count: usize) -> Result<T>
    where
        T: PrimInt + BitOrAssign + IsSigned + UncheckedPrimitiveInt + BitXor,
    {
        let type_bit_size = size_of::<T>() * 8;

        if type_bit_size < count {
            return Err(ReadError::TooManyBits {
                requested: count,
                max: type_bit_size,
            });
        }

        if position + count > self.bit_len() {
            return if position > self.bit_len() {
                Err(ReadError::IndexOutOfBounds {
                    pos: position,
                    size: self.bit_len(),
                })
            } else {
                Err(ReadError::NotEnoughData {
                    requested: count,
                    bits_left: self.bit_len() - position,
                })
            };
        }

        Ok(unsafe { self.read_int_unchecked(position, count) })
    }

    #[doc(hidden)]
    #[inline]
    pub unsafe fn read_int_unchecked<T>(&self, position: usize, count: usize) -> T
    where
        T: PrimInt + BitOrAssign + IsSigned + UncheckedPrimitiveInt + BitXor,
    {
        let type_bit_size = size_of::<T>() * 8;
        let usize_bit_size = size_of::<usize>() * 8;

        let bit_offset = position & 7;

        let fit_usize = count + bit_offset < usize_bit_size;
        let value = if fit_usize {
            self.read_fit_usize(position, count)
        } else {
            self.read_no_fit_usize(position, count)
        };

        if count == type_bit_size {
            value
        } else {
            self.make_signed(value, count)
        }
    }

    #[inline]
    unsafe fn read_fit_usize<T>(&self, position: usize, count: usize) -> T
    where
        T: PrimInt + BitOrAssign + IsSigned + UncheckedPrimitiveInt,
    {
        let raw = self.read_usize(position, count);
        T::from_unchecked(raw)
    }

    unsafe fn read_no_fit_usize<T>(&self, position: usize, count: usize) -> T
    where
        T: PrimInt + BitOrAssign + IsSigned + UncheckedPrimitiveInt,
    {
        let mut left_to_read = count;
        let mut acc = T::zero();
        let max_read = (size_of::<usize>() - 1) * 8;
        let mut read_pos = position;
        let mut bit_offset = 0;
        while left_to_read > 0 {
            let bits_left = self.bit_len() - read_pos;
            let read = min(min(left_to_read, max_read), bits_left);
            let data = T::from_unchecked(self.read_usize(read_pos, read));
            if E::is_le() {
                acc |= data << bit_offset;
            } else {
                acc = acc << read;
                acc |= data;
            }
            bit_offset += read;
            read_pos += read;
            left_to_read -= read;
        }

        acc
    }

    fn make_signed<T>(&self, value: T, count: usize) -> T
    where
        T: PrimInt + BitOrAssign + IsSigned + UncheckedPrimitiveInt + BitXor,
    {
        if count == 0 {
            T::zero()
        } else if T::is_signed() {
            let sign_bit = value >> (count - 1) & T::one();
            if sign_bit == T::one() {
                value | (T::zero() - T::one()) ^ ((T::one() << count) - T::one())
            } else {
                value
            }
        } else {
            value
        }
    }

    /// Read a series of bytes from the buffer
    ///
    /// # Errors
    ///
    /// - [`ReadError::NotEnoughData`]: not enough bits available in the buffer
    ///
    /// # Examples
    ///
    /// ```
    /// # use bitbuffer::{BitReadBuffer, LittleEndian, Result};
    /// #
    /// # fn main() -> Result<()> {
    /// # let bytes = vec![
    /// #     0b1011_0101, 0b0110_1010, 0b1010_1100, 0b1001_1001,
    /// #     0b1001_1001, 0b1001_1001, 0b1001_1001, 0b1110_0111
    /// # ];
    /// # let buffer = BitReadBuffer::new(bytes, LittleEndian);
    /// assert_eq!(buffer.read_bytes(5, 3)?, &[0b0_1010_101, 0b0_1100_011, 0b1_1001_101]);
    /// assert_eq!(buffer.read_bytes(0, 8)?, &[
    ///     0b1011_0101, 0b0110_1010, 0b1010_1100, 0b1001_1001,
    ///     0b1001_1001, 0b1001_1001, 0b1001_1001, 0b1110_0111
    /// ]);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// [`ReadError::NotEnoughData`]: enum.ReadError.html#variant.NotEnoughData
    #[inline]
    pub fn read_bytes(&self, position: usize, byte_count: usize) -> Result<Vec<u8>> {
        if position + byte_count * 8 > self.bit_len() {
            if position > self.bit_len() {
                return Err(ReadError::IndexOutOfBounds {
                    pos: position,
                    size: self.bit_len(),
                });
            } else {
                return Err(ReadError::NotEnoughData {
                    requested: byte_count * 8,
                    bits_left: self.bit_len() - position,
                });
            }
        }

        Ok(unsafe { self.read_bytes_unchecked(position, byte_count) })
    }

    #[doc(hidden)]
    #[inline]
    pub unsafe fn read_bytes_unchecked(&self, position: usize, byte_count: usize) -> Vec<u8> {
        let shift = position & 7;

        if shift == 0 {
            let byte_pos = position / 8;
            return self.bytes[byte_pos..byte_pos + byte_count].to_vec();
        }

        let mut data = Vec::with_capacity(byte_count);
        let mut byte_left = byte_count;
        let mut read_pos = position / 8;
        while byte_left > USIZE_SIZE - 1 {
            let bytes = self.read_shifted_usize(read_pos, shift).to_le_bytes();
            let read_bytes = USIZE_SIZE - 1;
            let usable_bytes = &bytes[0..read_bytes];
            data.extend_from_slice(usable_bytes);

            read_pos += read_bytes;
            byte_left -= read_bytes;
        }

        let bytes = self.read_shifted_usize(read_pos, shift).to_le_bytes();
        let usable_bytes = &bytes[0..byte_left];
        data.extend_from_slice(usable_bytes);

        data
    }

    /// Read a series of bytes from the buffer as string
    ///
    /// You can either read a fixed number of bytes, or a dynamic length null-terminated string
    ///
    /// # Errors
    ///
    /// - [`ReadError::NotEnoughData`]: not enough bits available in the buffer
    /// - [`ReadError::Utf8Error`]: the read bytes are not valid utf8
    ///
    /// # Examples
    ///
    /// ```
    /// # use bitbuffer::{BitReadBuffer, BitReadStream, LittleEndian, Result};
    /// #
    /// # fn main() -> Result<()> {
    /// # let bytes = vec![
    /// #     0x48, 0x65, 0x6c, 0x6c,
    /// #     0x6f, 0x20, 0x77, 0x6f,
    /// #     0x72, 0x6c, 0x64, 0,
    /// #     0,    0,    0,    0
    /// # ];
    /// # let buffer = BitReadBuffer::new(bytes, LittleEndian);
    /// // Fixed length string
    /// assert_eq!(buffer.read_string(0, Some(13))?, "Hello world".to_owned());
    /// // fixed length with null padding
    /// assert_eq!(buffer.read_string(0, Some(16))?, "Hello world".to_owned());
    /// // null terminated
    /// assert_eq!(buffer.read_string(0, None)?, "Hello world".to_owned());
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// [`ReadError::NotEnoughData`]: enum.ReadError.html#variant.NotEnoughData
    /// [`ReadError::Utf8Error`]: enum.ReadError.html#variant.Utf8Error
    #[inline]
    pub fn read_string(&self, position: usize, byte_len: Option<usize>) -> Result<String> {
        match byte_len {
            Some(byte_len) => {
                let bytes = self.read_bytes(position, byte_len)?;
                let raw_string = String::from_utf8(bytes)?;
                Ok(raw_string.trim_end_matches(char::from(0)).to_owned())
            }
            None => {
                let bytes = self.read_string_bytes(position)?;
                String::from_utf8(bytes).map_err(ReadError::from)
            }
        }
    }

    #[inline]
    fn find_null_byte(&self, byte_index: usize) -> usize {
        memchr::memchr(0, &self.bytes[byte_index..])
            .map(|index| index + byte_index)
            .unwrap() // due to padding we always have 0 bytes at the end
    }

    #[inline]
    fn read_string_bytes(&self, position: usize) -> Result<Vec<u8>> {
        let shift = position & 7;
        if shift == 0 {
            let byte_index = position / 8;
            Ok(self.bytes[byte_index..self.find_null_byte(byte_index)].to_vec())
        } else {
            let mut acc = Vec::with_capacity(32);
            let mut byte_index = position / 8;
            loop {
                // note: if less then a usize worth of data is left in the buffer, read_usize_bytes
                // will automatically pad with null bytes, triggering the loop termination
                // thus no separate logic for dealing with the end of the bytes is required
                //
                // This is safe because the final usize is filled with 0's, thus triggering the exit clause
                // before reading any out of bounds
                let shifted = unsafe { self.read_shifted_usize(byte_index, shift) };

                let has_null = contains_zero_byte_non_top(shifted);
                let bytes: [u8; USIZE_SIZE] = shifted.to_le_bytes();
                let usable_bytes = &bytes[0..USIZE_SIZE - 1];

                if has_null {
                    for i in 0..USIZE_SIZE - 1 {
                        if usable_bytes[i] == 0 {
                            acc.extend_from_slice(&usable_bytes[0..i]);
                            return Ok(acc);
                        }
                    }
                }

                acc.extend_from_slice(&usable_bytes[0..USIZE_SIZE - 1]);

                byte_index += USIZE_SIZE - 1;
            }
        }
    }

    /// Read a sequence of bits from the buffer as float
    ///
    /// # Errors
    ///
    /// - [`ReadError::NotEnoughData`]: not enough bits available in the buffer
    ///
    /// # Examples
    ///
    /// ```
    /// # use bitbuffer::{BitReadBuffer, LittleEndian, Result};
    /// #
    /// # fn main() -> Result<()> {
    /// # let bytes = vec![
    /// #     0b1011_0101, 0b0110_1010, 0b1010_1100, 0b1001_1001,
    /// #     0b1001_1001, 0b1001_1001, 0b1001_1001, 0b1110_0111
    /// # ];
    /// # let buffer = BitReadBuffer::new(bytes, LittleEndian);
    /// let result = buffer.read_float::<f32>(10)?;
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// [`ReadError::NotEnoughData`]: enum.ReadError.html#variant.NotEnoughData
    #[inline]
    pub fn read_float<T>(&self, position: usize) -> Result<T>
    where
        T: Float + UncheckedPrimitiveFloat,
    {
        let type_bit_size = size_of::<T>() * 8;
        if position + type_bit_size > self.bit_len() {
            if position > self.bit_len() {
                return Err(ReadError::IndexOutOfBounds {
                    pos: position,
                    size: self.bit_len(),
                });
            } else {
                return Err(ReadError::NotEnoughData {
                    requested: size_of::<T>() * 8,
                    bits_left: self.bit_len() - position,
                });
            }
        }

        Ok(unsafe { self.read_float_unchecked(position) })
    }

    #[doc(hidden)]
    #[inline]
    pub unsafe fn read_float_unchecked<T>(&self, position: usize) -> T
    where
        T: Float + UncheckedPrimitiveFloat,
    {
        if size_of::<T>() == 4 {
            let int = if size_of::<T>() < USIZE_SIZE {
                self.read_fit_usize::<u32>(position, 32)
            } else {
                self.read_no_fit_usize::<u32>(position, 32)
            };
            T::from_f32_unchecked(f32::from_bits(int))
        } else {
            let int = self.read_no_fit_usize::<u64>(position, 64);
            T::from_f64_unchecked(f64::from_bits(int))
        }
    }

    pub(crate) fn get_sub_buffer(&self, bit_len: usize) -> Result<Self> {
        if bit_len > self.bit_len() {
            return Err(ReadError::NotEnoughData {
                requested: bit_len,
                bits_left: self.bit_len(),
            });
        }

        Ok(BitReadBuffer {
            bytes: Rc::clone(&self.bytes),
            bit_len,
            endianness: PhantomData,
        })
    }
}

impl<E: Endianness> From<Vec<u8>> for BitReadBuffer<E> {
    fn from(bytes: Vec<u8>) -> Self {
        let byte_len = bytes.len();
        BitReadBuffer {
            bytes: Rc::new(bytes),
            bit_len: byte_len * 8,
            endianness: PhantomData,
        }
    }
}

impl<E: Endianness> Clone for BitReadBuffer<E> {
    fn clone(&self) -> Self {
        BitReadBuffer {
            bytes: Rc::clone(&self.bytes),
            bit_len: self.bit_len(),
            endianness: PhantomData,
        }
    }
}

impl<E: Endianness> Debug for BitReadBuffer<E> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "BitBuffer {{ bit_len: {}, endianness: {} }}",
            self.bit_len(),
            E::as_string()
        )
    }
}

/// Return `true` if `x` contains any zero byte except for the topmost byte.
///
/// From *Matters Computational*, J. Arndt
///
/// "The idea is to subtract one from each of the bytes and then look for
/// bytes where the borrow propagated all the way to the most significant
/// bit."
#[inline(always)]
fn contains_zero_byte_non_top(x: usize) -> bool {
    #[cfg(target_pointer_width = "64")]
    const LO_USIZE: usize = 0x0001_0101_0101_0101;
    #[cfg(target_pointer_width = "64")]
    const HI_USIZE: usize = 0x0080_8080_8080_8080;

    #[cfg(target_pointer_width = "32")]
    const LO_USIZE: usize = 0x000_10101;
    #[cfg(target_pointer_width = "32")]
    const HI_USIZE: usize = 0x0080_8080;

    x.wrapping_sub(LO_USIZE) & !x & HI_USIZE != 0
}