pbdems2 0.4.2

Game-neutral Source 2 PBDEMS2 demo parsing primitives
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
use crate::error::{Error, Result};

// Source 2 coordinate encoding constants. A coordinate is encoded as an
// optional integer part (14 bits) plus an optional fractional part (5 bits).
const COORD_INTEGER_BITS: usize = 14;
const COORD_FRACTIONAL_BITS: usize = 5;
const COORD_DENOMINATOR: f32 = (1 << COORD_FRACTIONAL_BITS) as f32;
const COORD_RESOLUTION: f32 = 1.0 / COORD_DENOMINATOR;

// Source 2 normal encoding constants. A normal component is a sign bit
// followed by an 11-bit fractional value in [0, 1].
const NORMAL_FRACTIONAL_BITS: usize = 11;
const NORMAL_DENOMINATOR: f32 = ((1 << NORMAL_FRACTIONAL_BITS) - 1) as f32;
const NORMAL_RESOLUTION: f32 = 1.0 / NORMAL_DENOMINATOR;

/// High-performance bit-level reader over a byte slice.
///
/// Uses safe unaligned 64-bit reads via `u64::from_le_bytes` for fast
/// bit extraction. Every read returns `Result<T>` with overflow checking.
pub struct BitReader<'a> {
    data: &'a [u8],
    position: usize,
    total_bits: usize,
}

impl<'a> BitReader<'a> {
    /// Create a new reader starting at bit 0 of `data`.
    #[inline]
    pub fn new(data: &'a [u8]) -> Self {
        Self {
            data,
            position: 0,
            total_bits: data.len() * 8,
        }
    }

    /// Number of bits between the cursor and the end of the buffer.
    #[inline]
    pub fn bits_remaining(&self) -> usize {
        self.total_bits.saturating_sub(self.position)
    }

    /// Current bit offset from the start of the buffer.
    #[inline]
    pub fn position(&self) -> usize {
        self.position
    }

