oximedia_bitstream/read/bit_read.rs
1// Copyright 2017 Brian Langenberger
2// Copyright 2024-2026 COOLJAPAN OU (Team Kitasan)
3//
4// Licensed under the Apache License, Version 2.0 or the MIT license,
5// at your option. See the LICENSE-APACHE / LICENSE-MIT files for details.
6
7//! The core `BitRead` trait and its blanket impls.
8
9use std::io;
10#[cfg(feature = "alloc")]
11use std::vec::Vec;
12
13use super::{
14 read_to_vec, BitCount, CheckablePrimitive, Endianness, FromBitStream, FromBitStreamUsing,
15 FromBitStreamWith, Integer, Primitive, SignedBitCount, SignedInteger, UnsignedInteger,
16 VBRInteger, VariableWidthOverflow,
17};
18
19/// A trait for anything that can read a variable number of
20/// potentially un-aligned values from an input stream
21pub trait BitRead {
22 /// Reads a single bit from the stream.
23 /// `true` indicates 1, `false` indicates 0
24 ///
25 /// # Errors
26 ///
27 /// Passes along any I/O error from the underlying stream.
28 ///
29 /// # Examples
30 /// ```
31 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian};
32 ///
33 /// let bytes: &[u8] = &[0b1000_1110];
34 /// let mut r = BitReader::endian(bytes, BigEndian);
35 /// assert_eq!(r.read_bit().unwrap(), true);
36 /// assert_eq!(r.read_bit().unwrap(), false);
37 /// assert_eq!(r.read_bit().unwrap(), false);
38 /// assert_eq!(r.read_bit().unwrap(), false);
39 /// assert_eq!(r.read_bit().unwrap(), true);
40 /// assert_eq!(r.read_bit().unwrap(), true);
41 /// assert_eq!(r.read_bit().unwrap(), true);
42 /// assert_eq!(r.read_bit().unwrap(), false);
43 /// assert!(r.read_bit().is_err()); // no more bits to read
44 /// ```
45 ///
46 /// ```
47 /// use oximedia_bitstream::{BitReader, BitRead, LittleEndian};
48 ///
49 /// let bytes: &[u8] = &[0b1000_1110];
50 /// let mut r = BitReader::endian(bytes, LittleEndian);
51 /// assert_eq!(r.read_bit().unwrap(), false);
52 /// assert_eq!(r.read_bit().unwrap(), true);
53 /// assert_eq!(r.read_bit().unwrap(), true);
54 /// assert_eq!(r.read_bit().unwrap(), true);
55 /// assert_eq!(r.read_bit().unwrap(), false);
56 /// assert_eq!(r.read_bit().unwrap(), false);
57 /// assert_eq!(r.read_bit().unwrap(), false);
58 /// assert_eq!(r.read_bit().unwrap(), true);
59 /// assert!(r.read_bit().is_err()); // no more bits to read
60 /// ```
61 fn read_bit(&mut self) -> io::Result<bool> {
62 self.read_unsigned::<1, u8>().map(|b| b == 1)
63 }
64
65 /// Reads a signed or unsigned value from the stream with
66 /// the given constant number of bits.
67 ///
68 /// # Errors
69 ///
70 /// Passes along any I/O error from the underlying stream.
71 /// A compile-time error occurs if the given number of bits
72 /// is larger than the output type.
73 ///
74 /// # Examples
75 /// ```
76 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian};
77 ///
78 /// let bytes: &[u8] = &[0b0001_1111, 0b1011_11_00];
79 /// let mut r = BitReader::endian(bytes, BigEndian);
80 /// // reading unsigned value is ok
81 /// assert_eq!(r.read::<4, u8>().unwrap(), 1);
82 /// // reading signed value is also ok
83 /// assert_eq!(r.read::<4, i8>().unwrap(), -1);
84 /// // reading an array of bits is ok too
85 /// assert_eq!(r.read::<1, [bool; 4]>().unwrap(), [true, false, true, true]);
86 /// // reading an array of any Integer type is ok
87 /// assert_eq!(r.read::<2, [u8; 2]>().unwrap(), [0b11, 0b00]);
88 /// // reading more bytes than we have is an error
89 /// assert!(r.read::<4, u8>().is_err());
90 /// ```
91 ///
92 /// ```rust,compile_fail
93 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian};
94 ///
95 /// let bytes: &[u8] = &[0b0001_1111, 0, 0];
96 /// let mut r = BitReader::endian(bytes, BigEndian);
97 /// // reading 9 bits to a u8 is a compile-time error
98 /// r.read::<9, u8>();
99 /// ```
100 #[inline]
101 fn read<const BITS: u32, I>(&mut self) -> io::Result<I>
102 where
103 I: Integer,
104 {
105 I::read::<BITS, _>(self)
106 }
107
108 /// Reads a signed or unsigned value from the stream with
109 /// the given variable number of bits.
110 ///
111 /// # Errors
112 ///
113 /// Passes along any I/O error from the underlying stream.
114 /// Also returns an error if the output type is too small
115 /// to hold the requested number of bits.
116 ///
117 /// # Examples
118 /// ```
119 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian};
120 /// let bytes: &[u8] = &[0b0001_1111];
121 /// let mut r = BitReader::endian(bytes, BigEndian);
122 /// // reading unsigned value is ok
123 /// assert_eq!(r.read_var::<u8>(4).unwrap(), 1);
124 /// // reading signed value is also ok
125 /// assert_eq!(r.read_var::<i8>(4).unwrap(), -1);
126 /// // reading more bytes than we have is an error
127 /// assert!(r.read_var::<u8>(4).is_err());
128 /// ```
129 ///
130 /// ```
131 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian};
132 /// let bytes: &[u8] = &[0, 0, 0, 0, 0];
133 /// let mut r = BitReader::endian(bytes, BigEndian);
134 /// // reading 9 bits to a u8 is a runtime error
135 /// // no matter how much data is left
136 /// assert!(r.read_var::<u8>(9).is_err());
137 /// ```
138 #[inline]
139 fn read_var<I>(&mut self, bits: u32) -> io::Result<I>
140 where
141 I: Integer + Sized,
142 {
143 I::read_var(self, BitCount::unknown(bits))
144 }
145
146 /// Given a desired maximum value for a bit count,
147 /// reads the necessary bits to fill up to that amount.
148 ///
149 /// For example, if the maximum bit count is 15 - or `0b1111` -
150 /// reads a 4-bit unsigned value from the stream and returns a [`BitCount`]
151 /// which can be used in subsequent reads.
152 ///
153 /// Note that `MAX` must be greater than 0, and `MAX + 1` must be
154 /// an exact power of two.
155 ///
156 /// # Errors
157 ///
158 /// Passes along an I/O error from the underlying stream.
159 ///
160 /// # Examples
161 ///
162 /// ```
163 /// use oximedia_bitstream::{BigEndian, BitReader, BitRead};
164 ///
165 /// let bytes: &[u8] = &[0b100_11110];
166 /// let mut r = BitReader::endian(bytes, BigEndian);
167 /// let count = r.read::<3, u32>().unwrap();
168 /// assert_eq!(count, 4); // reads 0b100 - or 4
169 /// // may need to verify count is not larger than u8 at runtime
170 /// assert_eq!(r.read_var::<u8>(count).unwrap(), 0b1111);
171 /// ```
172 ///
173 /// ```
174 /// use oximedia_bitstream::{BigEndian, BitReader, BitRead, BitCount};
175 ///
176 /// let bytes: &[u8] = &[0b100_11110];
177 /// let mut r = BitReader::endian(bytes, BigEndian);
178 /// let count = r.read_count::<0b111>().unwrap();
179 /// assert_eq!(count, BitCount::new::<4>()); // reads 0b100 - or 4
180 /// // maximum size of bit count is known to be 7 at compile-time,
181 /// // so no runtime check needed to know 7 bits is not larger than a u8
182 /// assert_eq!(r.read_counted::<0b111, u8>(count).unwrap(), 0b1111);
183 /// ```
184 ///
185 /// ```rust,compile_fail
186 /// use oximedia_bitstream::{BigEndian, BitReader, BitRead};
187 ///
188 /// let bytes: &[u8] = &[0b100_11110];
189 /// let mut r = BitReader::endian(bytes, BigEndian);
190 /// // maximum bit count is 6 (0b110), so we need to read 3 bits
191 /// // but no idea what to do if a value of 7 (0b111) is read,
192 /// // so this does not compile at all
193 /// let count = r.read_count::<0b110>();
194 /// ```
195 fn read_count<const MAX: u32>(&mut self) -> io::Result<BitCount<MAX>> {
196 const {
197 assert!(MAX > 0, "MAX value must be > 0");
198 assert!(
199 MAX == u32::MAX || (MAX + 1).is_power_of_two(),
200 "MAX should fill some whole number of bits ('0b111', '0b1111', etc.)"
201 );
202 }
203
204 self.read_unsigned_var(if MAX < u32::MAX {
205 (MAX + 1).ilog2()
206 } else {
207 32
208 })
209 .map(|bits| BitCount { bits })
210 }
211
212 /// Reads a signed or unsigned value from the stream with
213 /// the given number of bits.
214 ///
215 /// # Errors
216 ///
217 /// Passes along any I/O error from the underlying stream.
218 /// Also returns an error if the output type is too small
219 /// to hold the requested number of bits.
220 ///
221 /// # Examples
222 /// ```
223 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian, BitCount};
224 ///
225 /// let bytes: &[u8] = &[0b1111_0000];
226 /// let mut r = BitReader::endian(bytes, BigEndian);
227 /// // reading 4 bits with a maximum of 4 will fit into a u8
228 /// // so no runtime check needed
229 /// assert_eq!(r.read_counted::<4, u8>(BitCount::new::<4>()).unwrap(), 0b1111);
230 /// // reading 4 bits with a maximum of 64 might not fit into a u8
231 /// // so we need to verify this at runtime
232 /// assert_eq!(r.read_counted::<64, u8>(BitCount::new::<4>()).unwrap(), 0b0000);
233 /// ```
234 #[inline(always)]
235 fn read_counted<const MAX: u32, I>(&mut self, bits: BitCount<MAX>) -> io::Result<I>
236 where
237 I: Integer + Sized,
238 {
239 I::read_var(self, bits)
240 }
241
242 /// Reads an unsigned value from the stream with
243 /// the given constant number of bits.
244 ///
245 /// # Errors
246 ///
247 /// Passes along any I/O error from the underlying stream.
248 /// A compile-time error occurs if the given number of bits
249 /// is larger than the output type.
250 ///
251 /// # Examples
252 /// ```
253 /// use oximedia_bitstream::{BigEndian, BitReader, BitRead};
254 /// let data: &[u8] = &[0b1_01_10111];
255 /// let mut reader = BitReader::endian(data, BigEndian);
256 /// assert_eq!(reader.read_unsigned::<1, u8>().unwrap(), 0b1);
257 /// assert_eq!(reader.read_unsigned::<2, u8>().unwrap(), 0b01);
258 /// assert_eq!(reader.read_unsigned::<5, u8>().unwrap(), 0b10111);
259 /// ```
260 ///
261 /// ```
262 /// use oximedia_bitstream::{LittleEndian, BitReader, BitRead};
263 /// let data: &[u8] = &[0b10110_11_1];
264 /// let mut reader = BitReader::endian(data, LittleEndian);
265 /// assert_eq!(reader.read_unsigned::<1, u8>().unwrap(), 0b1);
266 /// assert_eq!(reader.read_unsigned::<2, u8>().unwrap(), 0b11);
267 /// assert_eq!(reader.read_unsigned::<5, u8>().unwrap(), 0b10110);
268 /// ```
269 ///
270 /// ```rust,compile_fail
271 /// use oximedia_bitstream::{BigEndian, BitReader, BitRead};
272 /// let data: &[u8] = &[0, 0, 0, 0, 0];
273 /// let mut reader = BitReader::endian(data, BigEndian);
274 /// // doesn't compile at all
275 /// reader.read_unsigned::<9, u8>(); // can't read 9 bits to u8
276 /// ```
277 fn read_unsigned<const BITS: u32, U>(&mut self) -> io::Result<U>
278 where
279 U: UnsignedInteger,
280 {
281 self.read_unsigned_var(BITS)
282 }
283
284 /// Reads an unsigned value from the stream with
285 /// the given number of bits.
286 ///
287 /// # Errors
288 ///
289 /// Passes along any I/O error from the underlying stream.
290 /// Also returns an error if the output type is too small
291 /// to hold the requested number of bits.
292 ///
293 /// # Examples
294 /// ```
295 /// use oximedia_bitstream::{BigEndian, BitReader, BitRead};
296 /// let data: &[u8] = &[0b1_01_10111];
297 /// let mut reader = BitReader::endian(data, BigEndian);
298 /// assert_eq!(reader.read_unsigned_var::<u8>(1).unwrap(), 0b1);
299 /// assert_eq!(reader.read_unsigned_var::<u8>(2).unwrap(), 0b01);
300 /// assert_eq!(reader.read_unsigned_var::<u8>(5).unwrap(), 0b10111);
301 /// ```
302 ///
303 /// ```
304 /// use oximedia_bitstream::{LittleEndian, BitReader, BitRead};
305 /// let data: &[u8] = &[0b10110_11_1];
306 /// let mut reader = BitReader::endian(data, LittleEndian);
307 /// assert_eq!(reader.read_unsigned_var::<u8>(1).unwrap(), 0b1);
308 /// assert_eq!(reader.read_unsigned_var::<u8>(2).unwrap(), 0b11);
309 /// assert_eq!(reader.read_unsigned_var::<u8>(5).unwrap(), 0b10110);
310 /// ```
311 ///
312 /// ```
313 /// use oximedia_bitstream::{BigEndian, BitReader, BitRead};
314 /// let data: &[u8] = &[0, 0, 0, 0, 0];
315 /// let mut reader = BitReader::endian(data, BigEndian);
316 /// assert!(reader.read_unsigned_var::<u8>(9).is_err()); // can't read 9 bits to u8
317 /// assert!(reader.read_unsigned_var::<u16>(17).is_err()); // can't read 17 bits to u16
318 /// assert!(reader.read_unsigned_var::<u32>(33).is_err()); // can't read 33 bits to u32
319 /// assert!(reader.read_unsigned_var::<u64>(65).is_err()); // can't read 65 bits to u64
320 /// ```
321 #[inline(always)]
322 fn read_unsigned_var<U>(&mut self, bits: u32) -> io::Result<U>
323 where
324 U: UnsignedInteger,
325 {
326 self.read_unsigned_counted(BitCount::unknown(bits))
327 }
328
329 /// Reads an unsigned value from the stream with
330 /// the given number of bits.
331 ///
332 /// # Errors
333 ///
334 /// Passes along any I/O error from the underlying stream.
335 /// Also returns an error if the output type is too small
336 /// to hold the requested number of bits.
337 ///
338 /// # Examples
339 /// ```
340 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian, BitCount};
341 ///
342 /// let bytes: &[u8] = &[0b1111_0000];
343 /// let mut r = BitReader::endian(bytes, BigEndian);
344 /// // reading 4 bits with a maximum of 4 will fit into a u8
345 /// // so no runtime check needed
346 /// assert_eq!(r.read_unsigned_counted::<4, u8>(BitCount::new::<4>()).unwrap(), 0b1111);
347 /// // reading 4 bits with a maximum of 64 might not fit into a u8
348 /// // so we need to verify this at runtime
349 /// assert_eq!(r.read_unsigned_counted::<64, u8>(BitCount::new::<4>()).unwrap(), 0b0000);
350 /// ```
351 fn read_unsigned_counted<const MAX: u32, U>(&mut self, bits: BitCount<MAX>) -> io::Result<U>
352 where
353 U: UnsignedInteger;
354
355 /// Reads a twos-complement signed value from the stream with
356 /// the given constant number of bits.
357 ///
358 /// # Errors
359 ///
360 /// Passes along any I/O error from the underlying stream.
361 /// A compile-time error occurs if the number of bits is 0,
362 /// since one bit is always needed for the sign.
363 /// A compile-time error occurs if the given number of bits
364 /// is larger than the output type.
365 ///
366 /// # Examples
367 /// ```
368 /// use oximedia_bitstream::{BigEndian, BitReader, BitRead};
369 ///
370 /// let data: &[u8] = &[0b1011_0111];
371 /// let mut reader = BitReader::endian(data, BigEndian);
372 /// assert_eq!(reader.read_signed::<4, i8>().unwrap(), -5);
373 /// assert_eq!(reader.read_signed::<4, i8>().unwrap(), 7);
374 /// assert!(reader.read_signed::<4, i8>().is_err());
375 /// ```
376 ///
377 /// ```
378 /// use oximedia_bitstream::{LittleEndian, BitReader, BitRead};
379 ///
380 /// let data: &[u8] = &[0b1011_0111];
381 /// let mut reader = BitReader::endian(data, LittleEndian);
382 /// assert_eq!(reader.read_signed::<4, i8>().unwrap(), 7);
383 /// assert_eq!(reader.read_signed::<4, i8>().unwrap(), -5);
384 /// assert!(reader.read_signed::<4, i8>().is_err());
385 /// ```
386 ///
387 /// ```rust,compile_fail
388 /// use oximedia_bitstream::{LittleEndian, BitReader, BitRead};
389 ///
390 /// let data: &[u8] = &[0, 0, 0, 0, 0];
391 /// let mut reader = BitReader::endian(data, LittleEndian);
392 /// // reading 9 bits to an i8 is a compile-time error
393 /// reader.read_signed::<9, i8>();
394 /// ```
395 fn read_signed<const BITS: u32, S>(&mut self) -> io::Result<S>
396 where
397 S: SignedInteger,
398 {
399 self.read_signed_var(BITS)
400 }
401
402 /// Reads a twos-complement signed value from the stream with
403 /// the given number of bits.
404 ///
405 /// # Errors
406 ///
407 /// Passes along any I/O error from the underlying stream.
408 /// Returns an error if the number of bits is 0,
409 /// since one bit is always needed for the sign.
410 /// Also returns an error if the output type is too small
411 /// to hold the requested number of bits.
412 ///
413 /// # Examples
414 /// ```
415 /// use oximedia_bitstream::{BigEndian, BitReader, BitRead};
416 /// let data: &[u8] = &[0b1011_0111];
417 /// let mut reader = BitReader::endian(data, BigEndian);
418 /// assert_eq!(reader.read_signed_var::<i8>(4).unwrap(), -5);
419 /// assert_eq!(reader.read_signed_var::<i8>(4).unwrap(), 7);
420 /// ```
421 ///
422 /// ```
423 /// use oximedia_bitstream::{LittleEndian, BitReader, BitRead};
424 /// let data: &[u8] = &[0b1011_0111];
425 /// let mut reader = BitReader::endian(data, LittleEndian);
426 /// assert_eq!(reader.read_signed_var::<i8>(4).unwrap(), 7);
427 /// assert_eq!(reader.read_signed_var::<i8>(4).unwrap(), -5);
428 /// ```
429 ///
430 /// ```
431 /// use std::io::Read;
432 /// use oximedia_bitstream::{BigEndian, BitReader, BitRead};
433 /// let data: &[u8] = &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
434 /// let mut r = BitReader::endian(data, BigEndian);
435 /// assert!(r.read_signed_var::<i8>(9).is_err()); // can't read 9 bits to i8
436 /// assert!(r.read_signed_var::<i16>(17).is_err()); // can't read 17 bits to i16
437 /// assert!(r.read_signed_var::<i32>(33).is_err()); // can't read 33 bits to i32
438 /// assert!(r.read_signed_var::<i64>(65).is_err()); // can't read 65 bits to i64
439 /// ```
440 fn read_signed_var<S>(&mut self, bits: u32) -> io::Result<S>
441 where
442 S: SignedInteger,
443 {
444 self.read_signed_counted(BitCount::unknown(bits))
445 }
446
447 /// Reads a twos-complement signed value from the stream with
448 /// the given number of bits.
449 ///
450 /// # Errors
451 ///
452 /// Passes along any I/O error from the underlying stream.
453 /// Returns an error if the number of bits is 0,
454 /// since one bit is always needed for the sign.
455 /// Also returns an error if the output type is too small
456 /// to hold the requested number of bits.
457 ///
458 /// # Examples
459 /// ```
460 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian, BitCount};
461 ///
462 /// let bytes: &[u8] = &[0b0001_1111];
463 /// let mut r = BitReader::endian(bytes, BigEndian);
464 /// // reading 4 bits with a maximum of 4 will fit into an i8
465 /// // so no runtime check needed
466 /// assert_eq!(r.read_signed_counted::<4, i8>(BitCount::new::<4>()).unwrap(), 1);
467 /// // reading 4 bits with a maximum of 64 might not fit into an i8
468 /// // so we need to verify this at runtime
469 /// assert_eq!(r.read_signed_counted::<64, i8>(BitCount::new::<4>()).unwrap(), -1);
470 /// ```
471 fn read_signed_counted<const MAX: u32, S>(
472 &mut self,
473 bits: impl TryInto<SignedBitCount<MAX>>,
474 ) -> io::Result<S>
475 where
476 S: SignedInteger;
477
478 /// Reads the given constant value from the stream with the
479 /// given number of bits.
480 ///
481 /// Due to current limitations of constant paramters,
482 /// this is limited to `u32` values.
483 ///
484 /// If the constant read from the stream doesn't match the expected
485 /// value, returns the generated error from the closure.
486 ///
487 /// # Errors
488 ///
489 /// Passes along any I/O error from the underlying stream,
490 /// converted to the mismatch error. Returns the generated
491 /// error if the read value doesn't match the expected constant.
492 ///
493 /// # Examples
494 ///
495 /// ```
496 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian};
497 ///
498 /// enum Error {
499 /// Mismatch,
500 /// Io,
501 /// }
502 ///
503 /// impl From<std::io::Error> for Error {
504 /// fn from(_err: std::io::Error) -> Self {
505 /// Self::Io
506 /// }
507 /// }
508 ///
509 /// let data: &[u8] = &[0b1000_1011, 0b0000_0001];
510 /// let mut r = BitReader::endian(data, BigEndian);
511 /// assert!(r.read_const::<4, 0b1000, _>(Error::Mismatch).is_ok());
512 /// assert!(r.read_const::<4, 0b1011, _>(Error::Mismatch).is_ok());
513 /// // 0b1000 doesn't match 0b0000
514 /// assert!(matches!(r.read_const::<4, 0b1000, _>(Error::Mismatch), Err(Error::Mismatch)));
515 /// // 0b1011 doesn't match 0b0001
516 /// assert!(matches!(r.read_const::<4, 0b1011, _>(Error::Mismatch), Err(Error::Mismatch)));
517 /// // run out of bits to check
518 /// assert!(matches!(r.read_const::<4, 0b0000, _>(Error::Mismatch), Err(Error::Io)));
519 /// ```
520 #[inline]
521 fn read_const<const BITS: u32, const VALUE: u32, E>(&mut self, err: E) -> Result<(), E>
522 where
523 E: From<io::Error>,
524 {
525 use crate::Numeric;
526
527 const {
528 assert!(
529 BITS == 0 || VALUE <= (u32::ALL >> (u32::BITS_SIZE - BITS)),
530 "excessive value for bits read"
531 );
532 }
533
534 (self.read::<BITS, u32>()? == VALUE)
535 .then_some(())
536 .ok_or(err)
537 }
538
539 /// Reads whole value from the stream whose size in bits is equal
540 /// to its type's size.
541 ///
542 /// # Errors
543 ///
544 /// Passes along any I/O error from the underlying stream.
545 ///
546 /// # Examples
547 /// ```
548 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian};
549 ///
550 /// let bytes: &[u8] = &[0x12, 0x34, 0x56, 0x78];
551 /// let mut r = BitReader::endian(bytes, BigEndian);
552 /// assert_eq!(r.read_to::<u32>().unwrap(), 0x12_34_56_78);
553 /// ```
554 ///
555 /// ```
556 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian};
557 ///
558 /// let bytes: &[u8] = &[0x12, 0x34, 0x56, 0x78];
559 /// let mut r = BitReader::endian(bytes, BigEndian);
560 /// assert_eq!(r.read_to::<[u8; 4]>().unwrap(), [0x12, 0x34, 0x56, 0x78]);
561 /// ```
562 fn read_to<V>(&mut self) -> io::Result<V>
563 where
564 V: Primitive;
565
566 /// Reads whole value from the stream whose size in bits is equal
567 /// to its type's size in an endianness that may be different
568 /// from the stream's endianness.
569 ///
570 /// # Errors
571 ///
572 /// Passes along any I/O error from the underlying stream.
573 ///
574 /// # Example
575 /// ```
576 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian, LittleEndian};
577 ///
578 /// let bytes: &[u8] = &[0x12, 0x34, 0x56, 0x78];
579 /// let mut r = BitReader::endian(bytes, BigEndian);
580 /// assert_eq!(r.read_as_to::<LittleEndian, u32>().unwrap(), 0x78_56_34_12);
581 /// ```
582 fn read_as_to<F, V>(&mut self) -> io::Result<V>
583 where
584 F: Endianness,
585 V: Primitive;
586
587 /// Skips the given number of bits in the stream.
588 /// Since this method does not need an accumulator,
589 /// it may be slightly faster than reading to an empty variable.
590 /// In addition, since there is no accumulator,
591 /// there is no upper limit on the number of bits
592 /// which may be skipped.
593 /// These bits are still read from the stream, however,
594 /// and are never skipped via a `seek` method.
595 ///
596 /// # Errors
597 ///
598 /// Passes along any I/O error from the underlying stream.
599 ///
600 /// # Example
601 /// ```
602 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian};
603 ///
604 /// let bytes: &[u8] = &[0b1_00000_10];
605 /// let mut r = BitReader::endian(bytes, BigEndian);
606 /// assert_eq!(r.read_bit().unwrap(), true);
607 /// assert!(r.skip(5).is_ok());
608 /// assert_eq!(r.read_bit().unwrap(), true);
609 /// assert_eq!(r.read_bit().unwrap(), false);
610 /// assert!(r.read_bit().is_err());
611 /// ```
612 fn skip(&mut self, bits: u32) -> io::Result<()> {
613 (0..bits).try_for_each(|_| self.read_bit().map(|_| ()))
614 }
615
616 /// Completely fills the given buffer with whole bytes.
617 /// If the stream is already byte-aligned, it will map
618 /// to a faster `read_exact` call. Otherwise it will read
619 /// bytes individually in 8-bit increments.
620 ///
621 /// # Errors
622 ///
623 /// Passes along any I/O error from the underlying stream.
624 ///
625 /// # Example
626 /// ```
627 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian};
628 ///
629 /// let bytes: &[u8] = &[0x00, 0x01, 0x02, 0x03, 0x04];
630 /// let mut r = BitReader::endian(bytes, BigEndian);
631 /// let mut buf = [0; 3];
632 /// assert_eq!(r.read::<8, u8>().unwrap(), 0x00);
633 /// assert!(r.read_bytes(&mut buf).is_ok());
634 /// assert_eq!(&buf, &[0x01, 0x02, 0x03]);
635 /// assert_eq!(r.read::<8, u8>().unwrap(), 0x04);
636 /// ```
637 fn read_bytes(&mut self, buf: &mut [u8]) -> io::Result<()> {
638 for b in buf.iter_mut() {
639 *b = self.read_unsigned::<8, _>()?;
640 }
641 Ok(())
642 }
643
644 /// Completely fills a whole buffer with bytes and returns it.
645 /// If the stream is already byte-aligned, it will map
646 /// to a faster `read_exact` call. Otherwise it will read
647 /// bytes individually in 8-bit increments.
648 ///
649 /// # Errors
650 ///
651 /// Passes along any I/O error from the underlying stream.
652 #[inline(always)]
653 #[deprecated(since = "1.8.0", note = "use read_to() method instead")]
654 fn read_to_bytes<const SIZE: usize>(&mut self) -> io::Result<[u8; SIZE]> {
655 self.read_to()
656 }
657
658 /// Completely fills a vector of bytes and returns it.
659 /// If the stream is already byte-aligned, it will map
660 /// to a faster `read_exact` call. Otherwise it will read
661 /// bytes individually in 8-bit increments.
662 ///
663 /// # Errors
664 ///
665 /// Passes along any I/O error from the underlying stream.
666 ///
667 /// # Example
668 /// ```
669 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian};
670 ///
671 /// let bytes: &[u8] = &[0x00, 0x01, 0x02, 0x03, 0x04];
672 /// let mut r = BitReader::endian(bytes, BigEndian);
673 /// let mut buf = [0; 3];
674 /// assert_eq!(r.read::<8, u8>().unwrap(), 0x00);
675 /// assert_eq!(r.read_to_vec(3).unwrap().as_slice(), &[0x01, 0x02, 0x03]);
676 /// assert_eq!(r.read::<8, u8>().unwrap(), 0x04);
677 /// ```
678 #[cfg(feature = "alloc")]
679 #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
680 fn read_to_vec(&mut self, bytes: usize) -> io::Result<Vec<u8>> {
681 read_to_vec(|buf| self.read_bytes(buf), bytes)
682 }
683
684 /// Counts the number of bits in the stream until `STOP_BIT`
685 /// and returns the amount read.
686 /// `STOP_BIT` must be 0 or 1.
687 /// Because this field is variably-sized and may be large,
688 /// its output is always a `u32` type.
689 ///
690 /// # Errors
691 ///
692 /// Passes along any I/O error from the underlying stream.
693 /// May panic if the number of bits exceeds `u32`.
694 ///
695 /// # Examples
696 /// ```
697 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian};
698 ///
699 /// let bytes: &[u8] = &[0b0_10_11111, 0b10_000000];
700 /// let mut r = BitReader::endian(bytes, BigEndian);
701 /// // read 1 bits until stop bit of 0, big-endian order
702 /// assert_eq!(r.read_unary::<0>().unwrap(), 0);
703 /// assert_eq!(r.read_unary::<0>().unwrap(), 1);
704 /// assert_eq!(r.read_unary::<0>().unwrap(), 6);
705 /// ```
706 ///
707 /// ```
708 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian};
709 ///
710 /// let bytes: &[u8] = &[0b1_01_00000, 0b01_000000];
711 /// let mut r = BitReader::endian(bytes, BigEndian);
712 /// // read 0 bits until stop bit of 1, big-endian order
713 /// assert_eq!(r.read_unary::<1>().unwrap(), 0);
714 /// assert_eq!(r.read_unary::<1>().unwrap(), 1);
715 /// assert_eq!(r.read_unary::<1>().unwrap(), 6);
716 /// ```
717 ///
718 /// ```
719 /// use oximedia_bitstream::{BitReader, BitRead, LittleEndian};
720 ///
721 /// let bytes: &[u8] = &[0b11111_01_0, 0b000000_01];
722 /// let mut r = BitReader::endian(bytes, LittleEndian);
723 /// // read 1 bits until stop bit of 0, little-endian order
724 /// assert_eq!(r.read_unary::<0>().unwrap(), 0);
725 /// assert_eq!(r.read_unary::<0>().unwrap(), 1);
726 /// assert_eq!(r.read_unary::<0>().unwrap(), 6);
727 /// ```
728 ///
729 /// ```
730 /// use oximedia_bitstream::{BitReader, BitRead, LittleEndian};
731 ///
732 /// let bytes: &[u8] = &[0b00000_10_1, 0b111111_10];
733 /// let mut r = BitReader::endian(bytes, LittleEndian);
734 /// // read 0 bits until stop bit of 1, little-endian order
735 /// assert_eq!(r.read_unary::<1>().unwrap(), 0);
736 /// assert_eq!(r.read_unary::<1>().unwrap(), 1);
737 /// assert_eq!(r.read_unary::<1>().unwrap(), 6);
738 /// ```
739 fn read_unary<const STOP_BIT: u8>(&mut self) -> io::Result<u32> {
740 const {
741 assert!(matches!(STOP_BIT, 0 | 1), "stop bit must be 0 or 1");
742 }
743
744 // a simple implementation which works anywhere
745 let mut unary = 0;
746 while self.read::<1, u8>()? != STOP_BIT {
747 unary += 1;
748 }
749 Ok(unary)
750 }
751
752 /// Reads to a checked value that is known to fit a given number of bits
753 ///
754 /// # Example
755 /// ```
756 /// use oximedia_bitstream::{
757 /// BitRead, BitReader, BigEndian, Checked, CheckedUnsigned, CheckedSigned,
758 /// BitCount, SignedBitCount, BitWrite, BitWriter,
759 /// };
760 ///
761 /// let data: &[u8] = &[0b1001_1111];
762 /// let mut r = BitReader::endian(data, BigEndian);
763 ///
764 /// let bit_count = BitCount::<4>::new::<4>();
765 /// let checked_u8 = r.read_checked::<CheckedUnsigned<4, u8>>(bit_count).unwrap();
766 /// assert_eq!(checked_u8.into_value(), 0b1001);
767 ///
768 /// let bit_count = SignedBitCount::<4>::new::<4>();
769 /// let checked_i8 = r.read_checked::<CheckedSigned<4, i8>>(bit_count).unwrap();
770 /// assert_eq!(checked_i8.into_value(), -1);
771 ///
772 /// // note that checked values already know their bit count
773 /// // so none is required when writing them to a stream
774 /// let mut w = BitWriter::endian(vec![], BigEndian);
775 /// w.write_checked(checked_u8).unwrap();
776 /// w.write_checked(checked_i8).unwrap();
777 /// assert_eq!(w.into_writer().as_slice(), data);
778 /// ```
779 #[inline]
780 fn read_checked<C>(&mut self, count: C::CountType) -> io::Result<C>
781 where
782 C: CheckablePrimitive,
783 {
784 C::read(self, count)
785 }
786
787 /// Parses and returns complex type
788 fn parse<F: FromBitStream>(&mut self) -> Result<F, F::Error> {
789 F::from_reader(self)
790 }
791
792 /// Parses and returns complex type with context
793 fn parse_with<'a, F: FromBitStreamWith<'a>>(
794 &mut self,
795 context: &F::Context,
796 ) -> Result<F, F::Error> {
797 F::from_reader(self, context)
798 }
799
800 /// Parses and returns complex type with owned context
801 fn parse_using<F: FromBitStreamUsing>(&mut self, context: F::Context) -> Result<F, F::Error> {
802 F::from_reader(self, context)
803 }
804
805 /// Returns true if the stream is aligned at a whole byte.
806 ///
807 /// # Example
808 /// ```
809 /// use std::io::Read;
810 /// use oximedia_bitstream::{BigEndian, BitReader, BitRead};
811 /// let data = [0];
812 /// let mut reader = BitReader::endian(data.as_slice(), BigEndian);
813 /// assert_eq!(reader.byte_aligned(), true);
814 /// assert!(reader.skip(1).is_ok());
815 /// assert_eq!(reader.byte_aligned(), false);
816 /// assert!(reader.skip(7).is_ok());
817 /// assert_eq!(reader.byte_aligned(), true);
818 /// ```
819 fn byte_aligned(&self) -> bool;
820
821 /// Throws away all unread bit values until the next whole byte.
822 /// Does nothing if the stream is already aligned.
823 ///
824 /// # Example
825 /// ```
826 /// use oximedia_bitstream::{BigEndian, BitReader, BitRead};
827 /// let data: &[u8] = &[0x00, 0xFF];
828 /// let mut reader = BitReader::endian(data, BigEndian);
829 /// assert_eq!(reader.read::<4, u8>().unwrap(), 0);
830 /// reader.byte_align();
831 /// assert_eq!(reader.read::<8, u8>().unwrap(), 0xFF);
832 /// ```
833 fn byte_align(&mut self);
834
835 /// Given a compiled Huffman tree, reads bits from the stream
836 /// until the next symbol is encountered.
837 ///
838 /// # Errors
839 ///
840 /// Passes along any I/O error from the underlying stream.
841 ///
842 /// # Example
843 ///
844 /// ```
845 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian, define_huffman_tree, huffman::FromBits};
846 ///
847 /// define_huffman_tree!(TreeName : char = ['a', ['b', ['c', 'd']]]);
848 /// // 'a' is 0
849 /// // 'b' is 1 -> 0
850 /// // 'c' is 1 -> 1 -> 0
851 /// // 'd' is 1 -> 1 -> 1
852 ///
853 /// let data: &[u8] = &[0b0_10_110_11, 0b1_0000000];
854 /// let mut r = BitReader::endian(data, BigEndian);
855 /// assert_eq!(r.read_huffman::<TreeName>().unwrap(), 'a');
856 /// assert_eq!(r.read_huffman::<TreeName>().unwrap(), 'b');
857 /// assert_eq!(r.read_huffman::<TreeName>().unwrap(), 'c');
858 /// assert_eq!(r.read_huffman::<TreeName>().unwrap(), 'd');
859 /// ```
860 #[inline]
861 fn read_huffman<T>(&mut self) -> io::Result<T::Symbol>
862 where
863 T: crate::huffman::FromBits,
864 {
865 T::from_bits(|| self.read_bit())
866 }
867
868 /// Reads a number using a variable using a variable width integer.
869 /// This optimises the case when the number is small.
870 ///
871 /// The integer is mapped to an unsigned value using zigzag encoding.
872 /// For an integer X:
873 /// - if X >= 0 -> 2X
874 /// - else -> -2X + 1
875 ///
876 /// # Errors
877 ///
878 /// Passes along any I/O error from the underlying stream.
879 /// Returns an error if the data read would overflow the size of the result
880 ///
881 /// # Example
882 /// ```
883 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian};
884 ///
885 /// let bytes: &[u8] = &[0b0111_1100, 0b1100_0001];
886 /// let mut r = BitReader::endian(bytes, BigEndian);
887 /// assert_eq!(r.read_unsigned_vbr::<4, u32>().unwrap(), 7);
888 /// assert_eq!(r.read_unsigned_vbr::<4, u32>().unwrap(), 100);
889 /// ```
890 /// ```
891 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian};
892 ///
893 /// let bytes: &[u8] = &[0b1111_1111, 0b0011_1000, 0b1000_0100, 0b1000_1000, 0b1000_0000];
894 /// let mut r = BitReader::endian(bytes, BigEndian);
895 /// assert_eq!(r.read_unsigned_vbr::<4, u8>().unwrap(), 255); // Tries to read <011><111><111>
896 /// assert!(r.read_unsigned_vbr::<4, u8>().is_err()); // Tries to read a value of <100><000><000>
897 /// assert!(r.read_unsigned_vbr::<4, u8>().is_err()); // Tries to read a value of <000><000><000><000>
898 /// ```
899 fn read_unsigned_vbr<const FIELD_SIZE: u32, U: UnsignedInteger>(&mut self) -> io::Result<U> {
900 const { assert!(FIELD_SIZE >= 2 && FIELD_SIZE < U::BITS_SIZE) };
901 let payload_bits = FIELD_SIZE - 1;
902 let mut value = U::ZERO;
903 let mut shift = 0u32;
904 loop {
905 let (data, continuation) = self.read_unsigned::<FIELD_SIZE, U>().map(|item| {
906 (
907 item & ((U::ONE << payload_bits) - U::ONE),
908 (item >> payload_bits) != U::ZERO,
909 )
910 })?;
911 let shifted = data << shift;
912 value |= shifted;
913 if !continuation {
914 if (data << shift) >> shift == data {
915 break Ok(value);
916 } else {
917 break Err(VariableWidthOverflow {}.into());
918 }
919 }
920 shift += payload_bits;
921 if shift >= U::BITS_SIZE {
922 break Err(VariableWidthOverflow {}.into());
923 }
924 }
925 }
926
927 /// Reads a number using a variable using a variable width integer.
928 /// This optimises the case when the number is small.
929 ///
930 /// The integer is mapped to an unsigned value using zigzag encoding.
931 /// For an integer X:
932 /// - if X >= 0 -> 2X
933 /// - else -> -2X + 1
934 ///
935 /// # Errors
936 ///
937 /// Passes along any I/O error from the underlying stream.
938 /// Returns an error if the data read would overflow the size of the result
939 ///
940 /// # Example
941 /// ```
942 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian};
943 ///
944 /// let bytes: &[u8] = &[0b0110_1011, 0b1100_0001];
945 /// let mut r = BitReader::endian(bytes, BigEndian);
946 /// assert_eq!(r.read_signed_vbr::<4, i32>().unwrap(), 3);
947 /// assert_eq!(r.read_signed_vbr::<4, i32>().unwrap(), -50);
948 /// ```
949 fn read_signed_vbr<const FIELD_SIZE: u32, I: SignedInteger>(&mut self) -> io::Result<I> {
950 self.read_unsigned_vbr::<FIELD_SIZE, I::Unsigned>()
951 .map(|zig_zag| {
952 let shifted = zig_zag >> 1;
953 let complimented = zig_zag & <I::Unsigned as crate::Numeric>::ONE;
954 let neg = I::ZERO - complimented.as_non_negative();
955 shifted.as_non_negative() ^ neg
956 })
957 }
958
959 /// Reads a signed or unsigned variable width integer from the stream.
960 ///
961 /// # Errors
962 ///
963 /// Passes along any I/O error from the underlying stream.
964 /// Returns an error if the data read would overflow the size of the result
965 ///
966 /// # Example
967 /// ```
968 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian};
969 ///
970 /// let bytes: &[u8] = &[0b0110_1011, 0b1100_0001];
971 /// let mut r = BitReader::endian(bytes, BigEndian);
972 /// assert_eq!(r.read_vbr::<4, u32>().unwrap(), 6);
973 /// assert_eq!(r.read_vbr::<4, i32>().unwrap(), -50);
974 /// ```
975 #[inline]
976 fn read_vbr<const FIELD_SIZE: u32, I: VBRInteger>(&mut self) -> io::Result<I> {
977 I::read_vbr::<FIELD_SIZE, _>(self)
978 }
979
980 /// Creates a "by reference" adaptor for this `BitRead`
981 ///
982 /// The returned adapter also implements `BitRead`
983 /// and will borrow the current reader.
984 ///
985 /// # Example
986 /// ```
987 /// use oximedia_bitstream::{BitReader, BitRead, BigEndian};
988 ///
989 /// fn parse<R: BitRead>(r: R) {
990 /// // perform some parsing
991 /// }
992 ///
993 /// let data: &[u8] = &[0];
994 /// let mut reader = BitReader::endian(data, BigEndian);
995 /// // performing parsing by reference
996 /// parse(reader.by_ref());
997 /// // original owned reader still available
998 /// assert_eq!(reader.read::<8, u8>().unwrap(), 0);
999 /// ```
1000 #[inline]
1001 fn by_ref(&mut self) -> &mut Self {
1002 self
1003 }
1004}
1005
1006impl<R: BitRead + ?Sized> BitRead for &mut R {
1007 #[inline]
1008 fn read_bit(&mut self) -> io::Result<bool> {
1009 (**self).read_bit()
1010 }
1011
1012 #[inline]
1013 fn read<const BITS: u32, I>(&mut self) -> io::Result<I>
1014 where
1015 I: Integer,
1016 {
1017 (**self).read::<BITS, I>()
1018 }
1019
1020 #[inline]
1021 fn read_var<I>(&mut self, bits: u32) -> io::Result<I>
1022 where
1023 I: Integer + Sized,
1024 {
1025 (**self).read_var(bits)
1026 }
1027
1028 #[inline]
1029 fn read_count<const MAX: u32>(&mut self) -> io::Result<BitCount<MAX>> {
1030 (**self).read_count::<MAX>()
1031 }
1032
1033 #[inline]
1034 fn read_counted<const MAX: u32, I>(&mut self, bits: BitCount<MAX>) -> io::Result<I>
1035 where
1036 I: Integer + Sized,
1037 {
1038 (**self).read_counted::<MAX, I>(bits)
1039 }
1040
1041 #[inline]
1042 fn read_unsigned<const BITS: u32, U>(&mut self) -> io::Result<U>
1043 where
1044 U: UnsignedInteger,
1045 {
1046 (**self).read_unsigned::<BITS, U>()
1047 }
1048
1049 #[inline]
1050 fn read_unsigned_var<U>(&mut self, bits: u32) -> io::Result<U>
1051 where
1052 U: UnsignedInteger,
1053 {
1054 (**self).read_unsigned_var(bits)
1055 }
1056
1057 #[inline]
1058 fn read_unsigned_counted<const MAX: u32, U>(&mut self, bits: BitCount<MAX>) -> io::Result<U>
1059 where
1060 U: UnsignedInteger,
1061 {
1062 (**self).read_unsigned_counted::<MAX, U>(bits)
1063 }
1064
1065 #[inline]
1066 fn read_signed<const BITS: u32, S>(&mut self) -> io::Result<S>
1067 where
1068 S: SignedInteger,
1069 {
1070 (**self).read_signed::<BITS, S>()
1071 }
1072
1073 #[inline]
1074 fn read_signed_var<S>(&mut self, bits: u32) -> io::Result<S>
1075 where
1076 S: SignedInteger,
1077 {
1078 (**self).read_signed_var(bits)
1079 }
1080
1081 #[inline]
1082 fn read_signed_counted<const MAX: u32, S>(
1083 &mut self,
1084 bits: impl TryInto<SignedBitCount<MAX>>,
1085 ) -> io::Result<S>
1086 where
1087 S: SignedInteger,
1088 {
1089 (**self).read_signed_counted::<MAX, S>(bits)
1090 }
1091
1092 #[inline]
1093 fn read_to<V>(&mut self) -> io::Result<V>
1094 where
1095 V: Primitive,
1096 {
1097 (**self).read_to::<V>()
1098 }
1099
1100 #[inline]
1101 fn read_as_to<F, V>(&mut self) -> io::Result<V>
1102 where
1103 F: Endianness,
1104 V: Primitive,
1105 {
1106 (**self).read_as_to::<F, V>()
1107 }
1108
1109 #[inline]
1110 fn skip(&mut self, bits: u32) -> io::Result<()> {
1111 (**self).skip(bits)
1112 }
1113
1114 #[inline]
1115 fn read_bytes(&mut self, buf: &mut [u8]) -> io::Result<()> {
1116 (**self).read_bytes(buf)
1117 }
1118
1119 #[inline]
1120 #[cfg(feature = "alloc")]
1121 fn read_to_vec(&mut self, bytes: usize) -> io::Result<Vec<u8>> {
1122 (**self).read_to_vec(bytes)
1123 }
1124
1125 #[inline]
1126 fn read_unary<const STOP_BIT: u8>(&mut self) -> io::Result<u32> {
1127 (**self).read_unary::<STOP_BIT>()
1128 }
1129
1130 #[inline]
1131 fn parse<F: FromBitStream>(&mut self) -> Result<F, F::Error> {
1132 (**self).parse::<F>()
1133 }
1134
1135 #[inline]
1136 fn parse_with<'a, F: FromBitStreamWith<'a>>(
1137 &mut self,
1138 context: &F::Context,
1139 ) -> Result<F, F::Error> {
1140 (**self).parse_with::<F>(context)
1141 }
1142
1143 #[inline]
1144 fn byte_aligned(&self) -> bool {
1145 (**self).byte_aligned()
1146 }
1147
1148 #[inline]
1149 fn byte_align(&mut self) {
1150 (**self).byte_align();
1151 }
1152
1153 #[inline]
1154 fn read_huffman<T>(&mut self) -> io::Result<T::Symbol>
1155 where
1156 T: crate::huffman::FromBits,
1157 {
1158 (**self).read_huffman::<T>()
1159 }
1160}