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