    /// The full underlying byte slice (independent of the cursor).
    #[inline]
    pub fn data(&self) -> &'a [u8] {
        self.data
    }

    /// Read up to 64 bits. Returns the value right-aligned in a u64.
    #[inline]
    pub fn read_bits(&mut self, n: usize) -> Result<u64> {
        if n == 0 {
            return Ok(0);
        }
        if n > 64 || self.position + n > self.total_bits {
            return Err(Error::Overflow {
                needed: n,
                available: self.bits_remaining(),
            });
        }

        let value = self.peek_bits_unchecked(n);
        self.position += n;
        Ok(value)
    }

    /// Peek at up to 64 bits without advancing the cursor.
    #[inline]
    pub fn peek_bits(&self, n: usize) -> Result<u64> {
        if n == 0 {
            return Ok(0);
        }
        if n > 64 || self.position + n > self.total_bits {
            return Err(Error::Overflow {
                needed: n,
                available: self.bits_remaining(),
            });
        }
        Ok(self.peek_bits_unchecked(n))
    }

    /// Internal: peek without bounds checking.
    ///
    /// Reads a little-endian u64 from the byte at `position / 8`, shifts right by
    /// the intra-byte bit offset, and masks to `n` bits. The 8-byte window only
    /// holds `64 - bit_offset` valid bits after the shift, so a read that needs
    /// more (only possible for `n > 56` at a non-zero offset — e.g. a 64-bit read
    /// mid-stream) pulls the extra high bits from the following byte; without that
    /// they would be silently dropped.
    #[inline(always)]
    fn peek_bits_unchecked(&self, n: usize) -> u64 {
        let byte_pos = self.position / 8;
        let bit_offset = self.position % 8;
        let remaining_bytes = self.data.len() - byte_pos;

        let word = if remaining_bytes >= 8 {
            u64::from_le_bytes(
                self.data[byte_pos..byte_pos + 8]
                    .try_into()
                    .expect("slice has exactly eight bytes"),
            )
        } else {
            self.data[byte_pos..]
                .iter()
                .enumerate()
                .fold(0u64, |word, (i, &byte)| word | (byte as u64) << (i * 8))
        };
        let low = word >> bit_offset;
        if bit_offset + n <= 64 {
            return low & mask(n);
        }
        let taken = 64 - bit_offset;
        let hi = self.data.get(byte_pos + 8).copied().unwrap_or(0) as u64 & mask(n - taken);
        (low | (hi << taken)) & mask(n)
    }

    /// Read a single bit as a boolean.
    #[inline]
    pub fn read_bool(&mut self) -> Result<bool> {
        if self.position >= self.total_bits {
            return Err(Error::Overflow {
                needed: 1,
                available: 0,
            });
        }
        let value = self.data[self.position / 8] & (1 << (self.position % 8)) != 0;
        self.position += 1;
        Ok(value)
    }

    /// Read 8 bits as a `u8`.
    #[inline]
    pub fn read_u8(&mut self) -> Result<u8> {
        if self.bits_remaining() < 8 {
            return Err(Error::Overflow {
                needed: 8,
                available: self.bits_remaining(),
            });
        }

        let byte_pos = self.position / 8;
        let bit_offset = self.position % 8;
        let value = if bit_offset == 0 {
            self.data[byte_pos]
        } else {
            let window = self.data[byte_pos] as u16 | (self.data[byte_pos + 1] as u16) << 8;
            (window >> bit_offset) as u8
        };
        self.position += 8;
        Ok(value)
    }

    /// Read 16 bits as a little-endian integer.
    #[inline]
    pub fn read_u16(&mut self) -> Result<u16> {
        Ok(self.read_bits(16)? as u16)
    }

    /// Read 32 bits as a little-endian `u32`.
    #[inline]
    pub fn read_u32(&mut self) -> Result<u32> {
        Ok(self.read_bits(32)? as u32)
    }

    /// Read 64 bits as a little-endian integer.
    #[inline]
    pub fn read_u64(&mut self) -> Result<u64> {
        self.read_bits(64)
    }

    /// Read 32 bits and reinterpret as an IEEE 754 `f32`.
    #[inline]
    pub fn read_f32(&mut self) -> Result<f32> {
        Ok(f32::from_bits(self.read_bits(32)? as u32))
    }

    /// Read N bytes into the provided buffer.
    pub fn read_bytes(&mut self, buf: &mut [u8]) -> Result<()> {
        if buf.len() > self.bits_remaining() / 8 {
            return Err(Error::Overflow {
                needed: buf.len().saturating_mul(8),
                available: self.bits_remaining(),
            });
        }
        if buf.is_empty() {
            return Ok(());
        }

        let byte_pos = self.position / 8;
        let shift = self.position % 8;
        // Fast path: byte-aligned — direct memcpy.
        if shift == 0 {
            buf.copy_from_slice(&self.data[byte_pos..byte_pos + buf.len()]);
        } else {
            // Every output byte straddles two input bytes. The bounds check
            // above guarantees the extra byte, including at the short tail.
            let input = &self.data[byte_pos..byte_pos + buf.len() + 1];
            for ((output, low), high) in buf.iter_mut().zip(input).zip(&input[1..]) {
                *output = (low >> shift) | (high << (8 - shift));
            }
        }
        self.position += buf.len() * 8;
        Ok(())
    }

    /// Read a specified number of bits into a byte buffer, filling LSB-first.
    pub fn read_bits_to_bytes(&mut self, buf: &mut [u8], bits: usize) -> Result<()> {
        let needed = bits.div_ceil(8);
        if needed > buf.len() {
            return Err(Error::Overflow {
                needed,
                available: buf.len(),
            });
        }
        let full_bytes = bits / 8;
        let remaining_bits = bits % 8;

        if remaining_bits == 0 {
            return self.read_bytes(&mut buf[..full_bytes]);
        }

        // Has trailing bits — can still fast-path the full bytes.
        if full_bytes > 0 {
            self.read_bytes(&mut buf[..full_bytes])?;
        }
        buf[full_bytes] = self.read_bits(remaining_bits)? as u8;
        Ok(())
    }

    /// Read an unsigned varint (up to 32 bits).
    #[inline]
    pub fn read_uvarint32(&mut self) -> Result<u32> {
        let mut result: u32 = 0;
        for i in 0..5 {
            let byte = self.read_u8()? as u32;
            result |= (byte & 0x7F) << (7 * i);
            if byte & 0x80 == 0 {
                return Ok(result);
            }
        }
        Ok(result)
    }

    /// Read an unsigned varint (up to 64 bits).
    pub fn read_uvarint64(&mut self) -> Result<u64> {
        let mut result: u64 = 0;
        for i in 0..10 {
            let byte = self.read_u8()? as u64;
            result |= (byte & 0x7F) << (7 * i);
            if byte & 0x80 == 0 {
                return Ok(result);
            }
        }
        Ok(result)
    }

    /// Read a signed varint (zigzag encoded, 32-bit).
    pub fn read_varint32(&mut self) -> Result<i32> {
        let n = self.read_uvarint32()?;
        Ok(((n >> 1) as i32) ^ -((n & 1) as i32))
    }

    /// Read a signed varint (zigzag encoded, 64-bit).
    pub fn read_varint64(&mut self) -> Result<i64> {
        let n = self.read_uvarint64()?;
        Ok(((n >> 1) as i64) ^ -((n & 1) as i64))
    }

    /// Valve's variable-length unsigned integer encoding.
    ///
    /// Reads 6 bits; bits 4-5 select the total width:
    /// `00` → 6 bits, `01` → 4+4, `10` → 4+8, `11` → 4+28.
    #[inline]
    pub fn read_ubitvar(&mut self) -> Result<u32> {
        let ret = self.read_bits(6)? as u32;
        match ret & (16 | 32) {
            16 => Ok((ret & 15) | (self.read_bits(4)? as u32) << 4),
            32 => Ok((ret & 15) | (self.read_bits(8)? as u32) << 4),
            48 => Ok((ret & 15) | (self.read_bits(28)? as u32) << 4),
            _ => Ok(ret),
        }
    }

    /// Field-path variant of ubitvar — cascading 1-bit selectors.
    ///
    /// Used exclusively for encoding field path operation indices:
    /// 2, 4, 10, 17, or 31 bits depending on which prefix bit is set.
    #[inline]
    pub fn read_ubitvarfp(&mut self) -> Result<u32> {
        // A complete selector and the longest payload fit in 35 bits. Near
        // EOF retain the stepwise reader and its exact error cursor.
        if self.bits_remaining() >= 35 {
            let word = self.peek_bits_unchecked(35);
            let selector = (word as u32).trailing_zeros().min(4) as usize;
            let prefix_bits = (selector + 1).min(4);
            let payload_bits = [2, 4, 10, 17, 31][selector];
            self.position += prefix_bits + payload_bits;
            return Ok(((word >> prefix_bits) & mask(payload_bits)) as u32);
        }
        if self.read_bool()? {
            return Ok(self.read_bits(2)? as u32);
        }
        if self.read_bool()? {
            return Ok(self.read_bits(4)? as u32);
        }
        if self.read_bool()? {
            return Ok(self.read_bits(10)? as u32);
        }
        if self.read_bool()? {
            return Ok(self.read_bits(17)? as u32);
        }
        Ok(self.read_bits(31)? as u32)
    }

    /// Read a coordinate value.
    pub fn read_bitcoord(&mut self) -> Result<f32> {
        let has_int = self.read_bool()?;
        let has_frac = self.read_bool()?;

        if !has_int && !has_frac {
            return Ok(0.0);
        }

        let negative = self.read_bool()?;
        let mut value = 0.0f32;

        if has_int {
            value += self.read_bits(COORD_INTEGER_BITS)? as f32 + 1.0;
        }
        if has_frac {
            value += self.read_bits(COORD_FRACTIONAL_BITS)? as f32 * COORD_RESOLUTION;
        }

        if negative {
            value = -value;
        }

        Ok(value)
    }

    /// Read a normal component (sign + 11-bit fraction).
    pub fn read_bitnormal(&mut self) -> Result<f32> {
        let negative = self.read_bool()?;
        let frac = self.read_bits(NORMAL_FRACTIONAL_BITS)? as f32;
        let mut value = frac * NORMAL_RESOLUTION;
        if negative {
            value = -value;
        }
        Ok(value)
    }

    /// Read a 3D coordinate vector.
    pub fn read_bitvec3coord(&mut self) -> Result<[f32; 3]> {
        let has_x = self.read_bool()?;
        let has_y = self.read_bool()?;
        let has_z = self.read_bool()?;

        let x = if has_x { self.read_bitcoord()? } else { 0.0 };
        let y = if has_y { self.read_bitcoord()? } else { 0.0 };
        let z = if has_z { self.read_bitcoord()? } else { 0.0 };

        Ok([x, y, z])
    }

    /// Read a 3D normal vector (2 components + derived Z).
    pub fn read_bitvec3normal(&mut self) -> Result<[f32; 3]> {
        let has_x = self.read_bool()?;
        let has_y = self.read_bool()?;

        let x = if has_x { self.read_bitnormal()? } else { 0.0 };
        let y = if has_y { self.read_bitnormal()? } else { 0.0 };

        let z_sign = self.read_bool()?;
        let z_sq = 1.0 - x * x - y * y;
        let z = if z_sq > 0.0 { z_sq.sqrt() } else { 0.0 };
        let z = if z_sign { -z } else { z };

        Ok([x, y, z])
    }

    /// Read an angle encoded as N bits, returning degrees in [0, 360).
    pub fn read_bitangle(&mut self, n: usize) -> Result<f32> {
        let raw = self.read_bits(n)? as f32;
        let shift = (1u64 << n) as f32;
        Ok(raw * 360.0 / shift)
    }

    /// Read a null-terminated string.
    pub fn read_string(&mut self) -> Result<String> {
        let mut bytes = Vec::new();
        loop {
            let byte = self.read_u8()?;
            if byte == 0 {
                break;
            }
            bytes.push(byte);
        }
        Ok(String::from_utf8_lossy(&bytes).into_owned())
    }

    /// Read a string into the provided buffer, returning bytes written (excluding null).
    pub fn read_string_into(&mut self, buf: &mut [u8]) -> Result<usize> {
        let mut i = 0;
        loop {
            let b = self.read_u8()?;
            if b == 0 {
                break;
            }
            if i < buf.len() {
                buf[i] = b;
                i += 1;
            }
        }
        Ok(i)
    }

    /// Read a raw null-terminated string while enforcing a byte limit.
    pub fn read_string_raw_limited(
        &mut self,
        buf: &mut Vec<u8>,
        max_bytes: usize,
    ) -> Result<usize> {
        let start = buf.len();
        loop {
            let b = self.read_u8()?;
            if b == 0 {
                break;
            }
            let written = buf.len() - start;
            if written == max_bytes {
                return Err(Error::LimitExceeded {
                    resource: "decoded field string",
                    limit: max_bytes,
                    actual: written.saturating_add(1),
                });
            }
            buf.push(b);
        }
        Ok(buf.len() - start)
    }

    /// Read a string as raw bytes into a Vec, returning bytes written (excluding null).
    pub fn read_string_raw(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
        let start = buf.len();
        loop {
            let b = self.read_u8()?;
            if b == 0 {
                break;
            }
            buf.push(b);
        }
        Ok(buf.len() - start)
    }

    /// Skip forward by N bits.
    pub fn skip_bits(&mut self, n: usize) -> Result<()> {
        if n > self.bits_remaining() {
            return Err(Error::Overflow {
                needed: n,
                available: self.bits_remaining(),
            });
        }
        self.position += n;
        Ok(())
    }

    /// Skip a varint without decoding it.
    pub fn skip_varint(&mut self) -> Result<()> {
        for _ in 0..10 {
            let byte = self.read_u8()?;
            if byte & 0x80 == 0 {
                return Ok(());
            }
        }
        Ok(())
    }

    /// Skip a bitcoord value.
    pub fn skip_bitcoord(&mut self) -> Result<()> {
        let has_int = self.read_bool()?;
        let has_frac = self.read_bool()?;

        if !has_int && !has_frac {
            return Ok(());
        }

        self.skip_bits(1)?; // negative flag

        if has_int {
            self.skip_bits(COORD_INTEGER_BITS)?;
        }
        if has_frac {
            self.skip_bits(COORD_FRACTIONAL_BITS)?;
        }

        Ok(())
    }

    /// Skip a bitnormal value.
    pub fn skip_bitnormal(&mut self) -> Result<()> {
        self.skip_bits(1 + NORMAL_FRACTIONAL_BITS)
    }

    /// Skip a 3D coordinate vector.
    pub fn skip_bitvec3coord(&mut self) -> Result<()> {
        let has_x = self.read_bool()?;
        let has_y = self.read_bool()?;
        let has_z = self.read_bool()?;

        if has_x {
            self.skip_bitcoord()?;
        }
        if has_y {
            self.skip_bitcoord()?;
        }
        if has_z {
            self.skip_bitcoord()?;
        }

        Ok(())
    }

    /// Skip a 3D normal vector.
    pub fn skip_bitvec3normal(&mut self) -> Result<()> {
        let has_x = self.read_bool()?;
        let has_y = self.read_bool()?;

        if has_x {
            self.skip_bitnormal()?;
        }
        if has_y {
            self.skip_bitnormal()?;
        }

        self.skip_bits(1)?; // z_sign

        Ok(())
    }

    /// Skip a null-terminated string with the same byte limit as a decoded string.
    #[inline]
    pub fn skip_string_limited(&mut self, max_bytes: usize) -> Result<()> {
        // Preserve the empty-string path without a limit check. After one byte,
        // a valid string cannot exceed the limit if the rest of the packet fits.
        if self.read_u8()? == 0 {
            return Ok(());
        }
        if self.bits_remaining() / 8 < max_bytes {
            return self.skip_string();
        }
        self.skip_string_bounded(max_bytes)
    }

    // Keep uncommon large-packet limit checks out of the small-packet loop.
    #[cold]
    fn skip_string_bounded(&mut self, max_bytes: usize) -> Result<()> {
        if max_bytes == 0 {
            return Err(Error::LimitExceeded {
                resource: "decoded field string",
                limit: 0,
                actual: 1,
            });
        }
        let mut length = 1_usize;
        loop {
            if self.read_u8()? == 0 {
                return Ok(());
            }
            if length == max_bytes {
                return Err(Error::LimitExceeded {
                    resource: "decoded field string",
                    limit: max_bytes,
                    actual: length.saturating_add(1),
                });
            }
            length += 1;
        }
    }

    /// Skip a null-terminated string.
    pub fn skip_string(&mut self) -> Result<()> {
        loop {
            let b = self.read_u8()?;
            if b == 0 {
                return Ok(());
            }
        }
    }
}

