edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·b123ba7·Tahinli·3 months ago·1499 commits
| 1 | //! Bit-level readers and writers shared by every parser in the family. |
| 2 | //! |
| 3 | //! Two orders: MSB-first ([`BitReader`], [`BitWriter`]) for the MPEG/ITU |
| 4 | //! bitstreams and FLAC, LSB-first ([`BitReaderLsb`], [`BitWriterLsb`]) for the |
| 5 | //! Xiph formats. Readers never panic on truncated input — a short buffer is |
| 6 | //! [`Error::NeedMore`], which is also the streaming "feed me more" contract. |
| 7 | |
| 8 | use crate::error::{Error, Result}; |
| 9 | |
| 10 | /// MSB-first bit reader over a borrowed buffer. |
| 11 | #[derive(Debug, Clone)] |
| 12 | pub struct BitReader<'a> { |
| 13 | data: &'a [u8], |
| 14 | pos: u64, |
| 15 | } |
| 16 | |
| 17 | impl<'a> BitReader<'a> { |
| 18 | /// A reader positioned at the first bit of `data`. |
| 19 | pub fn new(data: &'a [u8]) -> BitReader<'a> { |
| 20 | BitReader { data, pos: 0 } |
| 21 | } |
| 22 | |
| 23 | /// Bits consumed so far. |
| 24 | pub fn bit_position(&self) -> u64 { |
| 25 | self.pos |
| 26 | } |
| 27 | |
| 28 | /// Bits left in the buffer. |
| 29 | pub fn bits_remaining(&self) -> u64 { |
| 30 | (self.data.len() as u64 * 8).saturating_sub(self.pos) |
| 31 | } |
| 32 | |
| 33 | /// True when the next bit starts a byte. |
| 34 | pub fn is_byte_aligned(&self) -> bool { |
| 35 | self.pos.is_multiple_of(8) |
| 36 | } |
| 37 | |
| 38 | /// Skip to the next byte boundary; no-op when already aligned. |
| 39 | pub fn align_to_byte(&mut self) { |
| 40 | self.pos = self.pos.div_ceil(8) * 8; |
| 41 | } |
| 42 | |
| 43 | /// Read `n` bits (`n <= 64`) into a `u64`. |
| 44 | /// |
| 45 | /// Panics if `n > 64` (a coding error, not an input error). |
| 46 | pub fn read_bits64(&mut self, n: u32) -> Result<u64> { |
| 47 | assert!(n <= 64, "read_bits64: n = {n} > 64"); |
| 48 | if self.bits_remaining() < n as u64 { |
| 49 | return Err(Error::NeedMore); |
| 50 | } |
| 51 | let mut value = 0u64; |
| 52 | let mut left = n; |
| 53 | while left > 0 { |
| 54 | let byte = self.data[(self.pos >> 3) as usize]; |
| 55 | let bit_off = (self.pos & 7) as u32; |
| 56 | let take = left.min(8 - bit_off); |
| 57 | let chunk = (byte << bit_off) >> (8 - take); |
| 58 | value = (value << take) | chunk as u64; |
| 59 | self.pos += take as u64; |
| 60 | left -= take; |
| 61 | } |
| 62 | Ok(value) |
| 63 | } |
| 64 | |
| 65 | /// Read `n` bits (`n <= 32`) into a `u32`. |
| 66 | pub fn read_bits(&mut self, n: u32) -> Result<u32> { |
| 67 | assert!(n <= 32, "read_bits: n = {n} > 32"); |
| 68 | Ok(self.read_bits64(n)? as u32) |
| 69 | } |
| 70 | |
| 71 | /// Read `n` bits as a two's-complement signed value (`1 <= n <= 32`). |
| 72 | pub fn read_signed(&mut self, n: u32) -> Result<i32> { |
| 73 | assert!((1..=32).contains(&n), "read_signed: n = {n} outside 1..=32"); |
| 74 | let raw = self.read_bits(n)?; |
| 75 | Ok(((raw << (32 - n)) as i32) >> (32 - n)) |
| 76 | } |
| 77 | |
| 78 | /// Read one bit. |
| 79 | pub fn read_bit(&mut self) -> Result<bool> { |
| 80 | Ok(self.read_bits64(1)? != 0) |
| 81 | } |
| 82 | |
| 83 | /// Read `n` bits without consuming them. |
| 84 | pub fn peek_bits(&mut self, n: u32) -> Result<u32> { |
| 85 | let saved = self.pos; |
| 86 | let v = self.read_bits(n); |
| 87 | self.pos = saved; |
| 88 | v |
| 89 | } |
| 90 | |
| 91 | /// Skip `n` bits, or [`Error::NeedMore`] if fewer remain. |
| 92 | pub fn skip_bits(&mut self, n: u64) -> Result<()> { |
| 93 | if self.bits_remaining() < n { |
| 94 | return Err(Error::NeedMore); |
| 95 | } |
| 96 | self.pos += n; |
| 97 | Ok(()) |
| 98 | } |
| 99 | |
| 100 | /// Borrow `n` whole bytes from the current position, which must be aligned. |
| 101 | pub fn read_bytes(&mut self, n: usize) -> Result<&'a [u8]> { |
| 102 | if !self.is_byte_aligned() { |
| 103 | return Err(Error::corrupt("read_bytes at a non-byte-aligned position")); |
| 104 | } |
| 105 | let start = (self.pos >> 3) as usize; |
| 106 | let end = start.checked_add(n).ok_or(Error::NeedMore)?; |
| 107 | let slice = self.data.get(start..end).ok_or(Error::NeedMore)?; |
| 108 | self.pos += n as u64 * 8; |
| 109 | Ok(slice) |
| 110 | } |
| 111 | |
| 112 | /// Unsigned exp-Golomb `ue(v)`, as used by H.264 and H.265. |
| 113 | /// |
| 114 | /// The prefix is capped at 31 zero bits: 32 or more cannot encode a value |
| 115 | /// in `u32` range, so it is a corrupt bitstream (and, on a fuzzer's input, |
| 116 | /// the difference between an error and an unbounded loop). |
| 117 | pub fn read_ue(&mut self) -> Result<u32> { |
| 118 | let mut zeros = 0u32; |
| 119 | while !self.read_bit()? { |
| 120 | zeros += 1; |
| 121 | if zeros > 31 { |
| 122 | return Err(Error::corrupt("exp-Golomb prefix longer than 31 zero bits")); |
| 123 | } |
| 124 | } |
| 125 | if zeros == 0 { |
| 126 | return Ok(0); |
| 127 | } |
| 128 | let suffix = self.read_bits(zeros)?; |
| 129 | Ok((1u32 << zeros) - 1 + suffix) |
| 130 | } |
| 131 | |
| 132 | /// Signed exp-Golomb `se(v)`. |
| 133 | pub fn read_se(&mut self) -> Result<i32> { |
| 134 | let k = self.read_ue()? as i64; |
| 135 | let v = if k % 2 == 1 { (k + 1) / 2 } else { -(k / 2) }; |
| 136 | i32::try_from(v).map_err(|_| Error::corrupt(format!("se(v) out of i32 range: {v}"))) |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | /// MSB-first bit writer. |
| 141 | #[derive(Debug, Clone, Default)] |
| 142 | pub struct BitWriter { |
| 143 | buf: Vec<u8>, |
| 144 | /// Bits already written into the last byte of `buf` (0 means byte aligned). |
| 145 | used: u32, |
| 146 | } |
| 147 | |
| 148 | impl BitWriter { |
| 149 | /// An empty writer. |
| 150 | pub fn new() -> BitWriter { |
| 151 | BitWriter::default() |
| 152 | } |
| 153 | |
| 154 | /// An empty writer with room for `bytes`. |
| 155 | pub fn with_capacity(bytes: usize) -> BitWriter { |
| 156 | BitWriter { |
| 157 | buf: Vec::with_capacity(bytes), |
| 158 | used: 0, |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | /// Bits written so far. |
| 163 | pub fn bit_len(&self) -> u64 { |
| 164 | if self.used == 0 { |
| 165 | self.buf.len() as u64 * 8 |
| 166 | } else { |
| 167 | (self.buf.len() as u64 - 1) * 8 + self.used as u64 |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | /// True when the next bit would start a byte. |
| 172 | pub fn is_byte_aligned(&self) -> bool { |
| 173 | self.used == 0 |
| 174 | } |
| 175 | |
| 176 | /// Write the low `n` bits of `value` (`n <= 64`), most significant first. |
| 177 | pub fn write_bits64(&mut self, value: u64, n: u32) { |
| 178 | assert!(n <= 64, "write_bits64: n = {n} > 64"); |
| 179 | for i in (0..n).rev() { |
| 180 | self.write_bit(value >> i & 1 == 1); |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | /// Write the low `n` bits of `value` (`n <= 32`), most significant first. |
| 185 | pub fn write_bits(&mut self, value: u32, n: u32) { |
| 186 | assert!(n <= 32, "write_bits: n = {n} > 32"); |
| 187 | self.write_bits64(value as u64, n); |
| 188 | } |
| 189 | |
| 190 | /// Write a two's-complement signed value in `n` bits (`1 <= n <= 32`). |
| 191 | pub fn write_signed(&mut self, value: i32, n: u32) { |
| 192 | assert!( |
| 193 | (1..=32).contains(&n), |
| 194 | "write_signed: n = {n} outside 1..=32" |
| 195 | ); |
| 196 | self.write_bits((value as u32) & (u32::MAX >> (32 - n)), n); |
| 197 | } |
| 198 | |
| 199 | /// Write one bit. |
| 200 | pub fn write_bit(&mut self, bit: bool) { |
| 201 | if self.used == 0 { |
| 202 | self.buf.push(0); |
| 203 | } |
| 204 | if bit { |
| 205 | let last = self.buf.len() - 1; |
| 206 | self.buf[last] |= 0x80 >> self.used; |
| 207 | } |
| 208 | self.used = (self.used + 1) % 8; |
| 209 | } |
| 210 | |
| 211 | /// Pad with zero bits up to the next byte boundary. |
| 212 | pub fn align_to_byte(&mut self) { |
| 213 | while self.used != 0 { |
| 214 | self.write_bit(false); |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | /// Unsigned exp-Golomb `ue(v)`. |
| 219 | /// |
| 220 | /// Panics on `u32::MAX`, which has no exp-Golomb form that reads back into |
| 221 | /// `u32`; no codec in the family emits it. |
| 222 | pub fn write_ue(&mut self, value: u32) { |
| 223 | assert!(value != u32::MAX, "write_ue: u32::MAX is not encodable"); |
| 224 | let x = value as u64 + 1; |
| 225 | let bits = 64 - x.leading_zeros(); |
| 226 | self.write_bits64(0, bits - 1); |
| 227 | self.write_bits64(x, bits); |
| 228 | } |
| 229 | |
| 230 | /// Signed exp-Golomb `se(v)`. |
| 231 | pub fn write_se(&mut self, value: i32) { |
| 232 | let k = if value > 0 { |
| 233 | 2 * value as i64 - 1 |
| 234 | } else { |
| 235 | -2 * value as i64 |
| 236 | }; |
| 237 | let k = u32::try_from(k).expect("se(v) out of exp-Golomb range"); |
| 238 | self.write_ue(k); |
| 239 | } |
| 240 | |
| 241 | /// Append whole bytes; the writer must be byte aligned. |
| 242 | /// |
| 243 | /// Panics when misaligned — call [`BitWriter::align_to_byte`] first. |
| 244 | pub fn write_bytes(&mut self, bytes: &[u8]) { |
| 245 | assert!(self.is_byte_aligned(), "write_bytes while not byte aligned"); |
| 246 | self.buf.extend_from_slice(bytes); |
| 247 | } |
| 248 | |
| 249 | /// The bytes written so far; a trailing partial byte is zero padded. |
| 250 | pub fn as_bytes(&self) -> &[u8] { |
| 251 | &self.buf |
| 252 | } |
| 253 | |
| 254 | /// Consume the writer, returning its bytes. |
| 255 | pub fn into_bytes(self) -> Vec<u8> { |
| 256 | self.buf |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | /// LSB-first bit reader (Vorbis, and other Xiph-family bitstreams). |
| 261 | #[derive(Debug, Clone)] |
| 262 | pub struct BitReaderLsb<'a> { |
| 263 | data: &'a [u8], |
| 264 | pos: u64, |
| 265 | } |
| 266 | |
| 267 | impl<'a> BitReaderLsb<'a> { |
| 268 | /// A reader positioned at the first bit of `data`. |
| 269 | pub fn new(data: &'a [u8]) -> BitReaderLsb<'a> { |
| 270 | BitReaderLsb { data, pos: 0 } |
| 271 | } |
| 272 | |
| 273 | /// Bits consumed so far. |
| 274 | pub fn bit_position(&self) -> u64 { |
| 275 | self.pos |
| 276 | } |
| 277 | |
| 278 | /// Bits left in the buffer. |
| 279 | pub fn bits_remaining(&self) -> u64 { |
| 280 | (self.data.len() as u64 * 8).saturating_sub(self.pos) |
| 281 | } |
| 282 | |
| 283 | /// True when the next bit starts a byte. |
| 284 | pub fn is_byte_aligned(&self) -> bool { |
| 285 | self.pos.is_multiple_of(8) |
| 286 | } |
| 287 | |
| 288 | /// Skip to the next byte boundary; no-op when already aligned. |
| 289 | pub fn align_to_byte(&mut self) { |
| 290 | self.pos = self.pos.div_ceil(8) * 8; |
| 291 | } |
| 292 | |
| 293 | /// Read `n` bits (`n <= 64`), least significant bit first. |
| 294 | pub fn read_bits64(&mut self, n: u32) -> Result<u64> { |
| 295 | assert!(n <= 64, "read_bits64: n = {n} > 64"); |
| 296 | if self.bits_remaining() < n as u64 { |
| 297 | return Err(Error::NeedMore); |
| 298 | } |
| 299 | let mut value = 0u64; |
| 300 | let mut got = 0u32; |
| 301 | while got < n { |
| 302 | let byte = self.data[(self.pos >> 3) as usize]; |
| 303 | let bit_off = (self.pos & 7) as u32; |
| 304 | let take = (n - got).min(8 - bit_off); |
| 305 | let mask = ((1u16 << take) - 1) as u8; |
| 306 | let chunk = (byte >> bit_off) & mask; |
| 307 | value |= (chunk as u64) << got; |
| 308 | self.pos += take as u64; |
| 309 | got += take; |
| 310 | } |
| 311 | Ok(value) |
| 312 | } |
| 313 | |
| 314 | /// Read `n` bits (`n <= 32`), least significant bit first. |
| 315 | pub fn read_bits(&mut self, n: u32) -> Result<u32> { |
| 316 | assert!(n <= 32, "read_bits: n = {n} > 32"); |
| 317 | Ok(self.read_bits64(n)? as u32) |
| 318 | } |
| 319 | |
| 320 | /// Read one bit. |
| 321 | pub fn read_bit(&mut self) -> Result<bool> { |
| 322 | Ok(self.read_bits64(1)? != 0) |
| 323 | } |
| 324 | |
| 325 | /// Skip `n` bits, or [`Error::NeedMore`] if fewer remain. |
| 326 | pub fn skip_bits(&mut self, n: u64) -> Result<()> { |
| 327 | if self.bits_remaining() < n { |
| 328 | return Err(Error::NeedMore); |
| 329 | } |
| 330 | self.pos += n; |
| 331 | Ok(()) |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | /// LSB-first bit writer. |
| 336 | #[derive(Debug, Clone, Default)] |
| 337 | pub struct BitWriterLsb { |
| 338 | buf: Vec<u8>, |
| 339 | used: u32, |
| 340 | } |
| 341 | |
| 342 | impl BitWriterLsb { |
| 343 | /// An empty writer. |
| 344 | pub fn new() -> BitWriterLsb { |
| 345 | BitWriterLsb::default() |
| 346 | } |
| 347 | |
| 348 | /// Bits written so far. |
| 349 | pub fn bit_len(&self) -> u64 { |
| 350 | if self.used == 0 { |
| 351 | self.buf.len() as u64 * 8 |
| 352 | } else { |
| 353 | (self.buf.len() as u64 - 1) * 8 + self.used as u64 |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | /// True when the next bit would start a byte. |
| 358 | pub fn is_byte_aligned(&self) -> bool { |
| 359 | self.used == 0 |
| 360 | } |
| 361 | |
| 362 | /// Write the low `n` bits of `value` (`n <= 64`), least significant first. |
| 363 | pub fn write_bits64(&mut self, value: u64, n: u32) { |
| 364 | assert!(n <= 64, "write_bits64: n = {n} > 64"); |
| 365 | for i in 0..n { |
| 366 | self.write_bit(value >> i & 1 == 1); |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | /// Write the low `n` bits of `value` (`n <= 32`), least significant first. |
| 371 | pub fn write_bits(&mut self, value: u32, n: u32) { |
| 372 | assert!(n <= 32, "write_bits: n = {n} > 32"); |
| 373 | self.write_bits64(value as u64, n); |
| 374 | } |
| 375 | |
| 376 | /// Write one bit. |
| 377 | pub fn write_bit(&mut self, bit: bool) { |
| 378 | if self.used == 0 { |
| 379 | self.buf.push(0); |
| 380 | } |
| 381 | if bit { |
| 382 | let last = self.buf.len() - 1; |
| 383 | self.buf[last] |= 1 << self.used; |
| 384 | } |
| 385 | self.used = (self.used + 1) % 8; |
| 386 | } |
| 387 | |
| 388 | /// Pad with zero bits up to the next byte boundary. |
| 389 | pub fn align_to_byte(&mut self) { |
| 390 | while self.used != 0 { |
| 391 | self.write_bit(false); |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | /// The bytes written so far; a trailing partial byte is zero padded. |
| 396 | pub fn as_bytes(&self) -> &[u8] { |
| 397 | &self.buf |
| 398 | } |
| 399 | |
| 400 | /// Consume the writer, returning its bytes. |
| 401 | pub fn into_bytes(self) -> Vec<u8> { |
| 402 | self.buf |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | #[cfg(test)] |
| 407 | mod tests { |
| 408 | use super::*; |
| 409 | |
| 410 | #[test] |
| 411 | fn msb_round_trip_mixed_widths() { |
| 412 | let widths = [1u32, 2, 3, 5, 7, 8, 9, 13, 16, 17, 24, 31, 32]; |
| 413 | let mut w = BitWriter::new(); |
| 414 | let mut values = Vec::new(); |
| 415 | for (i, &n) in widths.iter().enumerate() { |
| 416 | let v = if n == 32 { |
| 417 | u32::MAX |
| 418 | } else { |
| 419 | ((0xDEAD_BEEFu64 >> i) as u32) & (u32::MAX >> (32 - n)) |
| 420 | }; |
| 421 | values.push(v); |
| 422 | w.write_bits(v, n); |
| 423 | } |
| 424 | let bits = w.bit_len(); |
| 425 | let bytes = w.into_bytes(); |
| 426 | let mut r = BitReader::new(&bytes); |
| 427 | for (&n, &v) in widths.iter().zip(&values) { |
| 428 | assert_eq!(r.read_bits(n).unwrap(), v, "width {n}"); |
| 429 | } |
| 430 | assert_eq!(r.bit_position(), bits); |
| 431 | } |
| 432 | |
| 433 | #[test] |
| 434 | fn msb_bit_order_is_most_significant_first() { |
| 435 | let mut w = BitWriter::new(); |
| 436 | w.write_bits(0b101, 3); |
| 437 | w.align_to_byte(); |
| 438 | assert_eq!(w.as_bytes(), &[0b1010_0000]); |
| 439 | let mut r = BitReader::new(&[0b1010_0000]); |
| 440 | assert!(r.read_bit().unwrap()); |
| 441 | assert!(!r.read_bit().unwrap()); |
| 442 | assert!(r.read_bit().unwrap()); |
| 443 | assert!(!r.is_byte_aligned()); |
| 444 | r.align_to_byte(); |
| 445 | assert!(r.is_byte_aligned()); |
| 446 | assert_eq!(r.bits_remaining(), 0); |
| 447 | } |
| 448 | |
| 449 | #[test] |
| 450 | fn exp_golomb_round_trip_including_edges() { |
| 451 | // 0 is a single '1' bit; the top of the range is 31 zeros + suffix. |
| 452 | let values = [ |
| 453 | 0u32, |
| 454 | 1, |
| 455 | 2, |
| 456 | 3, |
| 457 | 255, |
| 458 | 256, |
| 459 | 65_535, |
| 460 | (1 << 31) - 2, |
| 461 | (1 << 31) - 1, |
| 462 | u32::MAX - 2, |
| 463 | u32::MAX - 1, |
| 464 | ]; |
| 465 | for &v in &values { |
| 466 | let mut w = BitWriter::new(); |
| 467 | w.write_ue(v); |
| 468 | let bits = w.bit_len(); |
| 469 | let bytes = w.into_bytes(); |
| 470 | let mut r = BitReader::new(&bytes); |
| 471 | assert_eq!(r.read_ue().unwrap(), v, "ue({v})"); |
| 472 | assert_eq!(r.bit_position(), bits, "ue({v}) length"); |
| 473 | } |
| 474 | let mut w = BitWriter::new(); |
| 475 | w.write_ue(0); |
| 476 | w.align_to_byte(); |
| 477 | assert_eq!(w.as_bytes(), &[0b1000_0000]); |
| 478 | } |
| 479 | |
| 480 | #[test] |
| 481 | fn signed_exp_golomb_round_trip() { |
| 482 | for v in [ |
| 483 | 0i32, |
| 484 | 1, |
| 485 | -1, |
| 486 | 2, |
| 487 | -2, |
| 488 | 1000, |
| 489 | -1000, |
| 490 | i32::MAX / 2, |
| 491 | -(i32::MAX / 2), |
| 492 | ] { |
| 493 | let mut w = BitWriter::new(); |
| 494 | w.write_se(v); |
| 495 | let bytes = w.into_bytes(); |
| 496 | assert_eq!(BitReader::new(&bytes).read_se().unwrap(), v, "se({v})"); |
| 497 | } |
| 498 | } |
| 499 | |
| 500 | #[test] |
| 501 | fn truncation_is_need_more_never_panic() { |
| 502 | let mut r = BitReader::new(&[0xFF, 0xFF]); |
| 503 | assert!(r.read_bits(16).is_ok()); |
| 504 | assert!(r.read_bits(1).unwrap_err().is_need_more()); |
| 505 | assert!(BitReader::new(&[]).read_bit().unwrap_err().is_need_more()); |
| 506 | assert!( |
| 507 | BitReader::new(&[0x80]) |
| 508 | .read_bits(9) |
| 509 | .unwrap_err() |
| 510 | .is_need_more() |
| 511 | ); |
| 512 | // A ue() whose suffix is cut off, and one with no terminating 1 bit. |
| 513 | assert!( |
| 514 | BitReader::new(&[0x01]) |
| 515 | .read_ue() |
| 516 | .unwrap_err() |
| 517 | .is_need_more() |
| 518 | ); |
| 519 | assert!( |
| 520 | BitReader::new(&[0x00, 0x00]) |
| 521 | .read_ue() |
| 522 | .unwrap_err() |
| 523 | .is_need_more() |
| 524 | ); |
| 525 | // 32+ zero bits before the 1: corrupt, not an infinite scan. |
| 526 | let long = [0u8, 0, 0, 0, 0x80]; |
| 527 | let err = BitReader::new(&long).read_ue().unwrap_err(); |
| 528 | assert!(matches!(err, Error::Corrupt { .. }), "{err}"); |
| 529 | } |
| 530 | |
| 531 | #[test] |
| 532 | fn signed_fixed_width_and_bytes() { |
| 533 | let mut w = BitWriter::new(); |
| 534 | w.write_signed(-3, 8); |
| 535 | w.write_signed(7, 5); |
| 536 | w.align_to_byte(); |
| 537 | w.write_bytes(&[0xAB, 0xCD]); |
| 538 | let bytes = w.into_bytes(); |
| 539 | let mut r = BitReader::new(&bytes); |
| 540 | assert_eq!(r.read_signed(8).unwrap(), -3); |
| 541 | assert_eq!(r.read_signed(5).unwrap(), 7); |
| 542 | r.align_to_byte(); |
| 543 | assert_eq!(r.read_bytes(2).unwrap(), &[0xAB, 0xCD]); |
| 544 | assert!(r.read_bytes(1).unwrap_err().is_need_more()); |
| 545 | // Misaligned byte reads are refused rather than silently realigned. |
| 546 | let mut r = BitReader::new(&bytes); |
| 547 | r.read_bit().unwrap(); |
| 548 | assert!(matches!(r.read_bytes(1), Err(Error::Corrupt { .. }))); |
| 549 | } |
| 550 | |
| 551 | #[test] |
| 552 | fn peek_and_skip_do_not_diverge() { |
| 553 | let mut r = BitReader::new(&[0b1011_0010, 0xFF]); |
| 554 | assert_eq!(r.peek_bits(4).unwrap(), 0b1011); |
| 555 | assert_eq!(r.bit_position(), 0); |
| 556 | r.skip_bits(4).unwrap(); |
| 557 | assert_eq!(r.read_bits(4).unwrap(), 0b0010); |
| 558 | assert!(r.skip_bits(9).is_err()); |
| 559 | assert_eq!(r.bits_remaining(), 8); |
| 560 | } |
| 561 | |
| 562 | #[test] |
| 563 | fn lsb_round_trip_and_order() { |
| 564 | let mut w = BitWriterLsb::new(); |
| 565 | w.write_bits(0b101, 3); |
| 566 | w.align_to_byte(); |
| 567 | assert_eq!(w.as_bytes(), &[0b0000_0101]); |
| 568 | |
| 569 | let widths = [1u32, 4, 7, 11, 16, 32]; |
| 570 | let mut w = BitWriterLsb::new(); |
| 571 | let mut values = Vec::new(); |
| 572 | for (i, &n) in widths.iter().enumerate() { |
| 573 | let v = ((0xCAFE_F00Du64 >> i) as u32) & (u32::MAX >> (32 - n)); |
| 574 | values.push(v); |
| 575 | w.write_bits(v, n); |
| 576 | } |
| 577 | let bytes = w.into_bytes(); |
| 578 | let mut r = BitReaderLsb::new(&bytes); |
| 579 | for (&n, &v) in widths.iter().zip(&values) { |
| 580 | assert_eq!(r.read_bits(n).unwrap(), v, "lsb width {n}"); |
| 581 | } |
| 582 | assert_eq!(r.bits_remaining(), 1); // 71 bits written, padded to 9 bytes |
| 583 | } |
| 584 | |
| 585 | #[test] |
| 586 | fn lsb_truncation_is_need_more() { |
| 587 | let mut r = BitReaderLsb::new(&[0x0F]); |
| 588 | assert_eq!(r.read_bits(4).unwrap(), 0x0F); |
| 589 | assert!(r.read_bits(5).unwrap_err().is_need_more()); |
| 590 | assert!(r.skip_bits(5).is_err()); |
| 591 | r.align_to_byte(); |
| 592 | assert_eq!(r.bits_remaining(), 0); |
| 593 | } |
| 594 | } |