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, Endianness, Integer, PhantomData, Primitive, SignedBitCount, SignedInteger,
22    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    /// Parses and returns complex type
759    fn parse<F: FromBitStream>(&mut self) -> Result<F, F::Error> {
760        F::from_reader(self)
761    }
762
763    /// Parses and returns complex type with context
764    fn parse_with<'a, F: FromBitStreamWith<'a>>(
765        &mut self,
766        context: &F::Context,
767    ) -> Result<F, F::Error> {
768        F::from_reader(self, context)
769    }
770
771    /// Returns true if the stream is aligned at a whole byte.
772    ///
773    /// # Example
774    /// ```
775    /// use std::io::Read;
776    /// use bitstream_io::{BigEndian, BitReader, BitRead};
777    /// let data = [0];
778    /// let mut reader = BitReader::endian(data.as_slice(), BigEndian);
779    /// assert_eq!(reader.byte_aligned(), true);
780    /// assert!(reader.skip(1).is_ok());
781    /// assert_eq!(reader.byte_aligned(), false);
782    /// assert!(reader.skip(7).is_ok());
783    /// assert_eq!(reader.byte_aligned(), true);
784    /// ```
785    fn byte_aligned(&self) -> bool;
786
787    /// Throws away all unread bit values until the next whole byte.
788    /// Does nothing if the stream is already aligned.
789    ///
790    /// # Example
791    /// ```
792    /// use bitstream_io::{BigEndian, BitReader, BitRead};
793    /// let data: &[u8] = &[0x00, 0xFF];
794    /// let mut reader = BitReader::endian(data, BigEndian);
795    /// assert_eq!(reader.read::<4, u8>().unwrap(), 0);
796    /// reader.byte_align();
797    /// assert_eq!(reader.read::<8, u8>().unwrap(), 0xFF);
798    /// ```
799    fn byte_align(&mut self);
800
801    /// Given a compiled Huffman tree, reads bits from the stream
802    /// until the next symbol is encountered.
803    ///
804    /// # Errors
805    ///
806    /// Passes along any I/O error from the underlying stream.
807    ///
808    /// # Example
809    ///
810    /// ```
811    /// use bitstream_io::{BitReader, BitRead, BigEndian, define_huffman_tree, huffman::FromBits};
812    ///
813    /// define_huffman_tree!(TreeName : char = ['a', ['b', ['c', 'd']]]);
814    /// // 'a' is 0
815    /// // 'b' is 1 -> 0
816    /// // 'c' is 1 -> 1 -> 0
817    /// // 'd' is 1 -> 1 -> 1
818    ///
819    /// let data: &[u8] = &[0b0_10_110_11, 0b1_0000000];
820    /// let mut r = BitReader::endian(data, BigEndian);
821    /// assert_eq!(r.read_huffman::<TreeName>().unwrap(), 'a');
822    /// assert_eq!(r.read_huffman::<TreeName>().unwrap(), 'b');
823    /// assert_eq!(r.read_huffman::<TreeName>().unwrap(), 'c');
824    /// assert_eq!(r.read_huffman::<TreeName>().unwrap(), 'd');
825    /// ```
826    #[inline]
827    fn read_huffman<T>(&mut self) -> io::Result<T::Symbol>
828    where
829        T: crate::huffman::FromBits,
830    {
831        T::from_bits(|| self.read_bit())
832    }
833
834    /// Creates a "by reference" adaptor for this `BitRead`
835    ///
836    /// The returned adapter also implements `BitRead`
837    /// and will borrow the current reader.
838    ///
839    /// # Example
840    /// ```
841    /// use bitstream_io::{BitReader, BitRead, BigEndian};
842    ///
843    /// fn parse<R: BitRead>(r: R) {
844    ///     // perform some parsing
845    /// }
846    ///
847    /// let data: &[u8] = &[0];
848    /// let mut reader = BitReader::endian(data, BigEndian);
849    /// // performing parsing by reference
850    /// parse(reader.by_ref());
851    /// // original owned reader still available
852    /// assert_eq!(reader.read::<8, u8>().unwrap(), 0);
853    /// ```
854    #[inline]
855    fn by_ref(&mut self) -> &mut Self {
856        self
857    }
858}
859
860impl<R: BitRead + ?Sized> BitRead for &mut R {
861    #[inline]
862    fn read_bit(&mut self) -> io::Result<bool> {
863        (**self).read_bit()
864    }
865
866    #[inline]
867    fn read<const BITS: u32, I>(&mut self) -> io::Result<I>
868    where
869        I: Integer,
870    {
871        (**self).read::<BITS, I>()
872    }
873
874    #[inline]
875    fn read_var<I>(&mut self, bits: u32) -> io::Result<I>
876    where
877        I: Integer + Sized,
878    {
879        (**self).read_var(bits)
880    }
881
882    #[inline]
883    fn read_count<const MAX: u32>(&mut self) -> io::Result<BitCount<MAX>> {
884        (**self).read_count::<MAX>()
885    }
886
887    #[inline]
888    fn read_counted<const MAX: u32, I>(&mut self, bits: BitCount<MAX>) -> io::Result<I>
889    where
890        I: Integer + Sized,
891    {
892        (**self).read_counted::<MAX, I>(bits)
893    }
894
895    #[inline]
896    fn read_unsigned<const BITS: u32, U>(&mut self) -> io::Result<U>
897    where
898        U: UnsignedInteger,
899    {
900        (**self).read_unsigned::<BITS, U>()
901    }
902
903    #[inline]
904    fn read_unsigned_var<U>(&mut self, bits: u32) -> io::Result<U>
905    where
906        U: UnsignedInteger,
907    {
908        (**self).read_unsigned_var(bits)
909    }
910
911    #[inline]
912    fn read_unsigned_counted<const MAX: u32, U>(&mut self, bits: BitCount<MAX>) -> io::Result<U>
913    where
914        U: UnsignedInteger,
915    {
916        (**self).read_unsigned_counted::<MAX, U>(bits)
917    }
918
919    #[inline]
920    fn read_signed<const BITS: u32, S>(&mut self) -> io::Result<S>
921    where
922        S: SignedInteger,
923    {
924        (**self).read_signed::<BITS, S>()
925    }
926
927    #[inline]
928    fn read_signed_var<S>(&mut self, bits: u32) -> io::Result<S>
929    where
930        S: SignedInteger,
931    {
932        (**self).read_signed_var(bits)
933    }
934
935    #[inline]
936    fn read_signed_counted<const MAX: u32, S>(
937        &mut self,
938        bits: impl TryInto<SignedBitCount<MAX>>,
939    ) -> io::Result<S>
940    where
941        S: SignedInteger,
942    {
943        (**self).read_signed_counted::<MAX, S>(bits)
944    }
945
946    #[inline]
947    fn read_to<V>(&mut self) -> io::Result<V>
948    where
949        V: Primitive,
950    {
951        (**self).read_to::<V>()
952    }
953
954    #[inline]
955    fn read_as_to<F, V>(&mut self) -> io::Result<V>
956    where
957        F: Endianness,
958        V: Primitive,
959    {
960        (**self).read_as_to::<F, V>()
961    }
962
963    #[inline]
964    fn skip(&mut self, bits: u32) -> io::Result<()> {
965        (**self).skip(bits)
966    }
967
968    #[inline]
969    fn read_bytes(&mut self, buf: &mut [u8]) -> io::Result<()> {
970        (**self).read_bytes(buf)
971    }
972
973    #[inline]
974    fn read_to_vec(&mut self, bytes: usize) -> io::Result<Vec<u8>> {
975        (**self).read_to_vec(bytes)
976    }
977
978    #[inline]
979    fn read_unary<const STOP_BIT: u8>(&mut self) -> io::Result<u32> {
980        (**self).read_unary::<STOP_BIT>()
981    }
982
983    #[inline]
984    fn parse<F: FromBitStream>(&mut self) -> Result<F, F::Error> {
985        (**self).parse::<F>()
986    }
987
988    #[inline]
989    fn parse_with<'a, F: FromBitStreamWith<'a>>(
990        &mut self,
991        context: &F::Context,
992    ) -> Result<F, F::Error> {
993        (**self).parse_with::<F>(context)
994    }
995
996    #[inline]
997    fn byte_aligned(&self) -> bool {
998        (**self).byte_aligned()
999    }
1000
1001    #[inline]
1002    fn byte_align(&mut self) {
1003        (**self).byte_align()
1004    }
1005
1006    #[inline]
1007    fn read_huffman<T>(&mut self) -> io::Result<T::Symbol>
1008    where
1009        T: crate::huffman::FromBits,
1010    {
1011        (**self).read_huffman::<T>()
1012    }
1013}
1014
1015/// A compatibility trait for older code implementing [`BitRead`]
1016///
1017/// This is a trait largely compatible with older code
1018/// from the 2.X.X version,
1019/// which one can use with a named import as needed.
1020///
1021/// New code should prefer the regular [`BitRead`] trait.
1022///
1023/// # Example
1024/// ```
1025/// use bitstream_io::BitRead2 as BitRead;
1026/// use bitstream_io::{BitReader, BigEndian};
1027/// let byte = &[0b1111_0000];
1028/// let mut reader = BitReader::endian(byte.as_slice(), BigEndian);
1029/// assert_eq!(reader.read::<u8>(4).unwrap(), 0b1111);
1030/// assert_eq!(reader.read_in::<4, u8>().unwrap(), 0b0000);
1031/// ```
1032pub trait BitRead2 {
1033    /// Reads a single bit from the stream.
1034    /// `true` indicates 1, `false` indicates 0
1035    ///
1036    /// # Errors
1037    ///
1038    /// Passes along any I/O error from the underlying stream.
1039    fn read_bit(&mut self) -> io::Result<bool>;
1040
1041    /// Reads an unsigned value from the stream with
1042    /// the given number of bits.
1043    ///
1044    /// # Errors
1045    ///
1046    /// Passes along any I/O error from the underlying stream.
1047    /// Also returns an error if the output type is too small
1048    /// to hold the requested number of bits.
1049    fn read<I>(&mut self, bits: u32) -> io::Result<I>
1050    where
1051        I: Integer + Sized;
1052
1053    /// Reads an unsigned value from the stream with
1054    /// the given constant number of bits.
1055    ///
1056    /// # Errors
1057    ///
1058    /// Passes along any I/O error from the underlying stream.
1059    /// A compile-time error occurs if the given number of bits
1060    /// is larger than the output type.
1061    fn read_in<const BITS: u32, I>(&mut self) -> io::Result<I>
1062    where
1063        I: Integer,
1064    {
1065        self.read(BITS)
1066    }
1067
1068    /// Reads a twos-complement signed value from the stream with
1069    /// the given number of bits.
1070    ///
1071    /// # Errors
1072    ///
1073    /// Passes along any I/O error from the underlying stream.
1074    /// Returns an error if the number of bits is 0,
1075    /// since one bit is always needed for the sign.
1076    /// Also returns an error if the output type is too small
1077    /// to hold the requested number of bits.
1078    fn read_signed<S>(&mut self, bits: u32) -> io::Result<S>
1079    where
1080        S: SignedInteger;
1081
1082    /// Reads a twos-complement signed value from the stream with
1083    /// the given constant number of bits.
1084    ///
1085    /// # Errors
1086    ///
1087    /// Passes along any I/O error from the underlying stream.
1088    /// A compile-time error occurs if the number of bits is 0,
1089    /// since one bit is always needed for the sign.
1090    /// A compile-time error occurs if the given number of bits
1091    /// is larger than the output type.
1092    fn read_signed_in<const BITS: u32, S>(&mut self) -> io::Result<S>
1093    where
1094        S: SignedInteger,
1095    {
1096        self.read_signed(BITS)
1097    }
1098
1099    /// Reads whole value from the stream whose size in bits is equal
1100    /// to its type's size.
1101    ///
1102    /// # Errors
1103    ///
1104    /// Passes along any I/O error from the underlying stream.
1105    fn read_to<V>(&mut self) -> io::Result<V>
1106    where
1107        V: Primitive;
1108
1109    /// Reads whole value from the stream whose size in bits is equal
1110    /// to its type's size in an endianness that may be different
1111    /// from the stream's endianness.
1112    ///
1113    /// # Errors
1114    ///
1115    /// Passes along any I/O error from the underlying stream.
1116    fn read_as_to<F, V>(&mut self) -> io::Result<V>
1117    where
1118        F: Endianness,
1119        V: Primitive;
1120
1121    /// Skips the given number of bits in the stream.
1122    /// Since this method does not need an accumulator,
1123    /// it may be slightly faster than reading to an empty variable.
1124    /// In addition, since there is no accumulator,
1125    /// there is no upper limit on the number of bits
1126    /// which may be skipped.
1127    /// These bits are still read from the stream, however,
1128    /// and are never skipped via a `seek` method.
1129    ///
1130    /// # Errors
1131    ///
1132    /// Passes along any I/O error from the underlying stream.
1133    fn skip(&mut self, bits: u32) -> io::Result<()>;
1134
1135    /// Completely fills the given buffer with whole bytes.
1136    /// If the stream is already byte-aligned, it will map
1137    /// to a faster `read_exact` call.  Otherwise it will read
1138    /// bytes individually in 8-bit increments.
1139    ///
1140    /// # Errors
1141    ///
1142    /// Passes along any I/O error from the underlying stream.
1143    fn read_bytes(&mut self, buf: &mut [u8]) -> io::Result<()> {
1144        for b in buf.iter_mut() {
1145            *b = self.read_in::<8, _>()?;
1146        }
1147        Ok(())
1148    }
1149
1150    /// Completely fills a whole buffer with bytes and returns it.
1151    /// If the stream is already byte-aligned, it will map
1152    /// to a faster `read_exact` call.  Otherwise it will read
1153    /// bytes individually in 8-bit increments.
1154    ///
1155    /// # Errors
1156    ///
1157    /// Passes along any I/O error from the underlying stream.
1158    #[inline(always)]
1159    #[deprecated(since = "1.8.0", note = "use read_to() method instead")]
1160    fn read_to_bytes<const SIZE: usize>(&mut self) -> io::Result<[u8; SIZE]> {
1161        self.read_to()
1162    }
1163
1164    /// Completely fills a vector of bytes and returns it.
1165    /// If the stream is already byte-aligned, it will map
1166    /// to a faster `read_exact` call.  Otherwise it will read
1167    /// bytes individually in 8-bit increments.
1168    ///
1169    /// # Errors
1170    ///
1171    /// Passes along any I/O error from the underlying stream.
1172    fn read_to_vec(&mut self, bytes: usize) -> io::Result<Vec<u8>> {
1173        read_to_vec(|buf| self.read_bytes(buf), bytes)
1174    }
1175
1176    /// Counts the number of 1 bits in the stream until the next
1177    /// 0 bit and returns the amount read.
1178    /// Because this field is variably-sized and may be large,
1179    /// its output is always a `u32` type.
1180    ///
1181    /// # Errors
1182    ///
1183    /// Passes along any I/O error from the underlying stream.
1184    fn read_unary0(&mut self) -> io::Result<u32> {
1185        let mut unary = 0;
1186        while self.read_bit()? {
1187            unary += 1;
1188        }
1189        Ok(unary)
1190    }
1191
1192    /// Counts the number of 0 bits in the stream until the next
1193    /// 1 bit and returns the amount read.
1194    /// Because this field is variably-sized and may be large,
1195    /// its output is always a `u32` type.
1196    ///
1197    /// # Errors
1198    ///
1199    /// Passes along any I/O error from the underlying stream.
1200    fn read_unary1(&mut self) -> io::Result<u32> {
1201        let mut unary = 0;
1202        while !(self.read_bit()?) {
1203            unary += 1;
1204        }
1205        Ok(unary)
1206    }
1207
1208    /// Parses and returns complex type
1209    fn parse<F: FromBitStream>(&mut self) -> Result<F, F::Error>
1210    where
1211        Self: BitRead,
1212    {
1213        F::from_reader(self)
1214    }
1215
1216    /// Parses and returns complex type with context
1217    fn parse_with<'a, F: FromBitStreamWith<'a>>(
1218        &mut self,
1219        context: &F::Context,
1220    ) -> Result<F, F::Error>
1221    where
1222        Self: BitRead,
1223    {
1224        F::from_reader(self, context)
1225    }
1226
1227    /// Returns true if the stream is aligned at a whole byte.
1228    fn byte_aligned(&self) -> bool;
1229
1230    /// Throws away all unread bit values until the next whole byte.
1231    /// Does nothing if the stream is already aligned.
1232    fn byte_align(&mut self);
1233
1234    /// Given a compiled Huffman tree, reads bits from the stream
1235    /// until the next symbol is encountered.
1236    ///
1237    /// # Errors
1238    ///
1239    /// Passes along any I/O error from the underlying stream.
1240    #[inline]
1241    fn read_huffman<T>(&mut self) -> io::Result<T::Symbol>
1242    where
1243        T: crate::huffman::FromBits,
1244    {
1245        T::from_bits(|| self.read_bit())
1246    }
1247}
1248
1249impl<R: BitRead> BitRead2 for R {
1250    #[inline(always)]
1251    fn read_bit(&mut self) -> io::Result<bool> {
1252        BitRead::read_bit(self)
1253    }
1254
1255    #[inline(always)]
1256    fn read<I>(&mut self, bits: u32) -> io::Result<I>
1257    where
1258        I: Integer + Sized,
1259    {
1260        self.read_var(bits)
1261    }
1262
1263    #[inline(always)]
1264    fn read_in<const BITS: u32, I>(&mut self) -> io::Result<I>
1265    where
1266        I: Integer,
1267    {
1268        BitRead::read::<BITS, I>(self)
1269    }
1270
1271    #[inline(always)]
1272    fn read_signed<S>(&mut self, bits: u32) -> io::Result<S>
1273    where
1274        S: SignedInteger,
1275    {
1276        self.read_signed_var(bits)
1277    }
1278
1279    #[inline(always)]
1280    fn read_signed_in<const BITS: u32, S>(&mut self) -> io::Result<S>
1281    where
1282        S: SignedInteger,
1283    {
1284        BitRead::read_signed::<BITS, S>(self)
1285    }
1286
1287    #[inline(always)]
1288    fn read_to<V>(&mut self) -> io::Result<V>
1289    where
1290        V: Primitive,
1291    {
1292        BitRead::read_to::<V>(self)
1293    }
1294
1295    #[inline(always)]
1296    fn read_as_to<F, V>(&mut self) -> io::Result<V>
1297    where
1298        F: Endianness,
1299        V: Primitive,
1300    {
1301        BitRead::read_as_to::<F, V>(self)
1302    }
1303
1304    #[inline(always)]
1305    fn skip(&mut self, bits: u32) -> io::Result<()> {
1306        BitRead::skip(self, bits)
1307    }
1308
1309    #[inline(always)]
1310    fn read_bytes(&mut self, buf: &mut [u8]) -> io::Result<()> {
1311        BitRead::read_bytes(self, buf)
1312    }
1313
1314    #[inline(always)]
1315    fn read_unary0(&mut self) -> io::Result<u32> {
1316        self.read_unary::<0>()
1317    }
1318
1319    #[inline(always)]
1320    fn read_unary1(&mut self) -> io::Result<u32> {
1321        self.read_unary::<1>()
1322    }
1323
1324    #[inline(always)]
1325    fn byte_aligned(&self) -> bool {
1326        BitRead::byte_aligned(self)
1327    }
1328
1329    #[inline(always)]
1330    fn byte_align(&mut self) {
1331        BitRead::byte_align(self)
1332    }
1333}
1334
1335/// For reading non-aligned bits from a stream of bytes in a given endianness.
1336///
1337/// This will read exactly as many whole bytes needed to return
1338/// the requested number of bits.  It may cache up to a single partial byte
1339/// but no more.
1340#[derive(Clone, Debug)]
1341pub struct BitReader<R, E: Endianness> {
1342    // our underlying reader
1343    reader: R,
1344    // our partial byte
1345    value: u8,
1346    // the number of bits in our partial byte
1347    bits: u32,
1348    // a container for our endiannness
1349    phantom: PhantomData<E>,
1350}
1351
1352impl<R, E: Endianness> BitReader<R, E> {
1353    /// Wraps a BitReader around something that implements `Read`
1354    pub fn new(reader: R) -> BitReader<R, E> {
1355        BitReader {
1356            reader,
1357            value: 0,
1358            bits: 0,
1359            phantom: PhantomData,
1360        }
1361    }
1362
1363    /// Wraps a BitReader around something that implements `Read`
1364    /// with the given endianness.
1365    pub fn endian(reader: R, _endian: E) -> BitReader<R, E> {
1366        BitReader {
1367            reader,
1368            value: 0,
1369            bits: 0,
1370            phantom: PhantomData,
1371        }
1372    }
1373
1374    /// Unwraps internal reader and disposes of BitReader.
1375    ///
1376    /// # Warning
1377    ///
1378    /// Any unread partial bits are discarded.
1379    #[inline]
1380    pub fn into_reader(self) -> R {
1381        self.reader
1382    }
1383}
1384
1385impl<R: io::Read, E: Endianness> BitReader<R, E> {
1386    /// If stream is byte-aligned, provides mutable reference
1387    /// to internal reader.  Otherwise returns `None`
1388    #[inline]
1389    pub fn reader(&mut self) -> Option<&mut R> {
1390        if BitRead::byte_aligned(self) {
1391            Some(&mut self.reader)
1392        } else {
1393            None
1394        }
1395    }
1396
1397    /// Returns byte-aligned mutable reference to internal reader.
1398    ///
1399    /// Bytes aligns stream if it is not already aligned.
1400    #[inline]
1401    pub fn aligned_reader(&mut self) -> &mut R {
1402        BitRead::byte_align(self);
1403        &mut self.reader
1404    }
1405
1406    /// Converts `BitReader` to `ByteReader` in the same endianness.
1407    ///
1408    /// # Warning
1409    ///
1410    /// Any unread partial bits are discarded.
1411    #[inline]
1412    pub fn into_bytereader(self) -> ByteReader<R, E> {
1413        ByteReader::new(self.into_reader())
1414    }
1415
1416    /// If stream is byte-aligned, provides temporary `ByteReader`
1417    /// in the same endianness.  Otherwise returns `None`
1418    ///
1419    /// # Warning
1420    ///
1421    /// Any reader bits left over when `ByteReader` is dropped are lost.
1422    #[inline]
1423    pub fn bytereader(&mut self) -> Option<ByteReader<&mut R, E>> {
1424        self.reader().map(ByteReader::new)
1425    }
1426}
1427
1428impl<R: io::Read, E: Endianness> BitRead for BitReader<R, E> {
1429    #[inline(always)]
1430    fn read_bit(&mut self) -> io::Result<bool> {
1431        let Self {
1432            value,
1433            bits,
1434            reader,
1435            ..
1436        } = self;
1437        E::pop_bit_refill(reader, value, bits)
1438    }
1439
1440    #[inline(always)]
1441    fn read_unsigned_counted<const BITS: u32, U>(&mut self, bits: BitCount<BITS>) -> io::Result<U>
1442    where
1443        U: UnsignedInteger,
1444    {
1445        let Self {
1446            value: queue_value,
1447            bits: queue_bits,
1448            reader,
1449            ..
1450        } = self;
1451        E::read_bits(reader, queue_value, queue_bits, bits)
1452    }
1453
1454    #[inline]
1455    fn read_unsigned<const BITS: u32, U>(&mut self) -> io::Result<U>
1456    where
1457        U: UnsignedInteger,
1458    {
1459        let Self {
1460            value,
1461            bits,
1462            reader,
1463            ..
1464        } = self;
1465        E::read_bits_fixed::<BITS, R, U>(reader, value, bits)
1466    }
1467
1468    #[inline(always)]
1469    fn read_signed_counted<const MAX: u32, S>(
1470        &mut self,
1471        bits: impl TryInto<SignedBitCount<MAX>>,
1472    ) -> io::Result<S>
1473    where
1474        S: SignedInteger,
1475    {
1476        E::read_signed_counted(
1477            self,
1478            bits.try_into().map_err(|_| {
1479                io::Error::new(
1480                    io::ErrorKind::InvalidInput,
1481                    "signed reads need at least 1 bit for sign",
1482                )
1483            })?,
1484        )
1485    }
1486
1487    #[inline]
1488    fn read_signed<const BITS: u32, S>(&mut self) -> io::Result<S>
1489    where
1490        S: SignedInteger,
1491    {
1492        E::read_signed_fixed::<_, BITS, S>(self)
1493    }
1494
1495    #[inline]
1496    fn read_to<V>(&mut self) -> io::Result<V>
1497    where
1498        V: Primitive,
1499    {
1500        let mut buffer = V::buffer();
1501        E::read_bytes::<8, _>(
1502            &mut self.reader,
1503            &mut self.value,
1504            self.bits,
1505            buffer.as_mut(),
1506        )?;
1507        Ok(E::bytes_to_primitive(buffer))
1508    }
1509
1510    #[inline]
1511    fn read_as_to<F, V>(&mut self) -> io::Result<V>
1512    where
1513        F: Endianness,
1514        V: Primitive,
1515    {
1516        let mut buffer = V::buffer();
1517        F::read_bytes::<8, _>(
1518            &mut self.reader,
1519            &mut self.value,
1520            self.bits,
1521            buffer.as_mut(),
1522        )?;
1523        Ok(F::bytes_to_primitive(buffer))
1524    }
1525
1526    /// # Examples
1527    /// ```
1528    /// use std::io::Read;
1529    /// use bitstream_io::{BigEndian, BitReader, BitRead};
1530    /// let data = [0b10110111];
1531    /// let mut reader = BitReader::endian(data.as_slice(), BigEndian);
1532    /// assert!(reader.skip(3).is_ok());
1533    /// assert_eq!(reader.read::<5, u8>().unwrap(), 0b10111);
1534    /// ```
1535    ///
1536    /// ```
1537    /// use std::io::Read;
1538    /// use bitstream_io::{LittleEndian, BitReader, BitRead};
1539    /// let data = [0b10110111];
1540    /// let mut reader = BitReader::endian(data.as_slice(), LittleEndian);
1541    /// assert!(reader.skip(3).is_ok());
1542    /// assert_eq!(reader.read::<5, u8>().unwrap(), 0b10110);
1543    /// ```
1544    fn skip(&mut self, mut bits: u32) -> io::Result<()> {
1545        if BitRead::byte_aligned(self) && bits % 8 == 0 {
1546            skip_aligned(self.reader.by_ref(), bits / 8)
1547        } else {
1548            loop {
1549                match bits {
1550                    0 => break Ok(()),
1551                    bits @ 1..64 => break self.read_var(bits).map(|_: u64| ()),
1552                    _ => {
1553                        let _ = BitRead::read::<64, u64>(self)?;
1554                        bits -= 64;
1555                    }
1556                }
1557            }
1558        }
1559    }
1560
1561    /// # Example
1562    /// ```
1563    /// use std::io::Read;
1564    /// use bitstream_io::{BigEndian, BitReader, BitRead};
1565    /// let data = b"foobar";
1566    /// let mut reader = BitReader::endian(data.as_slice(), BigEndian);
1567    /// assert!(reader.skip(24).is_ok());
1568    /// let mut buf = [0;3];
1569    /// assert!(reader.read_bytes(&mut buf).is_ok());
1570    /// assert_eq!(&buf, b"bar");
1571    /// ```
1572    #[inline]
1573    fn read_bytes(&mut self, buf: &mut [u8]) -> io::Result<()> {
1574        E::read_bytes::<1024, _>(&mut self.reader, &mut self.value, self.bits, buf)
1575    }
1576
1577    fn read_unary<const STOP_BIT: u8>(&mut self) -> io::Result<u32> {
1578        let Self {
1579            value,
1580            bits,
1581            reader,
1582            ..
1583        } = self;
1584        E::pop_unary::<STOP_BIT, R>(reader, value, bits)
1585    }
1586
1587    #[inline]
1588    fn byte_aligned(&self) -> bool {
1589        self.bits == 0
1590    }
1591
1592    #[inline]
1593    fn byte_align(&mut self) {
1594        self.value = 0;
1595        self.bits = 0;
1596    }
1597}
1598
1599impl<R, E> BitReader<R, E>
1600where
1601    E: Endianness,
1602    R: io::Read + io::Seek,
1603{
1604    /// # Example
1605    /// ```
1606    /// use std::io::{Read, Cursor, SeekFrom};
1607    /// use bitstream_io::{BigEndian, BitReader, BitRead};
1608    /// let data = [0x00, 0xFF];
1609    /// let mut reader = BitReader::endian(Cursor::new(&data), BigEndian);
1610    /// assert_eq!(reader.position_in_bits().unwrap(), 0);
1611    ///
1612    /// let pos = reader.seek_bits(SeekFrom::Start(5)).unwrap();
1613    /// assert!(pos == 5 && 5 == reader.position_in_bits().unwrap());
1614    ///
1615    /// let pos = reader.seek_bits(SeekFrom::Current(-2)).unwrap();
1616    /// assert!(pos == 3 && 3 == reader.position_in_bits().unwrap());
1617    ///
1618    /// let pos = reader.seek_bits(SeekFrom::End(5)).unwrap();
1619    /// assert!(pos == 11 && 11 == reader.position_in_bits().unwrap());
1620    /// ```
1621    pub fn seek_bits(&mut self, from: io::SeekFrom) -> io::Result<u64> {
1622        match from {
1623            io::SeekFrom::Start(from_start_pos) => {
1624                let (bytes, bits) = (from_start_pos / 8, (from_start_pos % 8) as u32);
1625                BitRead::byte_align(self);
1626                self.reader.seek(io::SeekFrom::Start(bytes))?;
1627                BitRead::skip(self, bits)?;
1628                Ok(from_start_pos)
1629            }
1630            io::SeekFrom::End(from_end_pos) => {
1631                let reader_end = self.reader.seek(io::SeekFrom::End(0))?;
1632                let new_pos = (reader_end * 8) as i64 - from_end_pos;
1633                assert!(new_pos >= 0, "The final position should be greater than 0");
1634                self.seek_bits(io::SeekFrom::Start(new_pos as u64))
1635            }
1636            io::SeekFrom::Current(offset) => {
1637                let new_pos = self.position_in_bits()? as i64 + offset;
1638                assert!(new_pos >= 0, "The final position should be greater than 0");
1639                self.seek_bits(io::SeekFrom::Start(new_pos as u64))
1640            }
1641        }
1642    }
1643
1644    /// # Example
1645    /// ```
1646    /// use std::fs::read;
1647    /// use std::io::{Read, Cursor, SeekFrom};
1648    /// use bitstream_io::{BigEndian, BitReader, BitRead};
1649    /// let data = [0x00, 0xFF];
1650    /// let mut reader = BitReader::endian(Cursor::new(&data), BigEndian);
1651    /// assert_eq!(reader.position_in_bits().unwrap(), 0);
1652    ///
1653    /// let _: i32 = reader.read_signed::<5, _>().unwrap();
1654    /// assert_eq!(reader.position_in_bits().unwrap(), 5);
1655    ///
1656    /// reader.read_bit().unwrap();
1657    /// assert_eq!(reader.position_in_bits().unwrap(), 6);
1658    /// ```
1659    #[inline]
1660    pub fn position_in_bits(&mut self) -> io::Result<u64> {
1661        let bytes = self.reader.stream_position()?;
1662        Ok(bytes * 8 - (self.bits as u64))
1663    }
1664}
1665
1666fn skip_aligned<R>(reader: R, bytes: u32) -> io::Result<()>
1667where
1668    R: io::Read,
1669{
1670    fn skip_chunks<const SIZE: usize, R>(mut reader: R, mut bytes: usize) -> io::Result<()>
1671    where
1672        R: io::Read,
1673    {
1674        let mut buf = [0; SIZE];
1675        while bytes > 0 {
1676            let to_read = bytes.min(SIZE);
1677            reader.read_exact(&mut buf[0..to_read])?;
1678            bytes -= to_read;
1679        }
1680        Ok(())
1681    }
1682
1683    match bytes {
1684        0..256 => skip_chunks::<8, R>(reader, bytes as usize),
1685        256..1024 => skip_chunks::<256, R>(reader, bytes as usize),
1686        1024..4096 => skip_chunks::<1024, R>(reader, bytes as usize),
1687        _ => skip_chunks::<4096, R>(reader, bytes as usize),
1688    }
1689}
1690
1691/// A trait for anything that can read aligned values from an input stream
1692pub trait ByteRead {
1693    /// Reads whole numeric value from stream
1694    ///
1695    /// # Errors
1696    ///
1697    /// Passes along any I/O error from the underlying stream.
1698    ///
1699    /// # Examples
1700    /// ```
1701    /// use std::io::Read;
1702    /// use bitstream_io::{BigEndian, ByteReader, ByteRead};
1703    /// let data = [0b00000000, 0b11111111];
1704    /// let mut reader = ByteReader::endian(data.as_slice(), BigEndian);
1705    /// assert_eq!(reader.read::<u16>().unwrap(), 0b0000000011111111);
1706    /// ```
1707    ///
1708    /// ```
1709    /// use std::io::Read;
1710    /// use bitstream_io::{LittleEndian, ByteReader, ByteRead};
1711    /// let data = [0b00000000, 0b11111111];
1712    /// let mut reader = ByteReader::endian(data.as_slice(), LittleEndian);
1713    /// assert_eq!(reader.read::<u16>().unwrap(), 0b1111111100000000);
1714    /// ```
1715    fn read<V>(&mut self) -> Result<V, io::Error>
1716    where
1717        V: Primitive;
1718
1719    /// Reads whole numeric value from stream in a potentially different endianness
1720    ///
1721    /// # Errors
1722    ///
1723    /// Passes along any I/O error from the underlying stream.
1724    ///
1725    /// # Examples
1726    /// ```
1727    /// use std::io::Read;
1728    /// use bitstream_io::{BigEndian, ByteReader, ByteRead, LittleEndian};
1729    /// let data = [0b00000000, 0b11111111];
1730    /// let mut reader = ByteReader::endian(data.as_slice(), BigEndian);
1731    /// assert_eq!(reader.read_as::<LittleEndian, u16>().unwrap(), 0b1111111100000000);
1732    /// ```
1733    ///
1734    /// ```
1735    /// use std::io::Read;
1736    /// use bitstream_io::{BigEndian, ByteReader, ByteRead, LittleEndian};
1737    /// let data = [0b00000000, 0b11111111];
1738    /// let mut reader = ByteReader::endian(data.as_slice(), LittleEndian);
1739    /// assert_eq!(reader.read_as::<BigEndian, u16>().unwrap(), 0b0000000011111111);
1740    /// ```
1741    fn read_as<F, V>(&mut self) -> Result<V, io::Error>
1742    where
1743        F: Endianness,
1744        V: Primitive;
1745
1746    /// Completely fills the given buffer with whole bytes.
1747    ///
1748    /// # Errors
1749    ///
1750    /// Passes along any I/O error from the underlying stream.
1751    fn read_bytes(&mut self, buf: &mut [u8]) -> io::Result<()> {
1752        for b in buf.iter_mut() {
1753            *b = self.read()?;
1754        }
1755        Ok(())
1756    }
1757
1758    /// Completely fills a whole buffer with bytes and returns it.
1759    ///
1760    /// # Errors
1761    ///
1762    /// Passes along any I/O error from the underlying stream.
1763    #[inline(always)]
1764    #[deprecated(since = "1.8.0", note = "use read() method instead")]
1765    fn read_to_bytes<const SIZE: usize>(&mut self) -> io::Result<[u8; SIZE]> {
1766        self.read()
1767    }
1768
1769    /// Completely fills a vector of bytes and returns it.
1770    ///
1771    /// # Errors
1772    ///
1773    /// Passes along any I/O error from the underlying stream.
1774    fn read_to_vec(&mut self, bytes: usize) -> io::Result<Vec<u8>> {
1775        read_to_vec(|buf| self.read_bytes(buf), bytes)
1776    }
1777
1778    /// Skips the given number of bytes in the stream.
1779    ///
1780    /// # Errors
1781    ///
1782    /// Passes along any I/O error from the underlying stream.
1783    fn skip(&mut self, bytes: u32) -> io::Result<()>;
1784
1785    /// Parses and returns complex type
1786    fn parse<F: FromByteStream>(&mut self) -> Result<F, F::Error> {
1787        F::from_reader(self)
1788    }
1789
1790    /// Parses and returns complex type with context
1791    fn parse_with<'a, F: FromByteStreamWith<'a>>(
1792        &mut self,
1793        context: &F::Context,
1794    ) -> Result<F, F::Error> {
1795        F::from_reader(self, context)
1796    }
1797
1798    /// Returns mutable reference to underlying reader
1799    fn reader_ref(&mut self) -> &mut dyn io::Read;
1800}
1801
1802/// For reading aligned bytes from a stream of bytes in a given endianness.
1803///
1804/// This only reads aligned values and maintains no internal state.
1805#[derive(Debug)]
1806pub struct ByteReader<R: io::Read, E: Endianness> {
1807    phantom: PhantomData<E>,
1808    reader: R,
1809}
1810
1811impl<R: io::Read, E: Endianness> ByteReader<R, E> {
1812    /// Wraps a ByteReader around something that implements `Read`
1813    pub fn new(reader: R) -> ByteReader<R, E> {
1814        ByteReader {
1815            phantom: PhantomData,
1816            reader,
1817        }
1818    }
1819
1820    /// Wraps a ByteReader around something that implements `Read`
1821    /// with the given endianness.
1822    pub fn endian(reader: R, _endian: E) -> ByteReader<R, E> {
1823        ByteReader {
1824            phantom: PhantomData,
1825            reader,
1826        }
1827    }
1828
1829    /// Unwraps internal reader and disposes of `ByteReader`.
1830    #[inline]
1831    pub fn into_reader(self) -> R {
1832        self.reader
1833    }
1834
1835    /// Provides mutable reference to internal reader
1836    #[inline]
1837    pub fn reader(&mut self) -> &mut R {
1838        &mut self.reader
1839    }
1840
1841    /// Converts `ByteReader` to `BitReader` in the same endianness.
1842    #[inline]
1843    pub fn into_bitreader(self) -> BitReader<R, E> {
1844        BitReader::new(self.into_reader())
1845    }
1846
1847    /// Provides temporary `BitReader` in the same endianness.
1848    ///
1849    /// # Warning
1850    ///
1851    /// Any unread bits left over when `BitReader` is dropped are lost.
1852    #[inline]
1853    pub fn bitreader(&mut self) -> BitReader<&mut R, E> {
1854        BitReader::new(self.reader())
1855    }
1856}
1857
1858impl<R: io::Read, E: Endianness> ByteRead for ByteReader<R, E> {
1859    #[inline]
1860    fn read<V>(&mut self) -> Result<V, io::Error>
1861    where
1862        V: Primitive,
1863    {
1864        let mut buf = V::buffer();
1865        self.read_bytes(buf.as_mut())?;
1866        Ok(E::bytes_to_primitive(buf))
1867    }
1868
1869    #[inline]
1870    fn read_as<F, V>(&mut self) -> Result<V, io::Error>
1871    where
1872        F: Endianness,
1873        V: Primitive,
1874    {
1875        let mut buf = V::buffer();
1876        self.read_bytes(buf.as_mut())?;
1877        Ok(F::bytes_to_primitive(buf))
1878    }
1879
1880    #[inline]
1881    fn read_bytes(&mut self, buf: &mut [u8]) -> io::Result<()> {
1882        self.reader.read_exact(buf)
1883    }
1884
1885    #[inline]
1886    fn skip(&mut self, bytes: u32) -> io::Result<()> {
1887        skip_aligned(&mut self.reader, bytes)
1888    }
1889
1890    #[inline]
1891    fn reader_ref(&mut self) -> &mut dyn io::Read {
1892        &mut self.reader
1893    }
1894}
1895
1896/// Implemented by complex types that don't require any additional context
1897/// to parse themselves from a reader.  Analogous to [`std::str::FromStr`].
1898///
1899/// # Example
1900/// ```
1901/// use std::io::Read;
1902/// use bitstream_io::{BigEndian, BitRead, BitReader, FromBitStream};
1903///
1904/// #[derive(Debug, PartialEq, Eq)]
1905/// struct BlockHeader {
1906///     last_block: bool,
1907///     block_type: u8,
1908///     block_size: u32,
1909/// }
1910///
1911/// impl FromBitStream for BlockHeader {
1912///     type Error = std::io::Error;
1913///
1914///     fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> std::io::Result<Self> {
1915///         Ok(Self {
1916///             last_block: r.read_bit()?,
1917///             block_type: r.read::<7, _>()?,
1918///             block_size: r.read::<24, _>()?,
1919///         })
1920///     }
1921/// }
1922///
1923/// let mut reader = BitReader::endian(b"\x04\x00\x00\x7A".as_slice(), BigEndian);
1924/// assert_eq!(
1925///     reader.parse::<BlockHeader>().unwrap(),
1926///     BlockHeader { last_block: false, block_type: 4, block_size: 122 }
1927/// );
1928/// ```
1929pub trait FromBitStream {
1930    /// Error generated during parsing, such as `io::Error`
1931    type Error;
1932
1933    /// Parse Self from reader
1934    fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> Result<Self, Self::Error>
1935    where
1936        Self: Sized;
1937}
1938
1939/// Implemented by complex types that require some immutable context
1940/// to parse themselves from a reader.
1941///
1942/// # Example
1943/// ```
1944/// use std::io::Read;
1945/// use bitstream_io::{BigEndian, BitRead, BitReader, FromBitStreamWith};
1946///
1947/// #[derive(Default)]
1948/// struct Streaminfo {
1949///     minimum_block_size: u16,
1950///     maximum_block_size: u16,
1951///     minimum_frame_size: u32,
1952///     maximum_frame_size: u32,
1953///     sample_rate: u32,
1954///     channels: u8,
1955///     bits_per_sample: u8,
1956///     total_samples: u64,
1957///     md5: [u8; 16],
1958/// }
1959///
1960/// #[derive(Debug, PartialEq, Eq)]
1961/// struct FrameHeader {
1962///     variable_block_size: bool,
1963///     block_size: u32,
1964///     sample_rate: u32,
1965///     channel_assignment: u8,
1966///     sample_size: u8,
1967///     frame_number: u64,
1968///     crc8: u8,
1969/// }
1970///
1971/// impl FromBitStreamWith<'_> for FrameHeader {
1972///     type Context = Streaminfo;
1973///
1974///     type Error = FrameHeaderError;
1975///
1976///     fn from_reader<R: BitRead + ?Sized>(
1977///         r: &mut R,
1978///         streaminfo: &Streaminfo,
1979///     ) -> Result<Self, Self::Error> {
1980///         if r.read::<14, u16>()? != 0b11111111111110 {
1981///             return Err(FrameHeaderError::InvalidSync);
1982///         }
1983///
1984///         if r.read_bit()? != false {
1985///             return Err(FrameHeaderError::InvalidReservedBit);
1986///         }
1987///
1988///         let variable_block_size = r.read_bit()?;
1989///
1990///         let block_size_bits = r.read::<4, u8>()?;
1991///
1992///         let sample_rate_bits = r.read::<4, u8>()?;
1993///
1994///         let channel_assignment = r.read::<4, u8>()?;
1995///
1996///         let sample_size = match r.read::<3, u8>()? {
1997///             0b000 => streaminfo.bits_per_sample,
1998///             0b001 => 8,
1999///             0b010 => 12,
2000///             0b011 => return Err(FrameHeaderError::InvalidSampleSize),
2001///             0b100 => 16,
2002///             0b101 => 20,
2003///             0b110 => 24,
2004///             0b111 => 32,
2005///             _ => unreachable!(),
2006///         };
2007///
2008///         if r.read_bit()? != false {
2009///             return Err(FrameHeaderError::InvalidReservedBit);
2010///         }
2011///
2012///         let frame_number = read_utf8(r)?;
2013///
2014///         Ok(FrameHeader {
2015///             variable_block_size,
2016///             block_size: match block_size_bits {
2017///                 0b0000 => return Err(FrameHeaderError::InvalidBlockSize),
2018///                 0b0001 => 192,
2019///                 n @ 0b010..=0b0101 => 576 * (1 << (n - 2)),
2020///                 0b0110 => r.read::<8, u32>()? + 1,
2021///                 0b0111 => r.read::<16, u32>()? + 1,
2022///                 n @ 0b1000..=0b1111 => 256 * (1 << (n - 8)),
2023///                 _ => unreachable!(),
2024///             },
2025///             sample_rate: match sample_rate_bits {
2026///                 0b0000 => streaminfo.sample_rate,
2027///                 0b0001 => 88200,
2028///                 0b0010 => 176400,
2029///                 0b0011 => 192000,
2030///                 0b0100 => 8000,
2031///                 0b0101 => 16000,
2032///                 0b0110 => 22050,
2033///                 0b0111 => 24000,
2034///                 0b1000 => 32000,
2035///                 0b1001 => 44100,
2036///                 0b1010 => 48000,
2037///                 0b1011 => 96000,
2038///                 0b1100 => r.read::<8, u32>()? * 1000,
2039///                 0b1101 => r.read::<16, u32>()?,
2040///                 0b1110 => r.read::<16, u32>()? * 10,
2041///                 0b1111 => return Err(FrameHeaderError::InvalidSampleRate),
2042///                 _ => unreachable!(),
2043///             },
2044///             channel_assignment,
2045///             sample_size,
2046///             frame_number,
2047///             crc8: r.read::<8, _>()?
2048///         })
2049///     }
2050/// }
2051///
2052/// #[derive(Debug)]
2053/// enum FrameHeaderError {
2054///     Io(std::io::Error),
2055///     InvalidSync,
2056///     InvalidReservedBit,
2057///     InvalidSampleSize,
2058///     InvalidBlockSize,
2059///     InvalidSampleRate,
2060/// }
2061///
2062/// impl From<std::io::Error> for FrameHeaderError {
2063///     fn from(err: std::io::Error) -> Self {
2064///         Self::Io(err)
2065///     }
2066/// }
2067///
2068/// fn read_utf8<R: BitRead + ?Sized>(r: &mut R) -> Result<u64, std::io::Error> {
2069///     r.read::<8, _>()  // left unimplimented in this example
2070/// }
2071///
2072/// let mut reader = BitReader::endian(b"\xFF\xF8\xC9\x18\x00\xC2".as_slice(), BigEndian);
2073/// assert_eq!(
2074///     reader.parse_with::<FrameHeader>(&Streaminfo::default()).unwrap(),
2075///     FrameHeader {
2076///         variable_block_size: false,
2077///         block_size: 4096,
2078///         sample_rate: 44100,
2079///         channel_assignment: 1,
2080///         sample_size: 16,
2081///         frame_number: 0,
2082///         crc8: 0xC2,
2083///     }
2084/// );
2085/// ```
2086///
2087/// # Example with lifetime-contrained `Context`
2088///
2089/// In some cases, the `Context` can depend on a reference to another `struct`.
2090///
2091/// ```
2092/// use std::io::Read;
2093/// use bitstream_io::{BigEndian, BitRead, BitReader, FromBitStreamWith};
2094///
2095/// #[derive(Default)]
2096/// struct ModeParameters {
2097///     size_len: u8,
2098///     index_len: u8,
2099///     index_delta_len: u8,
2100///     // ...
2101/// }
2102///
2103/// struct AuHeaderParseContext<'a> {
2104///     params: &'a ModeParameters,
2105///     base_index: Option<u32>,
2106/// }
2107///
2108/// #[derive(Debug, PartialEq, Eq)]
2109/// struct AuHeader {
2110///     size: u32,
2111///     index: u32,
2112///     // ...
2113/// }
2114///
2115/// impl<'a> FromBitStreamWith<'a> for AuHeader {
2116///     type Context = AuHeaderParseContext<'a>;
2117///
2118///     type Error = AuHeaderError;
2119///
2120///     fn from_reader<R: BitRead + ?Sized>(
2121///         r: &mut R,
2122///         ctx: &AuHeaderParseContext<'a>,
2123///     ) -> Result<Self, Self::Error> {
2124///         let size = r.read_var::<u32>(ctx.params.size_len as u32)?;
2125///         let index = match ctx.base_index {
2126///             None => r.read_var::<u32>(ctx.params.index_len as u32)?,
2127///             Some(base_index) => {
2128///                 base_index
2129///                 + 1
2130///                 + r.read_var::<u32>(ctx.params.index_delta_len as u32)?
2131///             }
2132///         };
2133///
2134///         Ok(AuHeader {
2135///             size,
2136///             index,
2137///             // ...
2138///         })
2139///     }
2140/// }
2141///
2142/// #[derive(Debug)]
2143/// enum AuHeaderError {
2144///     Io(std::io::Error),
2145/// }
2146///
2147/// impl From<std::io::Error> for AuHeaderError {
2148///     fn from(err: std::io::Error) -> Self {
2149///         Self::Io(err)
2150///     }
2151/// }
2152///
2153/// let mut reader = BitReader::endian(b"\xFF\xEA\xFF\x10".as_slice(), BigEndian);
2154///
2155/// let mode_params = ModeParameters {
2156///     size_len: 10,
2157///     index_len: 6,
2158///     index_delta_len: 2,
2159///     // ...
2160/// };
2161///
2162/// let mut ctx = AuHeaderParseContext {
2163///     params: &mode_params,
2164///     base_index: None,
2165/// };
2166///
2167/// let header1 = reader.parse_with::<AuHeader>(&ctx).unwrap();
2168/// assert_eq!(
2169///     header1,
2170///     AuHeader {
2171///         size: 1023,
2172///         index: 42,
2173///     }
2174/// );
2175///
2176/// ctx.base_index = Some(header1.index);
2177///
2178/// assert_eq!(
2179///     reader.parse_with::<AuHeader>(&ctx).unwrap(),
2180///     AuHeader {
2181///         size: 1020,
2182///         index: 44,
2183///     }
2184/// );
2185/// ```
2186pub trait FromBitStreamWith<'a> {
2187    /// Some context to use when parsing
2188    type Context: 'a;
2189
2190    /// Error generated during parsing, such as `io::Error`
2191    type Error;
2192
2193    /// Parse Self from reader with the given context
2194    fn from_reader<R: BitRead + ?Sized>(
2195        r: &mut R,
2196        context: &Self::Context,
2197    ) -> Result<Self, Self::Error>
2198    where
2199        Self: Sized;
2200}
2201
2202/// Implemented by complex types that don't require any additional context
2203/// to parse themselves from a reader.  Analagous to `FromStr`.
2204pub trait FromByteStream {
2205    /// Error generated during parsing, such as `io::Error`
2206    type Error;
2207
2208    /// Parse Self from reader
2209    fn from_reader<R: ByteRead + ?Sized>(r: &mut R) -> Result<Self, Self::Error>
2210    where
2211        Self: Sized;
2212}
2213
2214/// Implemented by complex types that require some additional context
2215/// to parse themselves from a reader.  Analagous to `FromStr`.
2216pub trait FromByteStreamWith<'a> {
2217    /// Some context to use when parsing
2218    type Context: 'a;
2219
2220    /// Error generated during parsing, such as `io::Error`
2221    type Error;
2222
2223    /// Parse Self from reader
2224    fn from_reader<R: ByteRead + ?Sized>(
2225        r: &mut R,
2226        context: &Self::Context,
2227    ) -> Result<Self, Self::Error>
2228    where
2229        Self: Sized;
2230}
2231
2232fn read_to_vec(
2233    mut read: impl FnMut(&mut [u8]) -> io::Result<()>,
2234    bytes: usize,
2235) -> io::Result<Vec<u8>> {
2236    const MAX_CHUNK: usize = 4096;
2237
2238    match bytes {
2239        0 => Ok(Vec::new()),
2240        bytes if bytes <= MAX_CHUNK => {
2241            let mut buf = vec![0; bytes];
2242            read(&mut buf)?;
2243            Ok(buf)
2244        }
2245        mut bytes => {
2246            let mut whole = Vec::with_capacity(MAX_CHUNK);
2247            let mut chunk: [u8; MAX_CHUNK] = [0; MAX_CHUNK];
2248            while bytes > 0 {
2249                let chunk_size = bytes.min(MAX_CHUNK);
2250                let chunk = &mut chunk[0..chunk_size];
2251                read(chunk)?;
2252                whole.extend_from_slice(chunk);
2253                bytes -= chunk_size;
2254            }
2255            Ok(whole)
2256        }
2257    }
2258}