/// Create a bitmask with n bits set.
#[inline(always)]
fn mask(n: usize) -> u64 {
    if n >= 64 { u64::MAX } else { (1u64 << n) - 1 }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn limited_string_skip_matches_read_errors_and_cursor() {
        for alignment in 0..8 {
            for length in 0..20 {
                for terminated in [false, true] {
                    let mut bits = crate::test_utils::BitWriter::default();
                    bits.push_bits(0, alignment);
                    bits.push_bytes(&vec![b'x'; length]);
                    if terminated {
                        bits.push_bits(0, 8);
                    }
                    let data = bits.finish();
                    for limit in [0, 1, 3, 8, 20, usize::MAX] {
                        let mut read = BitReader::new(&data);
                        let mut skip = BitReader::new(&data);
                        read.skip_bits(alignment).unwrap();
                        skip.skip_bits(alignment).unwrap();
                        let expected = read
                            .read_string_raw_limited(&mut Vec::new(), limit)
                            .map(|_| ())
                            .map_err(|e| e.to_string());
                        let actual = skip.skip_string_limited(limit).map_err(|e| e.to_string());
                        assert_eq!((actual, skip.position()), (expected, read.position()));
                    }
                }
            }
        }
    }

    #[test]
    fn oversized_skip_preserves_cursor() {
        let mut reader = BitReader::new(&[0xff]);
        reader.skip_bits(1).unwrap();
        assert!(matches!(
            reader.skip_bits(usize::MAX),
            Err(Error::Overflow { .. })
        ));
        assert_eq!(reader.position(), 1);
        assert_eq!(reader.read_bits(7).unwrap(), 127);
    }

    #[test]
    fn bit_copy_rejects_short_output_before_consuming_input() {
        for bits in [9, 16, usize::MAX] {
            let mut reader = BitReader::new(&[0xff; 4]);
            let mut output = [0x55];
            assert!(matches!(
                reader.read_bits_to_bytes(&mut output, bits),
                Err(Error::Overflow { .. })
            ));
            assert_eq!(reader.position(), 0);
            assert_eq!(output, [0x55]);
        }
    }

    #[test]
    fn test_read_u8_unaligned() {
        let data = [0b1011_0100, 0b1100_1010, 0b0110_0001];
        for offset in 1..8 {
            let mut br = BitReader::new(&data);
            br.skip_bits(offset).unwrap();
            let got = br.read_u8().unwrap();
            let window = u32::from_le_bytes([data[0], data[1], data[2], 0]);
            assert_eq!(got, ((window >> offset) & 0xff) as u8);
        }
    }

    #[test]
    fn test_read_bool_overflow() {
        let data = [0xff];
        let mut br = BitReader::new(&data);
        for _ in 0..8 {
            assert!(br.read_bool().unwrap());
        }
        assert!(br.read_bool().is_err());
    }

    #[test]
    fn test_read_bits_wide_unaligned() {
        // A ≥58-bit read at a non-zero offset needs bits beyond the first 8-byte
        // window; the extra high bits must come from the next byte, not be dropped.
        let data: Vec<u8> = (0..16).collect();
        let full = u128::from_le_bytes(data[..16].try_into().unwrap());
        for offset in 0..8usize {
            for n in 57..=64usize {
                let mut br = BitReader::new(&data);
                if offset > 0 {
                    br.read_bits(offset).unwrap();
                }
                let got = br.read_bits(n).unwrap();
                let want = ((full >> offset) & ((1u128 << n) - 1)) as u64;
                assert_eq!(got, want, "read_bits({n}) at offset {offset}");
            }
        }
    }

    #[test]
    fn test_read_bits_basic() {
        let data = [0b10110100, 0b11001010];
        let mut br = BitReader::new(&data);

        assert_eq!(br.read_bits(1).unwrap(), 0);
        assert_eq!(br.read_bits(1).unwrap(), 0);
        assert_eq!(br.read_bits(1).unwrap(), 1);
        assert_eq!(br.read_bits(1).unwrap(), 0);
        assert_eq!(br.read_bits(1).unwrap(), 1);
        assert_eq!(br.read_bits(1).unwrap(), 1);
        assert_eq!(br.read_bits(1).unwrap(), 0);
        assert_eq!(br.read_bits(1).unwrap(), 1);
    }

    #[test]
    fn test_read_byte() {
        let data = [0xAB, 0xCD];
        let mut br = BitReader::new(&data);
        assert_eq!(br.read_u8().unwrap(), 0xAB);
        assert_eq!(br.read_u8().unwrap(), 0xCD);
    }

    #[test]
    fn test_read_across_boundary() {
        let data = [0xFF, 0x00, 0xFF];
        let mut br = BitReader::new(&data);
        br.read_bits(4).unwrap();
        let val = br.read_bits(8).unwrap();
        assert_eq!(val, 0x0F);
    }

    #[test]
    fn test_read_bool() {
        let data = [0b10000001];
        let mut br = BitReader::new(&data);
        assert!(br.read_bool().unwrap());
        assert!(!br.read_bool().unwrap());
    }

    #[test]
    fn test_overflow() {
        let data = [0xFF];
        let mut br = BitReader::new(&data);
        br.read_bits(8).unwrap();
        assert!(br.read_bits(1).is_err());
    }

    #[test]
    fn test_uvarint32() {
        // Encode 300 as varint: 300 = 0b100101100
        // byte 0: 10101100 (0xAC), byte 1: 00000010 (0x02)
        let data = [0xAC, 0x02];
        let mut br = BitReader::new(&data);
        assert_eq!(br.read_uvarint32().unwrap(), 300);
    }

    #[test]
    fn test_varint32_negative() {
        // zigzag(-1) = 1
        let data = [0x01];
        let mut br = BitReader::new(&data);
        assert_eq!(br.read_varint32().unwrap(), -1);
    }

    #[test]
    fn test_varint32_positive() {
        // zigzag(1) = 2
        let data = [0x02];
        let mut br = BitReader::new(&data);
        assert_eq!(br.read_varint32().unwrap(), 1);
    }

    #[test]
    fn test_read_f32() {
        let val: f32 = 1.5;
        let data = val.to_bits().to_le_bytes();
        let mut br = BitReader::new(&data);
        let read_val = br.read_f32().unwrap();
        assert!((read_val - val).abs() < f32::EPSILON);
    }

    #[test]
    fn test_bits_remaining() {
        let data = [0xFF, 0xFF];
        let mut br = BitReader::new(&data);
        assert_eq!(br.bits_remaining(), 16);
        br.read_bits(5).unwrap();
        assert_eq!(br.bits_remaining(), 11);
    }

    #[test]
    fn test_skip_bits() {
        let data = [0b11110000, 0b10101010];
        let mut br = BitReader::new(&data);
        br.skip_bits(4).unwrap();
        assert_eq!(br.read_bits(4).unwrap(), 0b1111);
    }

    #[test]
    fn test_ubitvar() {
        // Simple case: value fits in 6 bits, bits 4,5 = 00
        // Value 5 = 0b000101
        let data = [0b00000101];
        let mut br = BitReader::new(&data);
        assert_eq!(br.read_ubitvar().unwrap(), 5);
    }

    #[test]
    fn test_bitangle() {
        let data = [0x00, 0x00, 0x00, 0x00];
        let mut br = BitReader::new(&data);
        assert!((br.read_bitangle(16).unwrap() - 0.0).abs() < f32::EPSILON);
    }
}

