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