Skip to main content

bitstream_io/
read.rs

1// Copyright 2017 Brian Langenberger
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9//! Traits and implementations for reading bits from a stream.
10
11#![warn(missing_docs)]
12
13#[cfg(not(feature = "std"))]
14use no_std_io2::io;
15
16#[cfg(feature = "alloc")]
17use alloc::{vec, vec::Vec};
18#[cfg(feature = "std")]
19use std::io;
20
21use super::{
22    BitCount, CheckablePrimitive, Endianness, Integer, PhantomData, Primitive, SignedBitCount,
23    SignedInteger, UnsignedInteger, VBRInteger,
24};
25
26use core::convert::TryInto;
27
28/// An error returned if performing VBR read overflows
29#[derive(Copy, Clone, Debug)]
30pub(crate) struct VariableWidthOverflow;
31
32impl core::fmt::Display for VariableWidthOverflow {
33    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
34        "variable bit rate overflowed".fmt(f)
35    }
36}
37
38impl core::error::Error for VariableWidthOverflow {}
39
40impl From<VariableWidthOverflow> for io::Error {
41    fn from(VariableWidthOverflow: VariableWidthOverflow) -> Self {
42        io::Error::new(
43            #[cfg(feature = "std")]
44            {
45                io::ErrorKind::StorageFull
46            },
47            #[cfg(not(feature = "std"))]
48            {
49                io::ErrorKind::Other
50            },
51            "variable bit rate overflow",
52        )
53    }
54}
55
56/// A trait for anything that can read a variable number of
57/// potentially un-aligned values from an input stream
58pub trait BitRead {
59    /// Reads a single bit from the stream.
60    /// `true` indicates 1, `false` indicates 0
61    ///
62    /// # Errors
63    ///
64    /// Passes along any I/O error from the underlying stream.
65    ///
66    /// # Examples
67    /// ```
68    /// use bitstream_io::{BitReader, BitRead, BigEndian};
69    ///
70    /// let bytes: &[u8] = &[0b1000_1110];
71    /// let mut r = BitReader::endian(bytes, BigEndian);
72    /// assert_eq!(r.read_bit().unwrap(), true);
73    /// assert_eq!(r.read_bit().unwrap(), false);
74    /// assert_eq!(r.read_bit().unwrap(), false);
75    /// assert_eq!(r.read_bit().unwrap(), false);
76    /// assert_eq!(r.read_bit().unwrap(), true);
77    /// assert_eq!(r.read_bit().unwrap(), true);
78    /// assert_eq!(r.read_bit().unwrap(), true);
79    /// assert_eq!(r.read_bit().unwrap(), false);
80    /// assert!(r.read_bit().is_err());  // no more bits to read
81    /// ```
82    ///
83    /// ```
84    /// use bitstream_io::{BitReader, BitRead, LittleEndian};
85    ///
86    /// let bytes: &[u8] = &[0b1000_1110];
87    /// let mut r = BitReader::endian(bytes, LittleEndian);
88    /// assert_eq!(r.read_bit().unwrap(), false);
89    /// assert_eq!(r.read_bit().unwrap(), true);
90    /// assert_eq!(r.read_bit().unwrap(), true);
91    /// assert_eq!(r.read_bit().unwrap(), true);
92    /// assert_eq!(r.read_bit().unwrap(), false);
93    /// assert_eq!(r.read_bit().unwrap(), false);
94    /// assert_eq!(r.read_bit().unwrap(), false);
95    /// assert_eq!(r.read_bit().unwrap(), true);
96    /// assert!(r.read_bit().is_err());  // no more bits to read
97    /// ```
98    fn read_bit(&mut self) -> io::Result<bool> {
99        self.read_unsigned::<1, u8>().map(|b| b == 1)
100    }
101
102    /// Reads a signed or unsigned value from the stream with
103    /// the given constant number of bits.
104    ///
105    /// # Errors
106    ///
107    /// Passes along any I/O error from the underlying stream.
108    /// A compile-time error occurs if the given number of bits
109    /// is larger than the output type.
110    ///
111    /// # Examples
112    /// ```
113    /// use bitstream_io::{BitReader, BitRead, BigEndian};
114    ///
115    /// let bytes: &[u8] = &[0b0001_1111, 0b1011_11_00];
116    /// let mut r = BitReader::endian(bytes, BigEndian);
117    /// // reading unsigned value is ok
118    /// assert_eq!(r.read::<4, u8>().unwrap(), 1);
119    /// // reading signed value is also ok
120    /// assert_eq!(r.read::<4, i8>().unwrap(), -1);
121    /// // reading an array of bits is ok too
122    /// assert_eq!(r.read::<1, [bool; 4]>().unwrap(), [true, false, true, true]);
123    /// // reading an array of any Integer type is ok
124    /// assert_eq!(r.read::<2, [u8; 2]>().unwrap(), [0b11, 0b00]);
125    /// // reading more bytes than we have is an error
126    /// assert!(r.read::<4, u8>().is_err());
127    /// ```
128    ///
129    /// ```rust,compile_fail
130    /// use bitstream_io::{BitReader, BitRead, BigEndian};
131    ///
132    /// let bytes: &[u8] = &[0b0001_1111, 0, 0];
133    /// let mut r = BitReader::endian(bytes, BigEndian);
134    /// // reading 9 bits to a u8 is a compile-time error
135    /// r.read::<9, u8>();
136    /// ```
137    #[inline]
138    fn read<const BITS: u32, I>(&mut self) -> io::Result<I>
139    where
140        I: Integer,
141    {
142        I::read::<BITS, _>(self)
143    }
144
145    /// Reads a signed or unsigned value from the stream with
146    /// the given variable number of bits.
147    ///
148    /// # Errors
149    ///
150    /// Passes along any I/O error from the underlying stream.
151    /// Also returns an error if the output type is too small
152    /// to hold the requested number of bits.
153    ///
154    /// # Examples
155    /// ```
156    /// use bitstream_io::{BitReader, BitRead, BigEndian};
157    /// let bytes: &[u8] = &[0b0001_1111];
158    /// let mut r = BitReader::endian(bytes, BigEndian);
159    /// // reading unsigned value is ok
160    /// assert_eq!(r.read_var::<u8>(4).unwrap(), 1);
161    /// // reading signed value is also ok
162    /// assert_eq!(r.read_var::<i8>(4).unwrap(), -1);
163    /// // reading more bytes than we have is an error
164    /// assert!(r.read_var::<u8>(4).is_err());
165    /// ```
166    ///
167    /// ```
168    /// use bitstream_io::{BitReader, BitRead, BigEndian};
169    /// let bytes: &[u8] = &[0, 0, 0, 0, 0];
170    /// let mut r = BitReader::endian(bytes, BigEndian);
171    /// // reading 9 bits to a u8 is a runtime error
172    /// // no matter how much data is left
173    /// assert!(r.read_var::<u8>(9).is_err());
174    /// ```
175    #[inline]
176    fn read_var<I>(&mut self, bits: u32) -> io::Result<I>
177    where
178        I: Integer + Sized,
179    {
180        I::read_var(self, BitCount::unknown(bits))
181    }
182
183    /// Given a desired maximum value for a bit count,
184    /// reads the necessary bits to fill up to that amount.
185    ///
186    /// For example, if the maximum bit count is 15 - or `0b1111` -
187    /// reads a 4-bit unsigned value from the stream and returns a [`BitCount`]
188    /// which can be used in subsequent reads.
189    ///
190    /// Note that `MAX` must be greater than 0, and `MAX + 1` must be
191    /// an exact power of two.
192    ///
193    /// # Errors
194    ///
195    /// Passes along an I/O error from the underlying stream.
196    ///
197    /// # Examples
198    ///
199    /// ```
200    /// use bitstream_io::{BigEndian, BitReader, BitRead};
201    ///
202    /// let bytes: &[u8] = &[0b100_11110];
203    /// let mut r = BitReader::endian(bytes, BigEndian);
204    /// let count = r.read::<3, u32>().unwrap();
205    /// assert_eq!(count, 4);  // reads 0b100 - or 4
206    /// // may need to verify count is not larger than u8 at runtime
207    /// assert_eq!(r.read_var::<u8>(count).unwrap(), 0b1111);
208    /// ```
209    ///
210    /// ```
211    /// use bitstream_io::{BigEndian, BitReader, BitRead, BitCount};
212    ///
213    /// let bytes: &[u8] = &[0b100_11110];
214    /// let mut r = BitReader::endian(bytes, BigEndian);
215    /// let count = r.read_count::<0b111>().unwrap();
216    /// assert_eq!(count, BitCount::new::<4>());  // reads 0b100 - or 4
217    /// // maximum size of bit count is known to be 7 at compile-time,
218    /// // so no runtime check needed to know 7 bits is not larger than a u8
219    /// assert_eq!(r.read_counted::<0b111, u8>(count).unwrap(), 0b1111);
220    /// ```
221    ///
222    /// ```rust,compile_fail
223    /// use bitstream_io::{BigEndian, BitReader, BitRead};
224    ///
225    /// let bytes: &[u8] = &[0b100_11110];
226    /// let mut r = BitReader::endian(bytes, BigEndian);
227    /// // maximum bit count is 6 (0b110), so we need to read 3 bits
228    /// // but no idea what to do if a value of 7 (0b111) is read,
229    /// // so this does not compile at all
230    /// let count = r.read_count::<0b110>();
231    /// ```
232    fn read_count<const MAX: u32>(&mut self) -> io::Result<BitCount<MAX>> {
233        const {
234            assert!(MAX > 0, "MAX value must be > 0");
235            assert!(
236                MAX == u32::MAX || (MAX + 1).is_power_of_two(),
237                "MAX should fill some whole number of bits ('0b111', '0b1111', etc.)"
238            )
239        }
240
241        self.read_unsigned_var(if MAX < u32::MAX {
242            (MAX + 1).ilog2()
243        } else {
244            32
245        })
246        .map(|bits| BitCount { bits })
247    }
248
249    /// Reads a signed or unsigned value from the stream with
250    /// the given number of bits.
251    ///
252    /// # Errors
253    ///
254    /// Passes along any I/O error from the underlying stream.
255    /// Also returns an error if the output type is too small
256    /// to hold the requested number of bits.
257    ///
258    /// # Examples
259    /// ```
260    /// use bitstream_io::{BitReader, BitRead, BigEndian, BitCount};
261    ///
262    /// let bytes: &[u8] = &[0b1111_0000];
263    /// let mut r = BitReader::endian(bytes, BigEndian);
264    /// // reading 4 bits with a maximum of 4 will fit into a u8
265    /// // so no runtime check needed
266    /// assert_eq!(r.read_counted::<4, u8>(BitCount::new::<4>()).unwrap(), 0b1111);
267    /// // reading 4 bits with a maximum of 64 might not fit into a u8
268    /// // so we need to verify this at runtime
269    /// assert_eq!(r.read_counted::<64, u8>(BitCount::new::<4>()).unwrap(), 0b0000);
270    /// ```
271    #[inline(always)]
272    fn read_counted<const MAX: u32, I>(&mut self, bits: BitCount<MAX>) -> io::Result<I>
273    where
274        I: Integer + Sized,
275    {
276        I::read_var(self, bits)
277    }
278
279    /// Reads an unsigned value from the stream with
280    /// the given constant number of bits.
281    ///
282    /// # Errors
283    ///
284    /// Passes along any I/O error from the underlying stream.
285    /// A compile-time error occurs if the given number of bits
286    /// is larger than the output type.
287    ///
288    /// # Examples
289    /// ```
290    /// use bitstream_io::{BigEndian, BitReader, BitRead};
291    /// let data: &[u8] = &[0b1_01_10111];
292    /// let mut reader = BitReader::endian(data, BigEndian);
293    /// assert_eq!(reader.read_unsigned::<1, u8>().unwrap(), 0b1);
294    /// assert_eq!(reader.read_unsigned::<2, u8>().unwrap(), 0b01);
295    /// assert_eq!(reader.read_unsigned::<5, u8>().unwrap(), 0b10111);
296    /// ```
297    ///
298    /// ```
299    /// use bitstream_io::{LittleEndian, BitReader, BitRead};
300    /// let data: &[u8] = &[0b10110_11_1];
301    /// let mut reader = BitReader::endian(data, LittleEndian);
302    /// assert_eq!(reader.read_unsigned::<1, u8>().unwrap(), 0b1);
303    /// assert_eq!(reader.read_unsigned::<2, u8>().unwrap(), 0b11);
304    /// assert_eq!(reader.read_unsigned::<5, u8>().unwrap(), 0b10110);
305    /// ```
306    ///
307    /// ```rust,compile_fail
308    /// use bitstream_io::{BigEndian, BitReader, BitRead};
309    /// let data: &[u8] = &[0, 0, 0, 0, 0];
310    /// let mut reader = BitReader::endian(data, BigEndian);
311    /// // doesn't compile at all
312    /// reader.read_unsigned::<9, u8>();  // can't read  9 bits to u8
313    /// ```
314    fn read_unsigned<const BITS: u32, U>(&mut self) -> io::Result<U>
315    where
316        U: UnsignedInteger,
317    {
318        self.read_unsigned_var(BITS)
319    }
320
321    /// Reads an unsigned value from the stream with
322    /// the given number of bits.
323    ///
324    /// # Errors
325    ///
326    /// Passes along any I/O error from the underlying stream.
327    /// Also returns an error if the output type is too small
328    /// to hold the requested number of bits.
329    ///
330    /// # Examples
331    /// ```
332    /// use bitstream_io::{BigEndian, BitReader, BitRead};
333    /// let data: &[u8] = &[0b1_01_10111];
334    /// let mut reader = BitReader::endian(data, BigEndian);
335    /// assert_eq!(reader.read_unsigned_var::<u8>(1).unwrap(), 0b1);
336    /// assert_eq!(reader.read_unsigned_var::<u8>(2).unwrap(), 0b01);
337    /// assert_eq!(reader.read_unsigned_var::<u8>(5).unwrap(), 0b10111);
338    /// ```
339    ///
340    /// ```
341    /// use bitstream_io::{LittleEndian, BitReader, BitRead};
342    /// let data: &[u8] = &[0b10110_11_1];
343    /// let mut reader = BitReader::endian(data, LittleEndian);
344    /// assert_eq!(reader.read_unsigned_var::<u8>(1).unwrap(), 0b1);
345    /// assert_eq!(reader.read_unsigned_var::<u8>(2).unwrap(), 0b11);
346    /// assert_eq!(reader.read_unsigned_var::<u8>(5).unwrap(), 0b10110);
347    /// ```
348    ///
349    /// ```
350    /// use bitstream_io::{BigEndian, BitReader, BitRead};
351    /// let data: &[u8] = &[0, 0, 0, 0, 0];
352    /// let mut reader = BitReader::endian(data, BigEndian);
353    /// assert!(reader.read_unsigned_var::<u8>(9).is_err());    // can't read  9 bits to u8
354    /// assert!(reader.read_unsigned_var::<u16>(17).is_err());  // can't read 17 bits to u16
355    /// assert!(reader.read_unsigned_var::<u32>(33).is_err());  // can't read 33 bits to u32
356    /// assert!(reader.read_unsigned_var::<u64>(65).is_err());  // can't read 65 bits to u64
357    /// ```
358    #[inline(always)]
359    fn read_unsigned_var<U>(&mut self, bits: u32) -> io::Result<U>
360    where
361        U: UnsignedInteger,
362    {
363        self.read_unsigned_counted(BitCount::unknown(bits))
364    }
365
366    /// Reads an unsigned value from the stream with
367    /// the given number of bits.
368    ///
369    /// # Errors
370    ///
371    /// Passes along any I/O error from the underlying stream.
372    /// Also returns an error if the output type is too small
373    /// to hold the requested number of bits.
374    ///
375    /// # Examples
376    /// ```
377    /// use bitstream_io::{BitReader, BitRead, BigEndian, BitCount};
378    ///
379    /// let bytes: &[u8] = &[0b1111_0000];
380    /// let mut r = BitReader::endian(bytes, BigEndian);
381    /// // reading 4 bits with a maximum of 4 will fit into a u8
382    /// // so no runtime check needed
383    /// assert_eq!(r.read_unsigned_counted::<4, u8>(BitCount::new::<4>()).unwrap(), 0b1111);
384    /// // reading 4 bits with a maximum of 64 might not fit into a u8
385    /// // so we need to verify this at runtime
386    /// assert_eq!(r.read_unsigned_counted::<64, u8>(BitCount::new::<4>()).unwrap(), 0b0000);
387    /// ```
388    fn read_unsigned_counted<const MAX: u32, U>(&mut self, bits: BitCount<MAX>) -> io::Result<U>
389    where
390        U: UnsignedInteger;
391
392    /// Reads a twos-complement signed value from the stream with
393    /// the given constant number of bits.
394    ///
395    /// # Errors
396    ///
397    /// Passes along any I/O error from the underlying stream.
398    /// A compile-time error occurs if the number of bits is 0,
399    /// since one bit is always needed for the sign.
400    /// A compile-time error occurs if the given number of bits
401    /// is larger than the output type.
402    ///
403    /// # Examples
404    /// ```
405    /// use bitstream_io::{BigEndian, BitReader, BitRead};
406    ///
407    /// let data: &[u8] = &[0b1011_0111];
408    /// let mut reader = BitReader::endian(data, BigEndian);
409    /// assert_eq!(reader.read_signed::<4, i8>().unwrap(), -5);
410    /// assert_eq!(reader.read_signed::<4, i8>().unwrap(), 7);
411    /// assert!(reader.read_signed::<4, i8>().is_err());
412    /// ```
413    ///
414    /// ```
415    /// use bitstream_io::{LittleEndian, BitReader, BitRead};
416    ///
417    /// let data: &[u8] = &[0b1011_0111];
418    /// let mut reader = BitReader::endian(data, LittleEndian);
419    /// assert_eq!(reader.read_signed::<4, i8>().unwrap(), 7);
420    /// assert_eq!(reader.read_signed::<4, i8>().unwrap(), -5);
421    /// assert!(reader.read_signed::<4, i8>().is_err());
422    /// ```
423    ///
424    /// ```rust,compile_fail
425    /// use bitstream_io::{LittleEndian, BitReader, BitRead};
426    ///
427    /// let data: &[u8] = &[0, 0, 0, 0, 0];
428    /// let mut reader = BitReader::endian(data, LittleEndian);
429    /// // reading 9 bits to an i8 is a compile-time error
430    /// reader.read_signed::<9, i8>();
431    /// ```
432    fn read_signed<const BITS: u32, S>(&mut self) -> io::Result<S>
433    where
434        S: SignedInteger,
435    {
436        self.read_signed_var(BITS)
437    }
438
439    /// Reads a twos-complement signed value from the stream with
440    /// the given number of bits.
441    ///
442    /// # Errors
443    ///
444    /// Passes along any I/O error from the underlying stream.
445    /// Returns an error if the number of bits is 0,
446    /// since one bit is always needed for the sign.
447    /// Also returns an error if the output type is too small
448    /// to hold the requested number of bits.
449    ///
450    /// # Examples
451    /// ```
452    /// use bitstream_io::{BigEndian, BitReader, BitRead};
453    /// let data: &[u8] = &[0b1011_0111];
454    /// let mut reader = BitReader::endian(data, BigEndian);
455    /// assert_eq!(reader.read_signed_var::<i8>(4).unwrap(), -5);
456    /// assert_eq!(reader.read_signed_var::<i8>(4).unwrap(), 7);
457    /// ```
458    ///
459    /// ```
460    /// use bitstream_io::{LittleEndian, BitReader, BitRead};
461    /// let data: &[u8] = &[0b1011_0111];
462    /// let mut reader = BitReader::endian(data, LittleEndian);
463    /// assert_eq!(reader.read_signed_var::<i8>(4).unwrap(), 7);
464    /// assert_eq!(reader.read_signed_var::<i8>(4).unwrap(), -5);
465    /// ```
466    ///
467    /// ```
468    /// use std::io::Read;
469    /// use bitstream_io::{BigEndian, BitReader, BitRead};
470    /// let data: &[u8] = &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
471    /// let mut r = BitReader::endian(data, BigEndian);
472    /// assert!(r.read_signed_var::<i8>(9).is_err());   // can't read 9 bits to i8
473    /// assert!(r.read_signed_var::<i16>(17).is_err()); // can't read 17 bits to i16
474    /// assert!(r.read_signed_var::<i32>(33).is_err()); // can't read 33 bits to i32
475    /// assert!(r.read_signed_var::<i64>(65).is_err()); // can't read 65 bits to i64
476    /// ```
477    fn read_signed_var<S>(&mut self, bits: u32) -> io::Result<S>
478    where
479        S: SignedInteger,
480    {
481        self.read_signed_counted(BitCount::unknown(bits))
482    }
483
484    /// Reads a twos-complement signed value from the stream with
485    /// the given number of bits.
486    ///
487    /// # Errors
488    ///
489    /// Passes along any I/O error from the underlying stream.
490    /// Returns an error if the number of bits is 0,
491    /// since one bit is always needed for the sign.
492    /// Also returns an error if the output type is too small
493    /// to hold the requested number of bits.
494    ///
495    /// # Examples
496    /// ```
497    /// use bitstream_io::{BitReader, BitRead, BigEndian, BitCount};
498    ///
499    /// let bytes: &[u8] = &[0b0001_1111];
500    /// let mut r = BitReader::endian(bytes, BigEndian);
501    /// // reading 4 bits with a maximum of 4 will fit into an i8
502    /// // so no runtime check needed
503    /// assert_eq!(r.read_signed_counted::<4, i8>(BitCount::new::<4>()).unwrap(), 1);
504    /// // reading 4 bits with a maximum of 64 might not fit into an i8
505    /// // so we need to verify this at runtime
506    /// assert_eq!(r.read_signed_counted::<64, i8>(BitCount::new::<4>()).unwrap(), -1);
507    /// ```
508    fn read_signed_counted<const MAX: u32, S>(
509        &mut self,
510        bits: impl TryInto<SignedBitCount<MAX>>,
511    ) -> io::Result<S>
512    where
513        S: SignedInteger;
514
515    /// Reads the given constant value from the stream with the
516    /// given number of bits.
517    ///
518    /// Due to current limitations of constant paramters,
519    /// this is limited to `u32` values.
520    ///
521    /// If the constant read from the stream doesn't match the expected
522    /// value, returns the generated error from the closure.
523    ///
524    /// # Errors
525    ///
526    /// Passes along any I/O error from the underlying stream,
527    /// converted to the mismatch error.  Returns the generated
528    /// error if the read value doesn't match the expected constant.
529    ///
530    /// # Examples
531    ///
532    /// ```
533    /// use bitstream_io::{BitReader, BitRead, BigEndian};
534    ///
535    /// enum Error {
536    ///     Mismatch,
537    ///     Io,
538    /// }
539    ///
540    /// impl From<std::io::Error> for Error {
541    ///     fn from(_err: std::io::Error) -> Self {
542    ///         Self::Io
543    ///     }
544    /// }
545    ///
546    /// let data: &[u8] = &[0b1000_1011, 0b0000_0001];
547    /// let mut r = BitReader::endian(data, BigEndian);
548    /// assert!(r.read_const::<4, 0b1000, _>(Error::Mismatch).is_ok());
549    /// assert!(r.read_const::<4, 0b1011, _>(Error::Mismatch).is_ok());
550    /// // 0b1000 doesn't match 0b0000
551    /// assert!(matches!(r.read_const::<4, 0b1000, _>(Error::Mismatch), Err(Error::Mismatch)));
552    /// // 0b1011 doesn't match 0b0001
553    /// assert!(matches!(r.read_const::<4, 0b1011, _>(Error::Mismatch), Err(Error::Mismatch)));
554    /// // run out of bits to check
555    /// assert!(matches!(r.read_const::<4, 0b0000, _>(Error::Mismatch), Err(Error::Io)));
556    /// ```
557    #[inline]
558    fn read_const<const BITS: u32, const VALUE: u32, E>(&mut self, err: E) -> Result<(), E>
559    where
560        E: From<io::Error>,
561    {
562        use super::Numeric;
563
564        const {
565            assert!(
566                BITS == 0 || VALUE <= (u32::ALL >> (u32::BITS_SIZE - BITS)),
567                "excessive value for bits read"
568            );
569        }
570
571        (self.read::<BITS, u32>()? == VALUE)
572            .then_some(())
573            .ok_or(err)
574    }
575
576    /// Reads whole value from the stream whose size in bits is equal
577    /// to its type's size.
578    ///
579    /// # Errors
580    ///
581    /// Passes along any I/O error from the underlying stream.
582    ///
583    /// # Examples
584    /// ```
585    /// use bitstream_io::{BitReader, BitRead, BigEndian};
586    ///
587    /// let bytes: &[u8] = &[0x12, 0x34, 0x56, 0x78];
588    /// let mut r = BitReader::endian(bytes, BigEndian);
589    /// assert_eq!(r.read_to::<u32>().unwrap(), 0x12_34_56_78);
590    /// ```
591    ///
592    /// ```
593    /// use bitstream_io::{BitReader, BitRead, BigEndian};
594    ///
595    /// let bytes: &[u8] = &[0x12, 0x34, 0x56, 0x78];
596    /// let mut r = BitReader::endian(bytes, BigEndian);
597    /// assert_eq!(r.read_to::<[u8; 4]>().unwrap(), [0x12, 0x34, 0x56, 0x78]);
598    /// ```
599    fn read_to<V>(&mut self) -> io::Result<V>
600    where
601        V: Primitive;
602
603    /// Reads whole value from the stream whose size in bits is equal
604    /// to its type's size in an endianness that may be different
605    /// from the stream's endianness.
606    ///
607    /// # Errors
608    ///
609    /// Passes along any I/O error from the underlying stream.
610    ///
611    /// # Example
612    /// ```
613    /// use bitstream_io::{BitReader, BitRead, BigEndian, LittleEndian};
614    ///
615    /// let bytes: &[u8] = &[0x12, 0x34, 0x56, 0x78];
616    /// let mut r = BitReader::endian(bytes, BigEndian);
617    /// assert_eq!(r.read_as_to::<LittleEndian, u32>().unwrap(), 0x78_56_34_12);
618    /// ```
619    fn read_as_to<F, V>(&mut self) -> io::Result<V>
620    where
621        F: Endianness,
622        V: Primitive;
623
624    /// Skips the given number of bits in the stream.
625    /// Since this method does not need an accumulator,
626    /// it may be slightly faster than reading to an empty variable.
627    /// In addition, since there is no accumulator,
628    /// there is no upper limit on the number of bits
629    /// which may be skipped.
630    /// These bits are still read from the stream, however,
631    /// and are never skipped via a `seek` method.
632    ///
633    /// # Errors
634    ///
635    /// Passes along any I/O error from the underlying stream.
636    ///
637    /// # Example
638    /// ```
639    /// use bitstream_io::{BitReader, BitRead, BigEndian};
640    ///
641    /// let bytes: &[u8] = &[0b1_00000_10];
642    /// let mut r = BitReader::endian(bytes, BigEndian);
643    /// assert_eq!(r.read_bit().unwrap(), true);
644    /// assert!(r.skip(5).is_ok());
645    /// assert_eq!(r.read_bit().unwrap(), true);
646    /// assert_eq!(r.read_bit().unwrap(), false);
647    /// assert!(r.read_bit().is_err());
648    /// ```
649    fn skip(&mut self, bits: u32) -> io::Result<()> {
650        (0..bits).try_for_each(|_| self.read_bit().map(|_| ()))
651    }
652
653    /// Completely fills the given buffer with whole bytes.
654    /// If the stream is already byte-aligned, it will map
655    /// to a faster `read_exact` call.  Otherwise it will read
656    /// bytes individually in 8-bit increments.
657    ///
658    /// # Errors
659    ///
660    /// Passes along any I/O error from the underlying stream.
661    ///
662    /// # Example
663    /// ```
664    /// use bitstream_io::{BitReader, BitRead, BigEndian};
665    ///
666    /// let bytes: &[u8] = &[0x00, 0x01, 0x02, 0x03, 0x04];
667    /// let mut r = BitReader::endian(bytes, BigEndian);
668    /// let mut buf = [0; 3];
669    /// assert_eq!(r.read::<8, u8>().unwrap(), 0x00);
670    /// assert!(r.read_bytes(&mut buf).is_ok());
671    /// assert_eq!(&buf, &[0x01, 0x02, 0x03]);
672    /// assert_eq!(r.read::<8, u8>().unwrap(), 0x04);
673    /// ```
674    fn read_bytes(&mut self, buf: &mut [u8]) -> io::Result<()> {
675        for b in buf.iter_mut() {
676            *b = self.read_unsigned::<8, _>()?;
677        }
678        Ok(())
679    }
680
681    /// Completely fills a whole buffer with bytes and returns it.
682    /// If the stream is already byte-aligned, it will map
683    /// to a faster `read_exact` call.  Otherwise it will read
684    /// bytes individually in 8-bit increments.
685    ///
686    /// # Errors
687    ///
688    /// Passes along any I/O error from the underlying stream.
689    #[inline(always)]
690    #[deprecated(since = "1.8.0", note = "use read_to() method instead")]
691    fn read_to_bytes<const SIZE: usize>(&mut self) -> io::Result<[u8; SIZE]> {
692        self.read_to()
693    }
694
695    /// Completely fills a vector of bytes and returns it.
696    /// If the stream is already byte-aligned, it will map
697    /// to a faster `read_exact` call.  Otherwise it will read
698    /// bytes individually in 8-bit increments.
699    ///
700    /// # Errors
701    ///
702    /// Passes along any I/O error from the underlying stream.
703    ///
704    /// # Example
705    /// ```
706    /// use bitstream_io::{BitReader, BitRead, BigEndian};
707    ///
708    /// let bytes: &[u8] = &[0x00, 0x01, 0x02, 0x03, 0x04];
709    /// let mut r = BitReader::endian(bytes, BigEndian);
710    /// let mut buf = [0; 3];
711    /// assert_eq!(r.read::<8, u8>().unwrap(), 0x00);
712    /// assert_eq!(r.read_to_vec(3).unwrap().as_slice(), &[0x01, 0x02, 0x03]);
713    /// assert_eq!(r.read::<8, u8>().unwrap(), 0x04);
714    /// ```
715    #[cfg(feature = "alloc")]
716    fn read_to_vec(&mut self, bytes: usize) -> io::Result<Vec<u8>> {
717        read_to_vec(|buf| self.read_bytes(buf), bytes)
718    }
719
720    /// Counts the number of bits in the stream until `STOP_BIT`
721    /// and returns the amount read.
722    /// `STOP_BIT` must be 0 or 1.
723    /// Because this field is variably-sized and may be large,
724    /// its output is always a `u32` type.
725    ///
726    /// # Errors
727    ///
728    /// Passes along any I/O error from the underlying stream.
729    /// May panic if the number of bits exceeds `u32`.
730    ///
731    /// # Examples
732    /// ```
733    /// use bitstream_io::{BitReader, BitRead, BigEndian};
734    ///
735    /// let bytes: &[u8] = &[0b0_10_11111, 0b10_000000];
736    /// let mut r = BitReader::endian(bytes, BigEndian);
737    /// // read 1 bits until stop bit of 0, big-endian order
738    /// assert_eq!(r.read_unary::<0>().unwrap(), 0);
739    /// assert_eq!(r.read_unary::<0>().unwrap(), 1);
740    /// assert_eq!(r.read_unary::<0>().unwrap(), 6);
741    /// ```
742    ///
743    /// ```
744    /// use bitstream_io::{BitReader, BitRead, BigEndian};
745    ///
746    /// let bytes: &[u8] = &[0b1_01_00000, 0b01_000000];
747    /// let mut r = BitReader::endian(bytes, BigEndian);
748    /// // read 0 bits until stop bit of 1, big-endian order
749    /// assert_eq!(r.read_unary::<1>().unwrap(), 0);
750    /// assert_eq!(r.read_unary::<1>().unwrap(), 1);
751    /// assert_eq!(r.read_unary::<1>().unwrap(), 6);
752    /// ```
753    ///
754    /// ```
755    /// use bitstream_io::{BitReader, BitRead, LittleEndian};
756    ///
757    /// let bytes: &[u8] = &[0b11111_01_0, 0b000000_01];
758    /// let mut r = BitReader::endian(bytes, LittleEndian);
759    /// // read 1 bits until stop bit of 0, little-endian order
760    /// assert_eq!(r.read_unary::<0>().unwrap(), 0);
761    /// assert_eq!(r.read_unary::<0>().unwrap(), 1);
762    /// assert_eq!(r.read_unary::<0>().unwrap(), 6);
763    /// ```
764    ///
765    /// ```
766    /// use bitstream_io::{BitReader, BitRead, LittleEndian};
767    ///
768    /// let bytes: &[u8] = &[0b00000_10_1, 0b111111_10];
769    /// let mut r = BitReader::endian(bytes, LittleEndian);
770    /// // read 0 bits until stop bit of 1, little-endian order
771    /// assert_eq!(r.read_unary::<1>().unwrap(), 0);
772    /// assert_eq!(r.read_unary::<1>().unwrap(), 1);
773    /// assert_eq!(r.read_unary::<1>().unwrap(), 6);
774    /// ```
775    fn read_unary<const STOP_BIT: u8>(&mut self) -> io::Result<u32> {
776        const {
777            assert!(matches!(STOP_BIT, 0 | 1), "stop bit must be 0 or 1");
778        }
779
780        // a simple implementation which works anywhere
781        let mut unary = 0;
782        while self.read::<1, u8>()? != STOP_BIT {
783            unary += 1;
784        }
785        Ok(unary)
786    }
787
788    /// Reads to a checked value that is known to fit a given number of bits
789    ///
790    /// # Example
791    /// ```
792    /// use bitstream_io::{
793    ///     BitRead, BitReader, BigEndian, Checked, CheckedUnsigned, CheckedSigned,
794    ///     BitCount, SignedBitCount, BitWrite, BitWriter,
795    /// };
796    ///
797    /// let data: &[u8] = &[0b1001_1111];
798    /// let mut r = BitReader::endian(data, BigEndian);
799    ///
800    /// let bit_count = BitCount::<4>::new::<4>();
801    /// let checked_u8 = r.read_checked::<CheckedUnsigned<4, u8>>(bit_count).unwrap();
802    /// assert_eq!(checked_u8.into_value(), 0b1001);
803    ///
804    /// let bit_count = SignedBitCount::<4>::new::<4>();
805    /// let checked_i8 = r.read_checked::<CheckedSigned<4, i8>>(bit_count).unwrap();
806    /// assert_eq!(checked_i8.into_value(), -1);
807    ///
808    /// // note that checked values already know their bit count
809    /// // so none is required when writing them to a stream
810    /// let mut w = BitWriter::endian(vec![], BigEndian);
811    /// w.write_checked(checked_u8).unwrap();
812    /// w.write_checked(checked_i8).unwrap();
813    /// assert_eq!(w.into_writer().as_slice(), data);
814    /// ```
815    #[inline]
816    fn read_checked<C>(&mut self, count: C::CountType) -> io::Result<C>
817    where
818        C: CheckablePrimitive,
819    {
820        C::read(self, count)
821    }
822
823    /// Parses and returns complex type
824    fn parse<F: FromBitStream>(&mut self) -> Result<F, F::Error> {
825        F::from_reader(self)
826    }
827
828    /// Parses and returns complex type with context
829    fn parse_with<'a, F: FromBitStreamWith<'a>>(
830        &mut self,
831        context: &F::Context,
832    ) -> Result<F, F::Error> {
833        F::from_reader(self, context)
834    }
835
836    /// Parses and returns complex type with owned context
837    fn parse_using<F: FromBitStreamUsing>(&mut self, context: F::Context) -> Result<F, F::Error> {
838        F::from_reader(self, context)
839    }
840
841    /// Returns true if the stream is aligned at a whole byte.
842    ///
843    /// # Example
844    /// ```
845    /// use std::io::Read;
846    /// use bitstream_io::{BigEndian, BitReader, BitRead};
847    /// let data = [0];
848    /// let mut reader = BitReader::endian(data.as_slice(), BigEndian);
849    /// assert_eq!(reader.byte_aligned(), true);
850    /// assert!(reader.skip(1).is_ok());
851    /// assert_eq!(reader.byte_aligned(), false);
852    /// assert!(reader.skip(7).is_ok());
853    /// assert_eq!(reader.byte_aligned(), true);
854    /// ```
855    fn byte_aligned(&self) -> bool;
856
857    /// Throws away all unread bit values until the next whole byte.
858    /// Does nothing if the stream is already aligned.
859    ///
860    /// # Example
861    /// ```
862    /// use bitstream_io::{BigEndian, BitReader, BitRead};
863    /// let data: &[u8] = &[0x00, 0xFF];
864    /// let mut reader = BitReader::endian(data, BigEndian);
865    /// assert_eq!(reader.read::<4, u8>().unwrap(), 0);
866    /// reader.byte_align();
867    /// assert_eq!(reader.read::<8, u8>().unwrap(), 0xFF);
868    /// ```
869    fn byte_align(&mut self);
870
871    /// Given a compiled Huffman tree, reads bits from the stream
872    /// until the next symbol is encountered.
873    ///
874    /// # Errors
875    ///
876    /// Passes along any I/O error from the underlying stream.
877    ///
878    /// # Example
879    ///
880    /// ```
881    /// use bitstream_io::{BitReader, BitRead, BigEndian, define_huffman_tree, huffman::FromBits};
882    ///
883    /// define_huffman_tree!(TreeName : char = ['a', ['b', ['c', 'd']]]);
884    /// // 'a' is 0
885    /// // 'b' is 1 -> 0
886    /// // 'c' is 1 -> 1 -> 0
887    /// // 'd' is 1 -> 1 -> 1
888    ///
889    /// let data: &[u8] = &[0b0_10_110_11, 0b1_0000000];
890    /// let mut r = BitReader::endian(data, BigEndian);
891    /// assert_eq!(r.read_huffman::<TreeName>().unwrap(), 'a');
892    /// assert_eq!(r.read_huffman::<TreeName>().unwrap(), 'b');
893    /// assert_eq!(r.read_huffman::<TreeName>().unwrap(), 'c');
894    /// assert_eq!(r.read_huffman::<TreeName>().unwrap(), 'd');
895    /// ```
896    #[inline]
897    fn read_huffman<T>(&mut self) -> io::Result<T::Symbol>
898    where
899        T: crate::huffman::FromBits,
900    {
901        T::from_bits(|| self.read_bit())
902    }
903
904    /// Reads a number using a variable using a variable width integer.
905    /// This optimises the case when the number is small.
906    ///
907    /// The integer is mapped to an unsigned value using zigzag encoding.
908    /// For an integer X:
909    ///   - if X >= 0 -> 2X
910    ///   - else -> -2X + 1
911    ///
912    /// # Errors
913    ///
914    /// Passes along any I/O error from the underlying stream.
915    /// Returns an error if the data read would overflow the size of the result
916    ///
917    /// # Example
918    /// ```
919    /// use bitstream_io::{BitReader, BitRead, BigEndian};
920    ///
921    /// let bytes: &[u8] = &[0b0111_1100, 0b1100_0001];
922    /// let mut r = BitReader::endian(bytes, BigEndian);
923    /// assert_eq!(r.read_unsigned_vbr::<4, u32>().unwrap(), 7);
924    /// assert_eq!(r.read_unsigned_vbr::<4, u32>().unwrap(), 100);
925    /// ```
926    /// ```
927    /// use bitstream_io::{BitReader, BitRead, BigEndian};
928    ///
929    /// let bytes: &[u8] = &[0b1111_1111, 0b0011_1000, 0b1000_0100, 0b1000_1000, 0b1000_0000];
930    /// let mut r = BitReader::endian(bytes, BigEndian);
931    /// assert_eq!(r.read_unsigned_vbr::<4, u8>().unwrap(), 255); // Tries to read <011><111><111>
932    /// assert!(r.read_unsigned_vbr::<4, u8>().is_err()); // Tries to read a value of <100><000><000>
933    /// assert!(r.read_unsigned_vbr::<4, u8>().is_err()); // Tries to read a value of <000><000><000><000>
934    /// ```
935    fn read_unsigned_vbr<const FIELD_SIZE: u32, U: UnsignedInteger>(&mut self) -> io::Result<U> {
936        const { assert!(FIELD_SIZE >= 2 && FIELD_SIZE < U::BITS_SIZE) };
937        let payload_bits = FIELD_SIZE - 1;
938        let mut value = U::ZERO;
939        let mut shift = 0u32;
940        loop {
941            let (data, continuation) = self.read_unsigned::<FIELD_SIZE, U>().map(|item| {
942                (
943                    item & ((U::ONE << payload_bits) - U::ONE),
944                    (item >> payload_bits) != U::ZERO,
945                )
946            })?;
947            let shifted = data << shift;
948            value |= shifted;
949            if !continuation {
950                if (data << shift) >> shift == data {
951                    break Ok(value);
952                } else {
953                    break Err(VariableWidthOverflow {}.into());
954                }
955            }
956            shift += payload_bits;
957            if shift >= U::BITS_SIZE {
958                break Err(VariableWidthOverflow {}.into());
959            }
960        }
961    }
962
963    /// Reads a number using a variable using a variable width integer.
964    /// This optimises the case when the number is small.
965    ///
966    /// The integer is mapped to an unsigned value using zigzag encoding.
967    /// For an integer X:
968    ///   - if X >= 0 -> 2X
969    ///   - else -> -2X + 1
970    ///
971    /// # Errors
972    ///
973    /// Passes along any I/O error from the underlying stream.
974    /// Returns an error if the data read would overflow the size of the result
975    ///
976    /// # Example
977    /// ```
978    /// use bitstream_io::{BitReader, BitRead, BigEndian};
979    ///
980    /// let bytes: &[u8] = &[0b0110_1011, 0b1100_0001];
981    /// let mut r = BitReader::endian(bytes, BigEndian);
982    /// assert_eq!(r.read_signed_vbr::<4, i32>().unwrap(), 3);
983    /// assert_eq!(r.read_signed_vbr::<4, i32>().unwrap(), -50);
984    /// ```
985    fn read_signed_vbr<const FIELD_SIZE: u32, I: SignedInteger>(&mut self) -> io::Result<I> {
986        self.read_unsigned_vbr::<FIELD_SIZE, I::Unsigned>()
987            .map(|zig_zag| {
988                let shifted = zig_zag >> 1;
989                let complimented = zig_zag & <I::Unsigned as crate::Numeric>::ONE;
990                let neg = I::ZERO - complimented.as_non_negative();
991                shifted.as_non_negative() ^ neg
992            })
993    }
994
995    /// Reads a signed or unsigned variable width integer from the stream.
996    ///
997    /// # Errors
998    ///
999    /// Passes along any I/O error from the underlying stream.
1000    /// Returns an error if the data read would overflow the size of the result
1001    ///
1002    /// # Example
1003    /// ```
1004    /// use bitstream_io::{BitReader, BitRead, BigEndian};
1005    ///
1006    /// let bytes: &[u8] = &[0b0110_1011, 0b1100_0001];
1007    /// let mut r = BitReader::endian(bytes, BigEndian);
1008    /// assert_eq!(r.read_vbr::<4, u32>().unwrap(), 6);
1009    /// assert_eq!(r.read_vbr::<4, i32>().unwrap(), -50);
1010    /// ```
1011    #[inline]
1012    fn read_vbr<const FIELD_SIZE: u32, I: VBRInteger>(&mut self) -> io::Result<I> {
1013        I::read_vbr::<FIELD_SIZE, _>(self)
1014    }
1015
1016    /// Creates a "by reference" adaptor for this `BitRead`
1017    ///
1018    /// The returned adapter also implements `BitRead`
1019    /// and will borrow the current reader.
1020    ///
1021    /// # Example
1022    /// ```
1023    /// use bitstream_io::{BitReader, BitRead, BigEndian};
1024    ///
1025    /// fn parse<R: BitRead>(r: R) {
1026    ///     // perform some parsing
1027    /// }
1028    ///
1029    /// let data: &[u8] = &[0];
1030    /// let mut reader = BitReader::endian(data, BigEndian);
1031    /// // performing parsing by reference
1032    /// parse(reader.by_ref());
1033    /// // original owned reader still available
1034    /// assert_eq!(reader.read::<8, u8>().unwrap(), 0);
1035    /// ```
1036    #[inline]
1037    fn by_ref(&mut self) -> &mut Self {
1038        self
1039    }
1040}
1041
1042impl<R: BitRead + ?Sized> BitRead for &mut R {
1043    #[inline]
1044    fn read_bit(&mut self) -> io::Result<bool> {
1045        (**self).read_bit()
1046    }
1047
1048    #[inline]
1049    fn read<const BITS: u32, I>(&mut self) -> io::Result<I>
1050    where
1051        I: Integer,
1052    {
1053        (**self).read::<BITS, I>()
1054    }
1055
1056    #[inline]
1057    fn read_var<I>(&mut self, bits: u32) -> io::Result<I>
1058    where
1059        I: Integer + Sized,
1060    {
1061        (**self).read_var(bits)
1062    }
1063
1064    #[inline]
1065    fn read_count<const MAX: u32>(&mut self) -> io::Result<BitCount<MAX>> {
1066        (**self).read_count::<MAX>()
1067    }
1068
1069    #[inline]
1070    fn read_counted<const MAX: u32, I>(&mut self, bits: BitCount<MAX>) -> io::Result<I>
1071    where
1072        I: Integer + Sized,
1073    {
1074        (**self).read_counted::<MAX, I>(bits)
1075    }
1076
1077    #[inline]
1078    fn read_unsigned<const BITS: u32, U>(&mut self) -> io::Result<U>
1079    where
1080        U: UnsignedInteger,
1081    {
1082        (**self).read_unsigned::<BITS, U>()
1083    }
1084
1085    #[inline]
1086    fn read_unsigned_var<U>(&mut self, bits: u32) -> io::Result<U>
1087    where
1088        U: UnsignedInteger,
1089    {
1090        (**self).read_unsigned_var(bits)
1091    }
1092
1093    #[inline]
1094    fn read_unsigned_counted<const MAX: u32, U>(&mut self, bits: BitCount<MAX>) -> io::Result<U>
1095    where
1096        U: UnsignedInteger,
1097    {
1098        (**self).read_unsigned_counted::<MAX, U>(bits)
1099    }
1100
1101    #[inline]
1102    fn read_signed<const BITS: u32, S>(&mut self) -> io::Result<S>
1103    where
1104        S: SignedInteger,
1105    {
1106        (**self).read_signed::<BITS, S>()
1107    }
1108
1109    #[inline]
1110    fn read_signed_var<S>(&mut self, bits: u32) -> io::Result<S>
1111    where
1112        S: SignedInteger,
1113    {
1114        (**self).read_signed_var(bits)
1115    }
1116
1117    #[inline]
1118    fn read_signed_counted<const MAX: u32, S>(
1119        &mut self,
1120        bits: impl TryInto<SignedBitCount<MAX>>,
1121    ) -> io::Result<S>
1122    where
1123        S: SignedInteger,
1124    {
1125        (**self).read_signed_counted::<MAX, S>(bits)
1126    }
1127
1128    #[inline]
1129    fn read_to<V>(&mut self) -> io::Result<V>
1130    where
1131        V: Primitive,
1132    {
1133        (**self).read_to::<V>()
1134    }
1135
1136    #[inline]
1137    fn read_as_to<F, V>(&mut self) -> io::Result<V>
1138    where
1139        F: Endianness,
1140        V: Primitive,
1141    {
1142        (**self).read_as_to::<F, V>()
1143    }
1144
1145    #[inline]
1146    fn skip(&mut self, bits: u32) -> io::Result<()> {
1147        (**self).skip(bits)
1148    }
1149
1150    #[inline]
1151    fn read_bytes(&mut self, buf: &mut [u8]) -> io::Result<()> {
1152        (**self).read_bytes(buf)
1153    }
1154
1155    #[inline]
1156    #[cfg(feature = "alloc")]
1157    fn read_to_vec(&mut self, bytes: usize) -> io::Result<Vec<u8>> {
1158        (**self).read_to_vec(bytes)
1159    }
1160
1161    #[inline]
1162    fn read_unary<const STOP_BIT: u8>(&mut self) -> io::Result<u32> {
1163        (**self).read_unary::<STOP_BIT>()
1164    }
1165
1166    #[inline]
1167    fn parse<F: FromBitStream>(&mut self) -> Result<F, F::Error> {
1168        (**self).parse::<F>()
1169    }
1170
1171    #[inline]
1172    fn parse_with<'a, F: FromBitStreamWith<'a>>(
1173        &mut self,
1174        context: &F::Context,
1175    ) -> Result<F, F::Error> {
1176        (**self).parse_with::<F>(context)
1177    }
1178
1179    #[inline]
1180    fn byte_aligned(&self) -> bool {
1181        (**self).byte_aligned()
1182    }
1183
1184    #[inline]
1185    fn byte_align(&mut self) {
1186        (**self).byte_align()
1187    }
1188
1189    #[inline]
1190    fn read_huffman<T>(&mut self) -> io::Result<T::Symbol>
1191    where
1192        T: crate::huffman::FromBits,
1193    {
1194        (**self).read_huffman::<T>()
1195    }
1196}
1197
1198/// A compatibility trait for older code implementing [`BitRead`]
1199///
1200/// This is a trait largely compatible with older code
1201/// from the 2.X.X version,
1202/// which one can use with a named import as needed.
1203///
1204/// New code should prefer the regular [`BitRead`] trait.
1205///
1206/// # Example
1207/// ```
1208/// use bitstream_io::BitRead2 as BitRead;
1209/// use bitstream_io::{BitReader, BigEndian};
1210/// let byte = &[0b1111_0000];
1211/// let mut reader = BitReader::endian(byte.as_slice(), BigEndian);
1212/// assert_eq!(reader.read::<u8>(4).unwrap(), 0b1111);
1213/// assert_eq!(reader.read_in::<4, u8>().unwrap(), 0b0000);
1214/// ```
1215pub trait BitRead2 {
1216    /// Reads a single bit from the stream.
1217    /// `true` indicates 1, `false` indicates 0
1218    ///
1219    /// # Errors
1220    ///
1221    /// Passes along any I/O error from the underlying stream.
1222    fn read_bit(&mut self) -> io::Result<bool>;
1223
1224    /// Reads an unsigned value from the stream with
1225    /// the given number of bits.
1226    ///
1227    /// # Errors
1228    ///
1229    /// Passes along any I/O error from the underlying stream.
1230    /// Also returns an error if the output type is too small
1231    /// to hold the requested number of bits.
1232    fn read<I>(&mut self, bits: u32) -> io::Result<I>
1233    where
1234        I: Integer + Sized;
1235
1236    /// Reads an unsigned value from the stream with
1237    /// the given constant number of bits.
1238    ///
1239    /// # Errors
1240    ///
1241    /// Passes along any I/O error from the underlying stream.
1242    /// A compile-time error occurs if the given number of bits
1243    /// is larger than the output type.
1244    fn read_in<const BITS: u32, I>(&mut self) -> io::Result<I>
1245    where
1246        I: Integer,
1247    {
1248        self.read(BITS)
1249    }
1250
1251    /// Reads a twos-complement signed value from the stream with
1252    /// the given number of bits.
1253    ///
1254    /// # Errors
1255    ///
1256    /// Passes along any I/O error from the underlying stream.
1257    /// Returns an error if the number of bits is 0,
1258    /// since one bit is always needed for the sign.
1259    /// Also returns an error if the output type is too small
1260    /// to hold the requested number of bits.
1261    fn read_signed<S>(&mut self, bits: u32) -> io::Result<S>
1262    where
1263        S: SignedInteger;
1264
1265    /// Reads a twos-complement signed value from the stream with
1266    /// the given constant number of bits.
1267    ///
1268    /// # Errors
1269    ///
1270    /// Passes along any I/O error from the underlying stream.
1271    /// A compile-time error occurs if the number of bits is 0,
1272    /// since one bit is always needed for the sign.
1273    /// A compile-time error occurs if the given number of bits
1274    /// is larger than the output type.
1275    fn read_signed_in<const BITS: u32, S>(&mut self) -> io::Result<S>
1276    where
1277        S: SignedInteger,
1278    {
1279        self.read_signed(BITS)
1280    }
1281
1282    /// Reads whole value from the stream whose size in bits is equal
1283    /// to its type's size.
1284    ///
1285    /// # Errors
1286    ///
1287    /// Passes along any I/O error from the underlying stream.
1288    fn read_to<V>(&mut self) -> io::Result<V>
1289    where
1290        V: Primitive;
1291
1292    /// Reads whole value from the stream whose size in bits is equal
1293    /// to its type's size in an endianness that may be different
1294    /// from the stream's endianness.
1295    ///
1296    /// # Errors
1297    ///
1298    /// Passes along any I/O error from the underlying stream.
1299    fn read_as_to<F, V>(&mut self) -> io::Result<V>
1300    where
1301        F: Endianness,
1302        V: Primitive;
1303
1304    /// Skips the given number of bits in the stream.
1305    /// Since this method does not need an accumulator,
1306    /// it may be slightly faster than reading to an empty variable.
1307    /// In addition, since there is no accumulator,
1308    /// there is no upper limit on the number of bits
1309    /// which may be skipped.
1310    /// These bits are still read from the stream, however,
1311    /// and are never skipped via a `seek` method.
1312    ///
1313    /// # Errors
1314    ///
1315    /// Passes along any I/O error from the underlying stream.
1316    fn skip(&mut self, bits: u32) -> io::Result<()>;
1317
1318    /// Completely fills the given buffer with whole bytes.
1319    /// If the stream is already byte-aligned, it will map
1320    /// to a faster `read_exact` call.  Otherwise it will read
1321    /// bytes individually in 8-bit increments.
1322    ///
1323    /// # Errors
1324    ///
1325    /// Passes along any I/O error from the underlying stream.
1326    fn read_bytes(&mut self, buf: &mut [u8]) -> io::Result<()> {
1327        for b in buf.iter_mut() {
1328            *b = self.read_in::<8, _>()?;
1329        }
1330        Ok(())
1331    }
1332
1333    /// Completely fills a whole buffer with bytes and returns it.
1334    /// If the stream is already byte-aligned, it will map
1335    /// to a faster `read_exact` call.  Otherwise it will read
1336    /// bytes individually in 8-bit increments.
1337    ///
1338    /// # Errors
1339    ///
1340    /// Passes along any I/O error from the underlying stream.
1341    #[inline(always)]
1342    #[deprecated(since = "1.8.0", note = "use read_to() method instead")]
1343    fn read_to_bytes<const SIZE: usize>(&mut self) -> io::Result<[u8; SIZE]> {
1344        self.read_to()
1345    }
1346
1347    /// Completely fills a vector of bytes and returns it.
1348    /// If the stream is already byte-aligned, it will map
1349    /// to a faster `read_exact` call.  Otherwise it will read
1350    /// bytes individually in 8-bit increments.
1351    ///
1352    /// # Errors
1353    ///
1354    /// Passes along any I/O error from the underlying stream.
1355    #[cfg(feature = "alloc")]
1356    fn read_to_vec(&mut self, bytes: usize) -> io::Result<Vec<u8>> {
1357        read_to_vec(|buf| self.read_bytes(buf), bytes)
1358    }
1359
1360    /// Counts the number of 1 bits in the stream until the next
1361    /// 0 bit and returns the amount read.
1362    /// Because this field is variably-sized and may be large,
1363    /// its output is always a `u32` type.
1364    ///
1365    /// # Errors
1366    ///
1367    /// Passes along any I/O error from the underlying stream.
1368    fn read_unary0(&mut self) -> io::Result<u32> {
1369        let mut unary = 0;
1370        while self.read_bit()? {
1371            unary += 1;
1372        }
1373        Ok(unary)
1374    }
1375
1376    /// Counts the number of 0 bits in the stream until the next
1377    /// 1 bit and returns the amount read.
1378    /// Because this field is variably-sized and may be large,
1379    /// its output is always a `u32` type.
1380    ///
1381    /// # Errors
1382    ///
1383    /// Passes along any I/O error from the underlying stream.
1384    fn read_unary1(&mut self) -> io::Result<u32> {
1385        let mut unary = 0;
1386        while !(self.read_bit()?) {
1387            unary += 1;
1388        }
1389        Ok(unary)
1390    }
1391
1392    /// Parses and returns complex type
1393    fn parse<F: FromBitStream>(&mut self) -> Result<F, F::Error>
1394    where
1395        Self: BitRead,
1396    {
1397        F::from_reader(self)
1398    }
1399
1400    /// Parses and returns complex type with context
1401    fn parse_with<'a, F: FromBitStreamWith<'a>>(
1402        &mut self,
1403        context: &F::Context,
1404    ) -> Result<F, F::Error>
1405    where
1406        Self: BitRead,
1407    {
1408        F::from_reader(self, context)
1409    }
1410
1411    /// Returns true if the stream is aligned at a whole byte.
1412    fn byte_aligned(&self) -> bool;
1413
1414    /// Throws away all unread bit values until the next whole byte.
1415    /// Does nothing if the stream is already aligned.
1416    fn byte_align(&mut self);
1417
1418    /// Given a compiled Huffman tree, reads bits from the stream
1419    /// until the next symbol is encountered.
1420    ///
1421    /// # Errors
1422    ///
1423    /// Passes along any I/O error from the underlying stream.
1424    #[inline]
1425    fn read_huffman<T>(&mut self) -> io::Result<T::Symbol>
1426    where
1427        T: crate::huffman::FromBits,
1428    {
1429        T::from_bits(|| self.read_bit())
1430    }
1431}
1432
1433impl<R: BitRead> BitRead2 for R {
1434    #[inline(always)]
1435    fn read_bit(&mut self) -> io::Result<bool> {
1436        BitRead::read_bit(self)
1437    }
1438
1439    #[inline(always)]
1440    fn read<I>(&mut self, bits: u32) -> io::Result<I>
1441    where
1442        I: Integer + Sized,
1443    {
1444        self.read_var(bits)
1445    }
1446
1447    #[inline(always)]
1448    fn read_in<const BITS: u32, I>(&mut self) -> io::Result<I>
1449    where
1450        I: Integer,
1451    {
1452        BitRead::read::<BITS, I>(self)
1453    }
1454
1455    #[inline(always)]
1456    fn read_signed<S>(&mut self, bits: u32) -> io::Result<S>
1457    where
1458        S: SignedInteger,
1459    {
1460        self.read_signed_var(bits)
1461    }
1462
1463    #[inline(always)]
1464    fn read_signed_in<const BITS: u32, S>(&mut self) -> io::Result<S>
1465    where
1466        S: SignedInteger,
1467    {
1468        BitRead::read_signed::<BITS, S>(self)
1469    }
1470
1471    #[inline(always)]
1472    fn read_to<V>(&mut self) -> io::Result<V>
1473    where
1474        V: Primitive,
1475    {
1476        BitRead::read_to::<V>(self)
1477    }
1478
1479    #[inline(always)]
1480    fn read_as_to<F, V>(&mut self) -> io::Result<V>
1481    where
1482        F: Endianness,
1483        V: Primitive,
1484    {
1485        BitRead::read_as_to::<F, V>(self)
1486    }
1487
1488    #[inline(always)]
1489    fn skip(&mut self, bits: u32) -> io::Result<()> {
1490        BitRead::skip(self, bits)
1491    }
1492
1493    #[inline(always)]
1494    fn read_bytes(&mut self, buf: &mut [u8]) -> io::Result<()> {
1495        BitRead::read_bytes(self, buf)
1496    }
1497
1498    #[inline(always)]
1499    fn read_unary0(&mut self) -> io::Result<u32> {
1500        self.read_unary::<0>()
1501    }
1502
1503    #[inline(always)]
1504    fn read_unary1(&mut self) -> io::Result<u32> {
1505        self.read_unary::<1>()
1506    }
1507
1508    #[inline(always)]
1509    fn byte_aligned(&self) -> bool {
1510        BitRead::byte_aligned(self)
1511    }
1512
1513    #[inline(always)]
1514    fn byte_align(&mut self) {
1515        BitRead::byte_align(self)
1516    }
1517}
1518
1519/// For reading non-aligned bits from a stream of bytes in a given endianness.
1520///
1521/// This will read exactly as many whole bytes needed to return
1522/// the requested number of bits.  It may cache up to a single partial byte
1523/// but no more.
1524#[derive(Clone, Debug)]
1525pub struct BitReader<R, E: Endianness> {
1526    // our underlying reader
1527    reader: R,
1528    // our partial byte
1529    value: u8,
1530    // the number of bits in our partial byte
1531    bits: u32,
1532    // a container for our endiannness
1533    phantom: PhantomData<E>,
1534}
1535
1536impl<R, E: Endianness> BitReader<R, E> {
1537    /// Wraps a BitReader around something that implements `Read`
1538    pub fn new(reader: R) -> BitReader<R, E> {
1539        BitReader {
1540            reader,
1541            value: 0,
1542            bits: 0,
1543            phantom: PhantomData,
1544        }
1545    }
1546
1547    /// Wraps a BitReader around something that implements `Read`
1548    /// with the given endianness.
1549    pub fn endian(reader: R, _endian: E) -> BitReader<R, E> {
1550        BitReader {
1551            reader,
1552            value: 0,
1553            bits: 0,
1554            phantom: PhantomData,
1555        }
1556    }
1557
1558    /// Unwraps internal reader and disposes of BitReader.
1559    ///
1560    /// # Warning
1561    ///
1562    /// Any unread partial bits are discarded.
1563    #[inline]
1564    pub fn into_reader(self) -> R {
1565        self.reader
1566    }
1567}
1568
1569impl<R: io::Read, E: Endianness> BitReader<R, E> {
1570    /// If stream is byte-aligned, provides mutable reference
1571    /// to internal reader.  Otherwise returns `None`
1572    #[inline]
1573    pub fn reader(&mut self) -> Option<&mut R> {
1574        if BitRead::byte_aligned(self) {
1575            Some(&mut self.reader)
1576        } else {
1577            None
1578        }
1579    }
1580
1581    /// Returns byte-aligned mutable reference to internal reader.
1582    ///
1583    /// Bytes aligns stream if it is not already aligned.
1584    #[inline]
1585    pub fn aligned_reader(&mut self) -> &mut R {
1586        BitRead::byte_align(self);
1587        &mut self.reader
1588    }
1589
1590    /// Converts `BitReader` to `ByteReader` in the same endianness.
1591    ///
1592    /// # Warning
1593    ///
1594    /// Any unread partial bits are discarded.
1595    #[inline]
1596    pub fn into_bytereader(self) -> ByteReader<R, E> {
1597        ByteReader::new(self.into_reader())
1598    }
1599
1600    /// If stream is byte-aligned, provides temporary `ByteReader`
1601    /// in the same endianness.  Otherwise returns `None`
1602    ///
1603    /// # Warning
1604    ///
1605    /// Any reader bits left over when `ByteReader` is dropped are lost.
1606    #[inline]
1607    pub fn bytereader(&mut self) -> Option<ByteReader<&mut R, E>> {
1608        self.reader().map(ByteReader::new)
1609    }
1610}
1611
1612impl<R: io::Read, E: Endianness> BitRead for BitReader<R, E> {
1613    #[inline(always)]
1614    fn read_bit(&mut self) -> io::Result<bool> {
1615        let Self {
1616            value,
1617            bits,
1618            reader,
1619            ..
1620        } = self;
1621        E::pop_bit_refill(reader, value, bits)
1622    }
1623
1624    #[inline(always)]
1625    fn read_unsigned_counted<const BITS: u32, U>(&mut self, bits: BitCount<BITS>) -> io::Result<U>
1626    where
1627        U: UnsignedInteger,
1628    {
1629        let Self {
1630            value: queue_value,
1631            bits: queue_bits,
1632            reader,
1633            ..
1634        } = self;
1635        E::read_bits(reader, queue_value, queue_bits, bits)
1636    }
1637
1638    #[inline]
1639    fn read_unsigned<const BITS: u32, U>(&mut self) -> io::Result<U>
1640    where
1641        U: UnsignedInteger,
1642    {
1643        let Self {
1644            value,
1645            bits,
1646            reader,
1647            ..
1648        } = self;
1649        E::read_bits_fixed::<BITS, R, U>(reader, value, bits)
1650    }
1651
1652    #[inline(always)]
1653    fn read_signed_counted<const MAX: u32, S>(
1654        &mut self,
1655        bits: impl TryInto<SignedBitCount<MAX>>,
1656    ) -> io::Result<S>
1657    where
1658        S: SignedInteger,
1659    {
1660        E::read_signed_counted(
1661            self,
1662            bits.try_into().map_err(|_| {
1663                io::Error::new(
1664                    io::ErrorKind::InvalidInput,
1665                    "signed reads need at least 1 bit for sign",
1666                )
1667            })?,
1668        )
1669    }
1670
1671    #[inline]
1672    fn read_signed<const BITS: u32, S>(&mut self) -> io::Result<S>
1673    where
1674        S: SignedInteger,
1675    {
1676        let count = const {
1677            assert!(BITS <= S::BITS_SIZE, "excessive bits for type read");
1678            let count = BitCount::<BITS>::new::<BITS>().signed_count();
1679            assert!(count.is_some(), "signed reads need at least 1 bit for sign");
1680            count.unwrap()
1681        };
1682
1683        E::read_signed_counted(self, count)
1684    }
1685
1686    #[inline]
1687    fn read_to<V>(&mut self) -> io::Result<V>
1688    where
1689        V: Primitive,
1690    {
1691        let mut buffer = V::buffer();
1692        E::read_bytes::<8, _>(
1693            &mut self.reader,
1694            &mut self.value,
1695            self.bits,
1696            buffer.as_mut(),
1697        )?;
1698        Ok(E::bytes_to_primitive(buffer))
1699    }
1700
1701    #[inline]
1702    fn read_as_to<F, V>(&mut self) -> io::Result<V>
1703    where
1704        F: Endianness,
1705        V: Primitive,
1706    {
1707        let mut buffer = V::buffer();
1708        F::read_bytes::<8, _>(
1709            &mut self.reader,
1710            &mut self.value,
1711            self.bits,
1712            buffer.as_mut(),
1713        )?;
1714        Ok(F::bytes_to_primitive(buffer))
1715    }
1716
1717    /// # Examples
1718    /// ```
1719    /// use std::io::Read;
1720    /// use bitstream_io::{BigEndian, BitReader, BitRead};
1721    /// let data = [0b10110111];
1722    /// let mut reader = BitReader::endian(data.as_slice(), BigEndian);
1723    /// assert!(reader.skip(3).is_ok());
1724    /// assert_eq!(reader.read::<5, u8>().unwrap(), 0b10111);
1725    /// ```
1726    ///
1727    /// ```
1728    /// use std::io::Read;
1729    /// use bitstream_io::{LittleEndian, BitReader, BitRead};
1730    /// let data = [0b10110111];
1731    /// let mut reader = BitReader::endian(data.as_slice(), LittleEndian);
1732    /// assert!(reader.skip(3).is_ok());
1733    /// assert_eq!(reader.read::<5, u8>().unwrap(), 0b10110);
1734    /// ```
1735    fn skip(&mut self, mut bits: u32) -> io::Result<()> {
1736        if BitRead::byte_aligned(self) && bits % 8 == 0 {
1737            skip_aligned(self.reader.by_ref(), bits / 8)
1738        } else {
1739            loop {
1740                match bits {
1741                    0 => break Ok(()),
1742                    bits @ 1..64 => break self.read_var(bits).map(|_: u64| ()),
1743                    _ => {
1744                        let _ = BitRead::read::<64, u64>(self)?;
1745                        bits -= 64;
1746                    }
1747                }
1748            }
1749        }
1750    }
1751
1752    /// # Example
1753    /// ```
1754    /// use std::io::Read;
1755    /// use bitstream_io::{BigEndian, BitReader, BitRead};
1756    /// let data = b"foobar";
1757    /// let mut reader = BitReader::endian(data.as_slice(), BigEndian);
1758    /// assert!(reader.skip(24).is_ok());
1759    /// let mut buf = [0;3];
1760    /// assert!(reader.read_bytes(&mut buf).is_ok());
1761    /// assert_eq!(&buf, b"bar");
1762    /// ```
1763    #[inline]
1764    fn read_bytes(&mut self, buf: &mut [u8]) -> io::Result<()> {
1765        E::read_bytes::<1024, _>(&mut self.reader, &mut self.value, self.bits, buf)
1766    }
1767
1768    fn read_unary<const STOP_BIT: u8>(&mut self) -> io::Result<u32> {
1769        let Self {
1770            value,
1771            bits,
1772            reader,
1773            ..
1774        } = self;
1775        E::pop_unary::<STOP_BIT, R>(reader, value, bits)
1776    }
1777
1778    #[inline]
1779    fn byte_aligned(&self) -> bool {
1780        self.bits == 0
1781    }
1782
1783    #[inline]
1784    fn byte_align(&mut self) {
1785        self.value = 0;
1786        self.bits = 0;
1787    }
1788}
1789
1790impl<R, E> BitReader<R, E>
1791where
1792    E: Endianness,
1793    R: io::Read + io::Seek,
1794{
1795    /// # Example
1796    /// ```
1797    /// use std::io::{Read, Cursor, SeekFrom};
1798    /// use bitstream_io::{BigEndian, BitReader, BitRead};
1799    /// let data = [0x00, 0xFF];
1800    /// let mut reader = BitReader::endian(Cursor::new(&data), BigEndian);
1801    /// assert_eq!(reader.position_in_bits().unwrap(), 0);
1802    ///
1803    /// let pos = reader.seek_bits(SeekFrom::Start(5)).unwrap();
1804    /// assert!(pos == 5 && 5 == reader.position_in_bits().unwrap());
1805    ///
1806    /// let pos = reader.seek_bits(SeekFrom::Current(-2)).unwrap();
1807    /// assert!(pos == 3 && 3 == reader.position_in_bits().unwrap());
1808    ///
1809    /// let pos = reader.seek_bits(SeekFrom::End(5)).unwrap();
1810    /// assert!(pos == 11 && 11 == reader.position_in_bits().unwrap());
1811    /// ```
1812    pub fn seek_bits(&mut self, from: io::SeekFrom) -> io::Result<u64> {
1813        match from {
1814            io::SeekFrom::Start(from_start_pos) => {
1815                let (bytes, bits) = (from_start_pos / 8, (from_start_pos % 8) as u32);
1816                BitRead::byte_align(self);
1817                self.reader.seek(io::SeekFrom::Start(bytes))?;
1818                BitRead::skip(self, bits)?;
1819                Ok(from_start_pos)
1820            }
1821            io::SeekFrom::End(from_end_pos) => {
1822                let reader_end = self.reader.seek(io::SeekFrom::End(0))?;
1823                let new_pos = (reader_end * 8) as i64 - from_end_pos;
1824                assert!(new_pos >= 0, "The final position should be greater than 0");
1825                self.seek_bits(io::SeekFrom::Start(new_pos as u64))
1826            }
1827            io::SeekFrom::Current(offset) => {
1828                let new_pos = self.position_in_bits()? as i64 + offset;
1829                assert!(new_pos >= 0, "The final position should be greater than 0");
1830                self.seek_bits(io::SeekFrom::Start(new_pos as u64))
1831            }
1832        }
1833    }
1834
1835    /// # Example
1836    /// ```
1837    /// use std::fs::read;
1838    /// use std::io::{Read, Cursor, SeekFrom};
1839    /// use bitstream_io::{BigEndian, BitReader, BitRead};
1840    /// let data = [0x00, 0xFF];
1841    /// let mut reader = BitReader::endian(Cursor::new(&data), BigEndian);
1842    /// assert_eq!(reader.position_in_bits().unwrap(), 0);
1843    ///
1844    /// let _: i32 = reader.read_signed::<5, _>().unwrap();
1845    /// assert_eq!(reader.position_in_bits().unwrap(), 5);
1846    ///
1847    /// reader.read_bit().unwrap();
1848    /// assert_eq!(reader.position_in_bits().unwrap(), 6);
1849    /// ```
1850    #[inline]
1851    #[allow(clippy::seek_from_current)]
1852    pub fn position_in_bits(&mut self) -> io::Result<u64> {
1853        // no_std_io2 doesn't have `seek_from_current`
1854        let bytes = self.reader.seek(io::SeekFrom::Current(0))?;
1855        Ok(bytes * 8 - (self.bits as u64))
1856    }
1857}
1858
1859fn skip_aligned<R>(reader: R, bytes: u32) -> io::Result<()>
1860where
1861    R: io::Read,
1862{
1863    fn skip_chunks<const SIZE: usize, R>(mut reader: R, mut bytes: usize) -> io::Result<()>
1864    where
1865        R: io::Read,
1866    {
1867        let mut buf = [0; SIZE];
1868        while bytes > 0 {
1869            let to_read = bytes.min(SIZE);
1870            reader.read_exact(&mut buf[0..to_read])?;
1871            bytes -= to_read;
1872        }
1873        Ok(())
1874    }
1875
1876    match bytes {
1877        0..256 => skip_chunks::<8, R>(reader, bytes as usize),
1878        256..1024 => skip_chunks::<256, R>(reader, bytes as usize),
1879        1024..4096 => skip_chunks::<1024, R>(reader, bytes as usize),
1880        _ => skip_chunks::<4096, R>(reader, bytes as usize),
1881    }
1882}
1883
1884/// A trait for anything that can read aligned values from an input stream
1885pub trait ByteRead {
1886    /// Reads whole numeric value from stream
1887    ///
1888    /// # Errors
1889    ///
1890    /// Passes along any I/O error from the underlying stream.
1891    ///
1892    /// # Examples
1893    /// ```
1894    /// use std::io::Read;
1895    /// use bitstream_io::{BigEndian, ByteReader, ByteRead};
1896    /// let data = [0b00000000, 0b11111111];
1897    /// let mut reader = ByteReader::endian(data.as_slice(), BigEndian);
1898    /// assert_eq!(reader.read::<u16>().unwrap(), 0b0000000011111111);
1899    /// ```
1900    ///
1901    /// ```
1902    /// use std::io::Read;
1903    /// use bitstream_io::{LittleEndian, ByteReader, ByteRead};
1904    /// let data = [0b00000000, 0b11111111];
1905    /// let mut reader = ByteReader::endian(data.as_slice(), LittleEndian);
1906    /// assert_eq!(reader.read::<u16>().unwrap(), 0b1111111100000000);
1907    /// ```
1908    fn read<V>(&mut self) -> Result<V, io::Error>
1909    where
1910        V: Primitive;
1911
1912    /// Reads whole numeric value from stream in a potentially different endianness
1913    ///
1914    /// # Errors
1915    ///
1916    /// Passes along any I/O error from the underlying stream.
1917    ///
1918    /// # Examples
1919    /// ```
1920    /// use std::io::Read;
1921    /// use bitstream_io::{BigEndian, ByteReader, ByteRead, LittleEndian};
1922    /// let data = [0b00000000, 0b11111111];
1923    /// let mut reader = ByteReader::endian(data.as_slice(), BigEndian);
1924    /// assert_eq!(reader.read_as::<LittleEndian, u16>().unwrap(), 0b1111111100000000);
1925    /// ```
1926    ///
1927    /// ```
1928    /// use std::io::Read;
1929    /// use bitstream_io::{BigEndian, ByteReader, ByteRead, LittleEndian};
1930    /// let data = [0b00000000, 0b11111111];
1931    /// let mut reader = ByteReader::endian(data.as_slice(), LittleEndian);
1932    /// assert_eq!(reader.read_as::<BigEndian, u16>().unwrap(), 0b0000000011111111);
1933    /// ```
1934    fn read_as<F, V>(&mut self) -> Result<V, io::Error>
1935    where
1936        F: Endianness,
1937        V: Primitive;
1938
1939    /// Completely fills the given buffer with whole bytes.
1940    ///
1941    /// # Errors
1942    ///
1943    /// Passes along any I/O error from the underlying stream.
1944    fn read_bytes(&mut self, buf: &mut [u8]) -> io::Result<()> {
1945        for b in buf.iter_mut() {
1946            *b = self.read()?;
1947        }
1948        Ok(())
1949    }
1950
1951    /// Completely fills a whole buffer with bytes and returns it.
1952    ///
1953    /// # Errors
1954    ///
1955    /// Passes along any I/O error from the underlying stream.
1956    #[inline(always)]
1957    #[deprecated(since = "1.8.0", note = "use read() method instead")]
1958    fn read_to_bytes<const SIZE: usize>(&mut self) -> io::Result<[u8; SIZE]> {
1959        self.read()
1960    }
1961
1962    /// Completely fills a vector of bytes and returns it.
1963    ///
1964    /// # Errors
1965    ///
1966    /// Passes along any I/O error from the underlying stream.
1967    #[cfg(feature = "alloc")]
1968    fn read_to_vec(&mut self, bytes: usize) -> io::Result<Vec<u8>> {
1969        read_to_vec(|buf| self.read_bytes(buf), bytes)
1970    }
1971
1972    /// Skips the given number of bytes in the stream.
1973    ///
1974    /// # Errors
1975    ///
1976    /// Passes along any I/O error from the underlying stream.
1977    fn skip(&mut self, bytes: u32) -> io::Result<()>;
1978
1979    /// Parses and returns complex type
1980    fn parse<F: FromByteStream>(&mut self) -> Result<F, F::Error> {
1981        F::from_reader(self)
1982    }
1983
1984    /// Parses and returns complex type with context
1985    fn parse_with<'a, F: FromByteStreamWith<'a>>(
1986        &mut self,
1987        context: &F::Context,
1988    ) -> Result<F, F::Error> {
1989        F::from_reader(self, context)
1990    }
1991
1992    /// Parses and returns complex type with owned context
1993    fn parse_using<F: FromByteStreamUsing>(&mut self, context: F::Context) -> Result<F, F::Error> {
1994        F::from_reader(self, context)
1995    }
1996
1997    /// Returns mutable reference to underlying reader
1998    fn reader_ref(&mut self) -> &mut dyn io::Read;
1999}
2000
2001/// For reading aligned bytes from a stream of bytes in a given endianness.
2002///
2003/// This only reads aligned values and maintains no internal state.
2004#[derive(Debug)]
2005pub struct ByteReader<R: io::Read, E: Endianness> {
2006    phantom: PhantomData<E>,
2007    reader: R,
2008}
2009
2010impl<R: io::Read, E: Endianness> ByteReader<R, E> {
2011    /// Wraps a ByteReader around something that implements `Read`
2012    pub fn new(reader: R) -> ByteReader<R, E> {
2013        ByteReader {
2014            phantom: PhantomData,
2015            reader,
2016        }
2017    }
2018
2019    /// Wraps a ByteReader around something that implements `Read`
2020    /// with the given endianness.
2021    pub fn endian(reader: R, _endian: E) -> ByteReader<R, E> {
2022        ByteReader {
2023            phantom: PhantomData,
2024            reader,
2025        }
2026    }
2027
2028    /// Unwraps internal reader and disposes of `ByteReader`.
2029    #[inline]
2030    pub fn into_reader(self) -> R {
2031        self.reader
2032    }
2033
2034    /// Provides mutable reference to internal reader
2035    #[inline]
2036    pub fn reader(&mut self) -> &mut R {
2037        &mut self.reader
2038    }
2039
2040    /// Converts `ByteReader` to `BitReader` in the same endianness.
2041    #[inline]
2042    pub fn into_bitreader(self) -> BitReader<R, E> {
2043        BitReader::new(self.into_reader())
2044    }
2045
2046    /// Provides temporary `BitReader` in the same endianness.
2047    ///
2048    /// # Warning
2049    ///
2050    /// Any unread bits left over when `BitReader` is dropped are lost.
2051    #[inline]
2052    pub fn bitreader(&mut self) -> BitReader<&mut R, E> {
2053        BitReader::new(self.reader())
2054    }
2055}
2056
2057impl<R: io::Read, E: Endianness> ByteRead for ByteReader<R, E> {
2058    #[inline]
2059    fn read<V>(&mut self) -> Result<V, io::Error>
2060    where
2061        V: Primitive,
2062    {
2063        let mut buf = V::buffer();
2064        self.read_bytes(buf.as_mut())?;
2065        Ok(E::bytes_to_primitive(buf))
2066    }
2067
2068    #[inline]
2069    fn read_as<F, V>(&mut self) -> Result<V, io::Error>
2070    where
2071        F: Endianness,
2072        V: Primitive,
2073    {
2074        let mut buf = V::buffer();
2075        self.read_bytes(buf.as_mut())?;
2076        Ok(F::bytes_to_primitive(buf))
2077    }
2078
2079    #[inline]
2080    fn read_bytes(&mut self, buf: &mut [u8]) -> io::Result<()> {
2081        self.reader.read_exact(buf)
2082    }
2083
2084    #[inline]
2085    fn skip(&mut self, bytes: u32) -> io::Result<()> {
2086        skip_aligned(&mut self.reader, bytes)
2087    }
2088
2089    #[inline]
2090    fn reader_ref(&mut self) -> &mut dyn io::Read {
2091        &mut self.reader
2092    }
2093}
2094
2095impl<R: io::Read + io::Seek, E: Endianness> io::Seek for ByteReader<R, E> {
2096    fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
2097        self.reader().seek(pos)
2098    }
2099}
2100
2101/// Implemented by complex types that don't require any additional context
2102/// to parse themselves from a reader.  Analogous to [`std::str::FromStr`].
2103///
2104/// # Example
2105/// ```
2106/// use std::io::Read;
2107/// use bitstream_io::{BigEndian, BitRead, BitReader, FromBitStream};
2108///
2109/// #[derive(Debug, PartialEq, Eq)]
2110/// struct BlockHeader {
2111///     last_block: bool,
2112///     block_type: u8,
2113///     block_size: u32,
2114/// }
2115///
2116/// impl FromBitStream for BlockHeader {
2117///     type Error = std::io::Error;
2118///
2119///     fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> std::io::Result<Self> {
2120///         Ok(Self {
2121///             last_block: r.read_bit()?,
2122///             block_type: r.read::<7, _>()?,
2123///             block_size: r.read::<24, _>()?,
2124///         })
2125///     }
2126/// }
2127///
2128/// let mut reader = BitReader::endian(b"\x04\x00\x00\x7A".as_slice(), BigEndian);
2129/// assert_eq!(
2130///     reader.parse::<BlockHeader>().unwrap(),
2131///     BlockHeader { last_block: false, block_type: 4, block_size: 122 }
2132/// );
2133/// ```
2134pub trait FromBitStream {
2135    /// Error generated during parsing, such as `io::Error`
2136    type Error;
2137
2138    /// Parse Self from reader
2139    fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> Result<Self, Self::Error>
2140    where
2141        Self: Sized;
2142}
2143
2144/// Implemented by complex types that require some immutable context
2145/// to parse themselves from a reader.
2146///
2147/// # Example
2148/// ```
2149/// use std::io::Read;
2150/// use bitstream_io::{BigEndian, BitRead, BitReader, FromBitStreamWith};
2151///
2152/// #[derive(Default)]
2153/// struct Streaminfo {
2154///     minimum_block_size: u16,
2155///     maximum_block_size: u16,
2156///     minimum_frame_size: u32,
2157///     maximum_frame_size: u32,
2158///     sample_rate: u32,
2159///     channels: u8,
2160///     bits_per_sample: u8,
2161///     total_samples: u64,
2162///     md5: [u8; 16],
2163/// }
2164///
2165/// #[derive(Debug, PartialEq, Eq)]
2166/// struct FrameHeader {
2167///     variable_block_size: bool,
2168///     block_size: u32,
2169///     sample_rate: u32,
2170///     channel_assignment: u8,
2171///     sample_size: u8,
2172///     frame_number: u64,
2173///     crc8: u8,
2174/// }
2175///
2176/// impl FromBitStreamWith<'_> for FrameHeader {
2177///     type Context = Streaminfo;
2178///
2179///     type Error = FrameHeaderError;
2180///
2181///     fn from_reader<R: BitRead + ?Sized>(
2182///         r: &mut R,
2183///         streaminfo: &Streaminfo,
2184///     ) -> Result<Self, Self::Error> {
2185///         if r.read::<14, u16>()? != 0b11111111111110 {
2186///             return Err(FrameHeaderError::InvalidSync);
2187///         }
2188///
2189///         if r.read_bit()? != false {
2190///             return Err(FrameHeaderError::InvalidReservedBit);
2191///         }
2192///
2193///         let variable_block_size = r.read_bit()?;
2194///
2195///         let block_size_bits = r.read::<4, u8>()?;
2196///
2197///         let sample_rate_bits = r.read::<4, u8>()?;
2198///
2199///         let channel_assignment = r.read::<4, u8>()?;
2200///
2201///         let sample_size = match r.read::<3, u8>()? {
2202///             0b000 => streaminfo.bits_per_sample,
2203///             0b001 => 8,
2204///             0b010 => 12,
2205///             0b011 => return Err(FrameHeaderError::InvalidSampleSize),
2206///             0b100 => 16,
2207///             0b101 => 20,
2208///             0b110 => 24,
2209///             0b111 => 32,
2210///             _ => unreachable!(),
2211///         };
2212///
2213///         if r.read_bit()? != false {
2214///             return Err(FrameHeaderError::InvalidReservedBit);
2215///         }
2216///
2217///         let frame_number = read_utf8(r)?;
2218///
2219///         Ok(FrameHeader {
2220///             variable_block_size,
2221///             block_size: match block_size_bits {
2222///                 0b0000 => return Err(FrameHeaderError::InvalidBlockSize),
2223///                 0b0001 => 192,
2224///                 n @ 0b010..=0b0101 => 576 * (1 << (n - 2)),
2225///                 0b0110 => r.read::<8, u32>()? + 1,
2226///                 0b0111 => r.read::<16, u32>()? + 1,
2227///                 n @ 0b1000..=0b1111 => 256 * (1 << (n - 8)),
2228///                 _ => unreachable!(),
2229///             },
2230///             sample_rate: match sample_rate_bits {
2231///                 0b0000 => streaminfo.sample_rate,
2232///                 0b0001 => 88200,
2233///                 0b0010 => 176400,
2234///                 0b0011 => 192000,
2235///                 0b0100 => 8000,
2236///                 0b0101 => 16000,
2237///                 0b0110 => 22050,
2238///                 0b0111 => 24000,
2239///                 0b1000 => 32000,
2240///                 0b1001 => 44100,
2241///                 0b1010 => 48000,
2242///                 0b1011 => 96000,
2243///                 0b1100 => r.read::<8, u32>()? * 1000,
2244///                 0b1101 => r.read::<16, u32>()?,
2245///                 0b1110 => r.read::<16, u32>()? * 10,
2246///                 0b1111 => return Err(FrameHeaderError::InvalidSampleRate),
2247///                 _ => unreachable!(),
2248///             },
2249///             channel_assignment,
2250///             sample_size,
2251///             frame_number,
2252///             crc8: r.read::<8, _>()?
2253///         })
2254///     }
2255/// }
2256///
2257/// #[derive(Debug)]
2258/// enum FrameHeaderError {
2259///     Io(std::io::Error),
2260///     InvalidSync,
2261///     InvalidReservedBit,
2262///     InvalidSampleSize,
2263///     InvalidBlockSize,
2264///     InvalidSampleRate,
2265/// }
2266///
2267/// impl From<std::io::Error> for FrameHeaderError {
2268///     fn from(err: std::io::Error) -> Self {
2269///         Self::Io(err)
2270///     }
2271/// }
2272///
2273/// fn read_utf8<R: BitRead + ?Sized>(r: &mut R) -> Result<u64, std::io::Error> {
2274///     r.read::<8, _>()  // left unimplimented in this example
2275/// }
2276///
2277/// let mut reader = BitReader::endian(b"\xFF\xF8\xC9\x18\x00\xC2".as_slice(), BigEndian);
2278/// assert_eq!(
2279///     reader.parse_with::<FrameHeader>(&Streaminfo::default()).unwrap(),
2280///     FrameHeader {
2281///         variable_block_size: false,
2282///         block_size: 4096,
2283///         sample_rate: 44100,
2284///         channel_assignment: 1,
2285///         sample_size: 16,
2286///         frame_number: 0,
2287///         crc8: 0xC2,
2288///     }
2289/// );
2290/// ```
2291///
2292/// # Example with lifetime-contrained `Context`
2293///
2294/// In some cases, the `Context` can depend on a reference to another `struct`.
2295///
2296/// ```
2297/// use std::io::Read;
2298/// use bitstream_io::{BigEndian, BitRead, BitReader, FromBitStreamWith};
2299///
2300/// #[derive(Default)]
2301/// struct ModeParameters {
2302///     size_len: u8,
2303///     index_len: u8,
2304///     index_delta_len: u8,
2305///     // ...
2306/// }
2307///
2308/// struct AuHeaderParseContext<'a> {
2309///     params: &'a ModeParameters,
2310///     base_index: Option<u32>,
2311/// }
2312///
2313/// #[derive(Debug, PartialEq, Eq)]
2314/// struct AuHeader {
2315///     size: u32,
2316///     index: u32,
2317///     // ...
2318/// }
2319///
2320/// impl<'a> FromBitStreamWith<'a> for AuHeader {
2321///     type Context = AuHeaderParseContext<'a>;
2322///
2323///     type Error = AuHeaderError;
2324///
2325///     fn from_reader<R: BitRead + ?Sized>(
2326///         r: &mut R,
2327///         ctx: &AuHeaderParseContext<'a>,
2328///     ) -> Result<Self, Self::Error> {
2329///         let size = r.read_var::<u32>(ctx.params.size_len as u32)?;
2330///         let index = match ctx.base_index {
2331///             None => r.read_var::<u32>(ctx.params.index_len as u32)?,
2332///             Some(base_index) => {
2333///                 base_index
2334///                 + 1
2335///                 + r.read_var::<u32>(ctx.params.index_delta_len as u32)?
2336///             }
2337///         };
2338///
2339///         Ok(AuHeader {
2340///             size,
2341///             index,
2342///             // ...
2343///         })
2344///     }
2345/// }
2346///
2347/// #[derive(Debug)]
2348/// enum AuHeaderError {
2349///     Io(std::io::Error),
2350/// }
2351///
2352/// impl From<std::io::Error> for AuHeaderError {
2353///     fn from(err: std::io::Error) -> Self {
2354///         Self::Io(err)
2355///     }
2356/// }
2357///
2358/// let mut reader = BitReader::endian(b"\xFF\xEA\xFF\x10".as_slice(), BigEndian);
2359///
2360/// let mode_params = ModeParameters {
2361///     size_len: 10,
2362///     index_len: 6,
2363///     index_delta_len: 2,
2364///     // ...
2365/// };
2366///
2367/// let mut ctx = AuHeaderParseContext {
2368///     params: &mode_params,
2369///     base_index: None,
2370/// };
2371///
2372/// let header1 = reader.parse_with::<AuHeader>(&ctx).unwrap();
2373/// assert_eq!(
2374///     header1,
2375///     AuHeader {
2376///         size: 1023,
2377///         index: 42,
2378///     }
2379/// );
2380///
2381/// ctx.base_index = Some(header1.index);
2382///
2383/// assert_eq!(
2384///     reader.parse_with::<AuHeader>(&ctx).unwrap(),
2385///     AuHeader {
2386///         size: 1020,
2387///         index: 44,
2388///     }
2389/// );
2390/// ```
2391pub trait FromBitStreamWith<'a> {
2392    /// Some context to use when parsing
2393    type Context: 'a;
2394
2395    /// Error generated during parsing, such as `io::Error`
2396    type Error;
2397
2398    /// Parse Self from reader with the given context
2399    fn from_reader<R: BitRead + ?Sized>(
2400        r: &mut R,
2401        context: &Self::Context,
2402    ) -> Result<Self, Self::Error>
2403    where
2404        Self: Sized;
2405}
2406
2407/// Implemented by complex types that consume some immutable context
2408/// to parse themselves from a reader.
2409///
2410/// Like [`FromBitStreamWith`], but consumes its context
2411/// rather than taking a shared reference to it.
2412pub trait FromBitStreamUsing {
2413    /// Some context to consume when parsing
2414    type Context;
2415
2416    /// Error generated during parsing, such as `io::Error`
2417    type Error;
2418
2419    /// Parse Self from reader with the given context
2420    fn from_reader<R: BitRead + ?Sized>(
2421        r: &mut R,
2422        context: Self::Context,
2423    ) -> Result<Self, Self::Error>
2424    where
2425        Self: Sized;
2426}
2427
2428/// Implemented by complex types that don't require any additional context
2429/// to parse themselves from a reader.  Analagous to `FromStr`.
2430pub trait FromByteStream {
2431    /// Error generated during parsing, such as `io::Error`
2432    type Error;
2433
2434    /// Parse Self from reader
2435    fn from_reader<R: ByteRead + ?Sized>(r: &mut R) -> Result<Self, Self::Error>
2436    where
2437        Self: Sized;
2438}
2439
2440/// Implemented by complex types that require some additional context
2441/// to parse themselves from a reader.  Analagous to `FromStr`.
2442pub trait FromByteStreamWith<'a> {
2443    /// Some context to use when parsing
2444    type Context: 'a;
2445
2446    /// Error generated during parsing, such as `io::Error`
2447    type Error;
2448
2449    /// Parse Self from reader
2450    fn from_reader<R: ByteRead + ?Sized>(
2451        r: &mut R,
2452        context: &Self::Context,
2453    ) -> Result<Self, Self::Error>
2454    where
2455        Self: Sized;
2456}
2457
2458/// Implemented by complex types that consume some additional context
2459/// to parse themselves from a reader.
2460///
2461/// Like [`FromByteStreamWith`], but consumes the context.
2462pub trait FromByteStreamUsing {
2463    /// Some context to use when parsing
2464    type Context;
2465
2466    /// Error generated during parsing, such as `io::Error`
2467    type Error;
2468
2469    /// Parse Self from reader
2470    fn from_reader<R: ByteRead + ?Sized>(
2471        r: &mut R,
2472        context: Self::Context,
2473    ) -> Result<Self, Self::Error>
2474    where
2475        Self: Sized;
2476}
2477
2478#[cfg(feature = "alloc")]
2479fn read_to_vec(
2480    mut read: impl FnMut(&mut [u8]) -> io::Result<()>,
2481    bytes: usize,
2482) -> io::Result<Vec<u8>> {
2483    const MAX_CHUNK: usize = 4096;
2484
2485    match bytes {
2486        0 => Ok(Vec::new()),
2487        bytes if bytes <= MAX_CHUNK => {
2488            let mut buf = vec![0; bytes];
2489            read(&mut buf)?;
2490            Ok(buf)
2491        }
2492        mut bytes => {
2493            let mut whole = Vec::with_capacity(MAX_CHUNK);
2494            let mut chunk: [u8; MAX_CHUNK] = [0; MAX_CHUNK];
2495            while bytes > 0 {
2496                let chunk_size = bytes.min(MAX_CHUNK);
2497                let chunk = &mut chunk[0..chunk_size];
2498                read(chunk)?;
2499                whole.extend_from_slice(chunk);
2500                bytes -= chunk_size;
2501            }
2502            Ok(whole)
2503        }
2504    }
2505}