1use std::borrow::Cow;
20
21#[derive(Clone, Copy, PartialEq, Eq, Debug, thiserror::Error)]
23pub enum BitError {
24 #[error("read of {width} bit(s) at bit {position} exceeds the {available}-bit buffer")]
26 OutOfBounds {
27 position: usize,
29 width: usize,
31 available: usize,
33 },
34
35 #[error("integer read of {width} bits exceeds the 64-bit maximum")]
37 TooWide {
38 width: u32,
40 },
41}
42
43#[derive(Clone, Copy, Debug)]
45pub struct BitCursor<'a> {
46 data: &'a [u8],
47 position: usize,
48}
49
50impl<'a> BitCursor<'a> {
51 #[must_use]
53 pub const fn new(data: &'a [u8]) -> Self {
54 Self { data, position: 0 }
55 }
56
57 #[must_use]
59 pub const fn data(&self) -> &'a [u8] {
60 self.data
61 }
62
63 #[must_use]
65 pub const fn position(&self) -> usize {
66 self.position
67 }
68
69 #[must_use]
71 pub const fn len_bits(&self) -> usize {
72 self.data.len() * 8
73 }
74
75 #[must_use]
77 pub const fn remaining(&self) -> usize {
78 self.len_bits().saturating_sub(self.position)
79 }
80
81 pub const fn seek(&mut self, position: usize) {
86 self.position = position;
87 }
88
89 pub fn skip(&mut self, bits: usize) -> Result<(), BitError> {
95 let end = self.position.saturating_add(bits);
96 if end > self.len_bits() {
97 return Err(BitError::OutOfBounds {
98 position: self.position,
99 width: bits,
100 available: self.len_bits(),
101 });
102 }
103 self.position = end;
104 Ok(())
105 }
106
107 #[inline]
116 pub fn read_uint(&mut self, width: u32) -> Result<u64, BitError> {
117 let value = self.peek_uint(self.position, width)?;
118 self.position += width as usize;
119 Ok(value)
120 }
121
122 #[inline]
129 pub fn peek_uint(&self, position: usize, width: u32) -> Result<u64, BitError> {
130 if width > 64 {
131 return Err(BitError::TooWide { width });
132 }
133 if width == 0 {
134 return Ok(0);
135 }
136 let end = position.saturating_add(width as usize);
137 if end > self.len_bits() {
138 return Err(BitError::OutOfBounds {
139 position,
140 width: width as usize,
141 available: self.len_bits(),
142 });
143 }
144
145 let byte = position / 8;
146 let bit_in_byte = (position % 8) as u32;
147
148 let window = if let Some(slice) = self.data.get(byte..byte + 16) {
154 let mut buf = [0u8; 16];
155 buf.copy_from_slice(slice);
156 u128::from_be_bytes(buf)
157 } else {
158 let mut buf = [0u8; 16];
159 let tail = self.data.get(byte..).unwrap_or_default();
160 let take = tail.len().min(16);
161 if let (Some(dst), Some(src)) = (buf.get_mut(..take), tail.get(..take)) {
162 dst.copy_from_slice(src);
163 }
164 u128::from_be_bytes(buf)
165 };
166
167 let shift = 128 - u32::from(bit_in_byte as u8) - width;
168 let mask = if width == 64 {
169 u64::MAX
170 } else {
171 (1u64 << width) - 1
172 };
173 Ok(((window >> shift) as u64) & mask)
174 }
175
176 #[inline]
182 pub fn peek_next(&self, width: u32) -> Result<u64, BitError> {
183 self.peek_uint(self.position, width)
184 }
185
186 pub fn read_bytes(&mut self, width: usize) -> Result<Cow<'a, [u8]>, BitError> {
199 let out_len = width.div_ceil(8);
200 let pad = out_len * 8 - width;
201
202 if let Some(slice) = self.aligned_slice(width) {
203 return Ok(Cow::Borrowed(slice));
204 }
205
206 let start = self.position;
207 self.bounds_check(width)?;
208
209 let mut out = vec![0u8; out_len];
210 for (index, slot) in out.iter_mut().enumerate() {
211 let (from, take) = match (index * 8).checked_sub(pad) {
214 Some(offset) => (start + offset, 8),
215 None => (start, 8 - pad as u32),
216 };
217 *slot = self.peek_uint(from, take)? as u8;
218 }
219 self.position = start + width;
220 Ok(Cow::Owned(out))
221 }
222
223 pub fn read_bytes_left_aligned(&mut self, width: usize) -> Result<Cow<'a, [u8]>, BitError> {
233 if let Some(slice) = self.aligned_slice(width) {
234 return Ok(Cow::Borrowed(slice));
235 }
236
237 let start = self.position;
238 self.bounds_check(width)?;
239
240 let out_len = width.div_ceil(8);
241 let mut out = vec![0u8; out_len];
242 for (index, slot) in out.iter_mut().enumerate() {
243 let offset = index * 8;
244 let take = u32::try_from(width - offset).unwrap_or(8).min(8);
245 *slot = (self.peek_uint(start + offset, take)? as u8) << (8 - take);
248 }
249 self.position = start + width;
250 Ok(Cow::Owned(out))
251 }
252
253 fn aligned_slice(&mut self, width: usize) -> Option<&'a [u8]> {
256 if self.position % 8 != 0 || width % 8 != 0 {
257 return None;
258 }
259 let start = self.position / 8;
260 let end = start.checked_add(width / 8)?;
261 let slice = self.data.get(start..end)?;
262 self.position += width;
263 Some(slice)
264 }
265
266 fn bounds_check(&self, width: usize) -> Result<(), BitError> {
267 let end = self.position.saturating_add(width);
268 if end > self.len_bits() {
269 return Err(BitError::OutOfBounds {
270 position: self.position,
271 width,
272 available: self.len_bits(),
273 });
274 }
275 Ok(())
276 }
277}
278
279#[must_use]
287pub fn twos_complement(value: u64, width: u32) -> i64 {
288 if width == 0 || width > 64 {
289 return value as i64;
290 }
291 let shift = 64 - width;
292 ((value << shift) as i64) >> shift
293}
294
295#[must_use]
310pub fn twos_complement_unmasked(value: u64, width: u32) -> Option<i64> {
311 if width == 0 || width >= 64 {
314 return Some(value as i64);
315 }
316 if value & (1u64 << (width - 1)) == 0 {
317 return i64::try_from(value).ok();
318 }
319 i64::try_from(i128::from(value) - (1i128 << width)).ok()
322}
323
324#[must_use]
327pub fn sign_magnitude(value: u64, width: u32) -> i64 {
328 if width == 0 || width > 64 {
329 return value as i64;
330 }
331 let sign_bit = 1u64 << (width - 1);
332 let magnitude = (value & (sign_bit - 1)) as i64;
333 if value & sign_bit == 0 {
334 magnitude
335 } else {
336 -magnitude
337 }
338}
339
340#[must_use]
342pub fn ones_complement(value: u64, width: u32) -> i64 {
343 if width == 0 || width > 64 {
344 return value as i64;
345 }
346 let sign_bit = 1u64 << (width - 1);
347 if value & sign_bit == 0 {
348 value as i64
349 } else {
350 let mask = if width == 64 {
351 u64::MAX
352 } else {
353 (1u64 << width) - 1
354 };
355 -(((!value) & mask) as i64)
356 }
357}
358
359#[must_use]
365pub fn swap_byte_order(value: u64, width: u32) -> u64 {
366 let bytes = (width as usize).div_ceil(8);
367 if bytes <= 1 {
368 return value;
369 }
370 let mut out = 0u64;
371 let mut remaining = value;
372 for _ in 0..bytes {
373 out = (out << 8) | (remaining & 0xFF);
374 remaining >>= 8;
375 }
376 out
377}
378
379#[cfg(test)]
380mod tests {
381 use super::*;
382
383 fn naive_read(data: &[u8], position: usize, width: u32) -> Option<u64> {
386 if position + width as usize > data.len() * 8 {
387 return None;
388 }
389 let mut value: u64 = 0;
390 for offset in 0..width as usize {
391 let bit_index = position + offset;
392 let byte = *data.get(bit_index / 8)?;
393 let bit = (byte >> (7 - (bit_index % 8))) & 1;
394 value = (value << 1) | u64::from(bit);
395 }
396 Some(value)
397 }
398
399 #[test]
400 fn documented_example_matches() {
401 let data = [0b0011_0101u8, 0b1100_1010];
403 let mut cursor = BitCursor::new(&data);
404 cursor.seek(2);
405 assert_eq!(cursor.read_uint(9), Ok(0b1_1010_1110));
406 assert_eq!(cursor.position(), 11);
407 }
408
409 #[test]
410 fn sixty_four_bits_at_a_bit_offset_spans_nine_bytes() {
411 let data: [u8; 9] = [0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF];
413 for offset in 0..8 {
414 let mut cursor = BitCursor::new(&data);
415 cursor.seek(offset);
416 let got = cursor.read_uint(64).expect("in range");
417 let want = naive_read(&data, offset, 64).expect("in range");
418 assert_eq!(got, want, "offset {offset}");
419 }
420 }
421
422 #[test]
423 fn reads_past_the_end_are_errors_not_panics() {
424 let data = [0xAAu8; 2];
425 let mut cursor = BitCursor::new(&data);
426 cursor.seek(9);
427 assert!(matches!(
428 cursor.read_uint(8),
429 Err(BitError::OutOfBounds { .. })
430 ));
431 assert!(matches!(
432 cursor.read_uint(65),
433 Err(BitError::TooWide { .. })
434 ));
435
436 let mut empty = BitCursor::new(&[]);
437 assert!(matches!(
438 empty.read_uint(1),
439 Err(BitError::OutOfBounds { .. })
440 ));
441 assert_eq!(empty.read_uint(0), Ok(0));
442 }
443
444 #[test]
445 fn aligned_byte_reads_borrow() {
446 let data = [1u8, 2, 3, 4];
447 let mut cursor = BitCursor::new(&data);
448 let bytes = cursor.read_bytes(16).expect("in range");
449 assert!(matches!(bytes, Cow::Borrowed(_)));
450 assert_eq!(&*bytes, &[1, 2]);
451 assert_eq!(cursor.position(), 16);
452 }
453
454 #[test]
455 fn unaligned_bytes_are_right_aligned() {
456 let data = [0xABu8, 0xCD];
458 let mut cursor = BitCursor::new(&data);
459 cursor.seek(4);
460 let bytes = cursor.read_bytes(12).expect("in range");
461 assert_eq!(&*bytes, &[0x0B, 0xCD]);
462 }
463
464 #[test]
465 fn left_aligned_bytes_pad_on_the_right() {
466 let data = [0xABu8, 0xCD];
468 let mut cursor = BitCursor::new(&data);
469 cursor.seek(4);
470 let bytes = cursor.read_bytes_left_aligned(12).expect("in range");
471 assert_eq!(&*bytes, &[0xBC, 0xD0]);
472 }
473
474 fn naive_twos_complement(value: u64, width: u32) -> i128 {
476 let modulus = 1i128 << width;
477 let value = i128::from(value) % modulus;
478 if value >= modulus / 2 {
479 value - modulus
480 } else {
481 value
482 }
483 }
484
485 #[test]
486 fn signed_interpretations() {
487 assert_eq!(twos_complement(0xFF, 8), -1);
488 assert_eq!(twos_complement(0x80, 8), -128);
489 assert_eq!(twos_complement(0x7F, 8), 127);
490 assert_eq!(twos_complement(u64::MAX, 64), -1);
491 assert_eq!(twos_complement(1 << 62, 63), -(1i64 << 62));
493 assert_eq!(twos_complement((1 << 62) - 1, 63), (1i64 << 62) - 1);
494 assert_eq!(twos_complement(u64::MAX >> 1, 63), -1);
495 assert_eq!(twos_complement(1, 1), -1);
496 assert_eq!(twos_complement(0, 1), 0);
497
498 assert_eq!(sign_magnitude(0b1000_0001, 8), -1);
499 assert_eq!(sign_magnitude(0b0000_0001, 8), 1);
500
501 assert_eq!(ones_complement(0b1111_1110, 8), -1);
502 assert_eq!(ones_complement(0b0000_0001, 8), 1);
503 }
504
505 #[test]
506 fn byte_order_swap() {
507 assert_eq!(swap_byte_order(0x1234, 16), 0x3412);
508 assert_eq!(swap_byte_order(0x12345678, 32), 0x78563412);
509 assert_eq!(swap_byte_order(0x12, 8), 0x12);
510 }
511
512 proptest::proptest! {
513 #[test]
517 fn matches_naive_reference(
518 data in proptest::collection::vec(proptest::num::u8::ANY, 1..24),
519 offset_seed in 0usize..200,
520 width in 0u32..=64,
521 ) {
522 let total_bits = data.len() * 8;
523 let offset = offset_seed % (total_bits + 1);
524 let mut cursor = BitCursor::new(&data);
525 cursor.seek(offset);
526 let got = cursor.read_uint(width);
527 match naive_read(&data, offset, width) {
528 Some(want) => {
529 proptest::prop_assert_eq!(got, Ok(want));
530 proptest::prop_assert_eq!(cursor.position(), offset + width as usize);
531 }
532 None => proptest::prop_assert!(got.is_err()),
533 }
534 }
535
536 #[test]
537 fn wide_reads_at_every_bit_offset(
538 data in proptest::collection::vec(proptest::num::u8::ANY, 9..17),
539 offset in 0usize..8,
540 width in 57u32..=64,
541 ) {
542 let mut cursor = BitCursor::new(&data);
543 cursor.seek(offset);
544 let want = naive_read(&data, offset, width).expect("buffer is long enough");
545 proptest::prop_assert_eq!(cursor.read_uint(width), Ok(want));
546 }
547
548 #[test]
549 fn bytes_and_integers_agree(
550 data in proptest::collection::vec(proptest::num::u8::ANY, 1..20),
551 offset_seed in 0usize..200,
552 width in 1usize..=64,
553 ) {
554 let total_bits = data.len() * 8;
555 let offset = offset_seed % (total_bits + 1);
556 if offset + width > total_bits {
557 return Ok(());
558 }
559 let mut as_int = BitCursor::new(&data);
560 as_int.seek(offset);
561 let integer = as_int.read_uint(width as u32).expect("in range");
562
563 let mut as_bytes = BitCursor::new(&data);
564 as_bytes.seek(offset);
565 let bytes = as_bytes.read_bytes(width).expect("in range");
566
567 let mut rebuilt = 0u64;
568 for byte in bytes.iter() {
569 rebuilt = (rebuilt << 8) | u64::from(*byte);
570 }
571 proptest::prop_assert_eq!(rebuilt, integer);
572 proptest::prop_assert_eq!(as_int.position(), as_bytes.position());
573 }
574
575 #[test]
578 fn twos_complement_matches_naive_reference(
579 bits in proptest::num::u64::ANY,
580 width in 1u32..=64,
581 ) {
582 let mask = if width == 64 { u64::MAX } else { (1u64 << width) - 1 };
583 let value = bits & mask;
584 proptest::prop_assert_eq!(
585 i128::from(twos_complement(value, width)),
586 naive_twos_complement(value, width),
587 "value {} width {}", value, width
588 );
589 }
590
591 #[test]
594 fn unmasked_sign_extension_agrees_within_the_field(
595 bits in proptest::num::u64::ANY,
596 width in 1u32..=64,
597 ) {
598 let mask = if width == 64 { u64::MAX } else { (1u64 << width) - 1 };
599 let value = bits & mask;
600 proptest::prop_assert_eq!(
601 twos_complement_unmasked(value, width),
602 Some(twos_complement(value, width)),
603 "value {} width {}", value, width
604 );
605 }
606
607 #[test]
608 fn unmasked_sign_extension_keeps_the_high_bits(
609 bits in proptest::num::u64::ANY,
610 width in 1u32..=56,
611 ) {
612 let expected = if bits & (1u64 << (width - 1)) == 0 {
614 i128::from(bits)
615 } else {
616 i128::from(bits) - (1i128 << width)
617 };
618 proptest::prop_assert_eq!(
619 twos_complement_unmasked(bits, width).map(i128::from),
620 i64::try_from(expected).ok().map(i128::from),
621 "value {} width {}", bits, width
622 );
623 }
624
625 #[test]
626 fn failures_leave_the_cursor_untouched(
627 data in proptest::collection::vec(proptest::num::u8::ANY, 0..8),
628 offset in 0usize..200,
629 width in 0u32..=80,
630 ) {
631 let mut cursor = BitCursor::new(&data);
632 cursor.seek(offset);
633 if cursor.read_uint(width).is_err() {
634 proptest::prop_assert_eq!(cursor.position(), offset);
635 }
636 }
637 }
638}