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