#[cfg(test)]
mod field_path_varint_tests {
    use super::*;

    fn read_reference(reader: &mut BitReader) -> Result<u32> {
        for width in [2, 4, 10, 17] {
            if reader.read_bool()? {
                return Ok(reader.read_bits(width)? as u32);
            }
        }
        Ok(reader.read_bits(31)? as u32)
    }

    #[test]
    fn every_width_alignment_and_truncation_matches_the_reference() {
        use crate::test_utils::BitWriter;

        for (selector, width) in [2, 4, 10, 17, 31].into_iter().enumerate() {
            for value in [0, 1, (1u64 << width) - 1] {
                for offset in 0..8 {
                    let mut writer = BitWriter::default();
                    writer.push_bits(0, offset);
                    for _ in 0..selector.min(4) {
                        writer.push_bool(false);
                    }
                    if selector < 4 {
                        writer.push_bool(true);
                    }
                    writer.push_bits(value, width);
                    writer.push_bits(0xabcdef12, 32);
                    let bytes = writer.finish();
                    for end in 0..=bytes.len() {
                        if end * 8 < offset {
                            continue;
                        }
                        let mut actual = BitReader::new(&bytes[..end]);
                        let mut reference = BitReader::new(&bytes[..end]);
                        actual.skip_bits(offset).unwrap();
                        reference.skip_bits(offset).unwrap();
                        assert_eq!(
                            format!("{:?}", actual.read_ubitvarfp()),
                            format!("{:?}", read_reference(&mut reference))
                        );
                        assert_eq!(actual.position(), reference.position());
                        if end == bytes.len() {
                            assert_eq!(actual.read_bits(32).unwrap(), 0xabcdef12);
                        }
                    }
                }
            }
        }
    }

    proptest::proptest! {
        #[test]
        fn combined_field_path_varints_preserve_values_errors_and_cursors(
            bytes in proptest::collection::vec(proptest::prelude::any::<u8>(), 1..128),
            offset in 0usize..8,
        ) {
            let mut actual = BitReader::new(&bytes);
            let mut reference = BitReader::new(&bytes);
            actual.skip_bits(offset).unwrap();
            reference.skip_bits(offset).unwrap();
            loop {
                let actual_result = actual.read_ubitvarfp();
                let reference_result = read_reference(&mut reference);
                proptest::prop_assert_eq!(format!("{actual_result:?}"), format!("{reference_result:?}"));
                proptest::prop_assert_eq!(actual.position(), reference.position());
                if actual_result.is_err() { break; }
            }
        }
    }
}