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