vexil-runtime 0.6.0

Runtime support for Vexil generated code — bit-level I/O, Pack/Unpack traits, wire encoding 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
use crate::error::DecodeError;
use crate::{MAX_BYTES_LENGTH, MAX_RECURSION_DEPTH};

/// A cursor over a byte slice that reads fields LSB-first at the bit level.
///
/// Created with [`BitReader::new`], consumed with `read_*` methods. Tracks
/// a byte position and a sub-byte bit offset, plus a recursion depth counter
/// for safely decoding recursive types.
///
/// Sub-byte reads pull individual bits from the current byte. Multi-byte reads
/// (e.g. [`read_u16`](Self::read_u16)) first align to the next byte boundary,
/// then interpret the bytes as little-endian.
pub struct BitReader<'a> {
    data: &'a [u8],
    byte_pos: usize,
    bit_offset: u8,
    recursion_depth: u32,
}

impl<'a> BitReader<'a> {
    /// Create a new `BitReader` over the given byte slice.
    pub fn new(data: &'a [u8]) -> Self {
        Self {
            data,
            byte_pos: 0,
            bit_offset: 0,
            recursion_depth: 0,
        }
    }

    /// Read `count` bits LSB-first into a u64.
    ///
    /// Fast path: if the requested bits fit entirely within the current byte,
    /// extract them with a single mask+shift instead of looping.
    pub fn read_bits(&mut self, count: u8) -> Result<u64, DecodeError> {
        debug_assert!(count <= 64, "read_bits: count must be <= 64");
        if count == 0 {
            return Ok(0);
        }

        if self.byte_pos >= self.data.len() {
            return Err(DecodeError::UnexpectedEof);
        }

        let remaining = 8 - self.bit_offset;

        // Fast path: all requested bits are in the current byte
        if count <= remaining {
            let byte = self.data[self.byte_pos];
            let mask = if count >= 8 {
                u8::MAX
            } else {
                (1u8 << count) - 1
            };
            let result = u64::from((byte >> self.bit_offset) & mask);
            self.bit_offset += count;
            if self.bit_offset == 8 {
                self.byte_pos += 1;
                self.bit_offset = 0;
            }
            return Ok(result);
        }

        // Slow path: bits span byte boundaries
        let mut result: u64 = 0;
        for i in 0..count {
            if self.byte_pos >= self.data.len() {
                return Err(DecodeError::UnexpectedEof);
            }
            let bit = (self.data[self.byte_pos] >> self.bit_offset) & 1;
            result |= u64::from(bit) << i;
            self.bit_offset += 1;
            if self.bit_offset == 8 {
                self.byte_pos += 1;
                self.bit_offset = 0;
            }
        }
        Ok(result)
    }

    /// Read a single bit as bool.
    pub fn read_bool(&mut self) -> Result<bool, DecodeError> {
        Ok(self.read_bits(1)? != 0)
    }

    /// Advance to the next byte boundary, discarding any remaining bits in the current byte.
    /// Infallible.
    pub fn flush_to_byte_boundary(&mut self) {
        if self.bit_offset > 0 {
            self.byte_pos += 1;
            self.bit_offset = 0;
        }
    }

    /// Remaining bytes from byte_pos.
    fn remaining(&self) -> usize {
        self.data.len().saturating_sub(self.byte_pos)
    }

    /// Read a `u8`, aligning to a byte boundary first.
    pub fn read_u8(&mut self) -> Result<u8, DecodeError> {
        self.flush_to_byte_boundary();
        if self.remaining() < 1 {
            return Err(DecodeError::UnexpectedEof);
        }
        let v = self.data[self.byte_pos];
        self.byte_pos += 1;
        Ok(v)
    }

    /// Read a little-endian `u16`, aligning to a byte boundary first.
    pub fn read_u16(&mut self) -> Result<u16, DecodeError> {
        self.flush_to_byte_boundary();
        if self.remaining() < 2 {
            return Err(DecodeError::UnexpectedEof);
        }
        let bytes: [u8; 2] = self.data[self.byte_pos..self.byte_pos + 2]
            .try_into()
            .map_err(|_| DecodeError::UnexpectedEof)?;
        self.byte_pos += 2;
        Ok(u16::from_le_bytes(bytes))
    }

    /// Read a little-endian `u32`, aligning to a byte boundary first.
    pub fn read_u32(&mut self) -> Result<u32, DecodeError> {
        self.flush_to_byte_boundary();
        if self.remaining() < 4 {
            return Err(DecodeError::UnexpectedEof);
        }
        let bytes: [u8; 4] = self.data[self.byte_pos..self.byte_pos + 4]
            .try_into()
            .map_err(|_| DecodeError::UnexpectedEof)?;
        self.byte_pos += 4;
        Ok(u32::from_le_bytes(bytes))
    }

    /// Read a little-endian `u64`, aligning to a byte boundary first.
    pub fn read_u64(&mut self) -> Result<u64, DecodeError> {
        self.flush_to_byte_boundary();
        if self.remaining() < 8 {
            return Err(DecodeError::UnexpectedEof);
        }
        let bytes: [u8; 8] = self.data[self.byte_pos..self.byte_pos + 8]
            .try_into()
            .map_err(|_| DecodeError::UnexpectedEof)?;
        self.byte_pos += 8;
        Ok(u64::from_le_bytes(bytes))
    }

    /// Read an `i8`, aligning to a byte boundary first.
    pub fn read_i8(&mut self) -> Result<i8, DecodeError> {
        self.flush_to_byte_boundary();
        if self.remaining() < 1 {
            return Err(DecodeError::UnexpectedEof);
        }
        let bytes: [u8; 1] = [self.data[self.byte_pos]];
        self.byte_pos += 1;
        Ok(i8::from_le_bytes(bytes))
    }

    /// Read a little-endian `i16`, aligning to a byte boundary first.
    pub fn read_i16(&mut self) -> Result<i16, DecodeError> {
        self.flush_to_byte_boundary();
        if self.remaining() < 2 {
            return Err(DecodeError::UnexpectedEof);
        }
        let bytes: [u8; 2] = self.data[self.byte_pos..self.byte_pos + 2]
            .try_into()
            .map_err(|_| DecodeError::UnexpectedEof)?;
        self.byte_pos += 2;
        Ok(i16::from_le_bytes(bytes))
    }

    /// Read a little-endian `i32`, aligning to a byte boundary first.
    pub fn read_i32(&mut self) -> Result<i32, DecodeError> {
        self.flush_to_byte_boundary();
        if self.remaining() < 4 {
            return Err(DecodeError::UnexpectedEof);
        }
        let bytes: [u8; 4] = self.data[self.byte_pos..self.byte_pos + 4]
            .try_into()
            .map_err(|_| DecodeError::UnexpectedEof)?;
        self.byte_pos += 4;
        Ok(i32::from_le_bytes(bytes))
    }

    /// Read a little-endian `i64`, aligning to a byte boundary first.
    pub fn read_i64(&mut self) -> Result<i64, DecodeError> {
        self.flush_to_byte_boundary();
        if self.remaining() < 8 {
            return Err(DecodeError::UnexpectedEof);
        }
        let bytes: [u8; 8] = self.data[self.byte_pos..self.byte_pos + 8]
            .try_into()
            .map_err(|_| DecodeError::UnexpectedEof)?;
        self.byte_pos += 8;
        Ok(i64::from_le_bytes(bytes))
    }

    /// Read a little-endian `f32`, aligning to a byte boundary first.
    pub fn read_f32(&mut self) -> Result<f32, DecodeError> {
        self.flush_to_byte_boundary();
        if self.remaining() < 4 {
            return Err(DecodeError::UnexpectedEof);
        }
        let bytes: [u8; 4] = self.data[self.byte_pos..self.byte_pos + 4]
            .try_into()
            .map_err(|_| DecodeError::UnexpectedEof)?;
        self.byte_pos += 4;
        Ok(f32::from_le_bytes(bytes))
    }

    /// Read a little-endian `f64`, aligning to a byte boundary first.
    pub fn read_f64(&mut self) -> Result<f64, DecodeError> {
        self.flush_to_byte_boundary();
        if self.remaining() < 8 {
            return Err(DecodeError::UnexpectedEof);
        }
        let bytes: [u8; 8] = self.data[self.byte_pos..self.byte_pos + 8]
            .try_into()
            .map_err(|_| DecodeError::UnexpectedEof)?;
        self.byte_pos += 8;
        Ok(f64::from_le_bytes(bytes))
    }

    /// Read a LEB128-encoded u64, consuming at most `max_bytes` bytes.
    pub fn read_leb128(&mut self, max_bytes: u8) -> Result<u64, DecodeError> {
        self.flush_to_byte_boundary();
        let (value, consumed) = crate::leb128::decode(&self.data[self.byte_pos..], max_bytes)?;
        self.byte_pos += consumed;
        Ok(value)
    }

    /// Read a ZigZag + LEB128 encoded signed integer.
    pub fn read_zigzag(&mut self, _type_bits: u8, max_bytes: u8) -> Result<i64, DecodeError> {
        let raw = self.read_leb128(max_bytes)?;
        Ok(crate::zigzag::zigzag_decode(raw))
    }

    /// Read a length-prefixed UTF-8 string.
    pub fn read_string(&mut self) -> Result<String, DecodeError> {
        self.flush_to_byte_boundary();
        let len = self.read_leb128(crate::MAX_LENGTH_PREFIX_BYTES)?;
        if len > MAX_BYTES_LENGTH {
            return Err(DecodeError::LimitExceeded {
                field: "string",
                limit: MAX_BYTES_LENGTH,
                actual: len,
            });
        }
        let len = len as usize;
        if self.remaining() < len {
            return Err(DecodeError::UnexpectedEof);
        }
        let bytes = self.data[self.byte_pos..self.byte_pos + len].to_vec();
        self.byte_pos += len;
        String::from_utf8(bytes).map_err(|_| DecodeError::InvalidUtf8)
    }

    /// Read a length-prefixed byte vector.
    pub fn read_bytes(&mut self) -> Result<Vec<u8>, DecodeError> {
        self.flush_to_byte_boundary();
        let len = self.read_leb128(crate::MAX_LENGTH_PREFIX_BYTES)?;
        if len > MAX_BYTES_LENGTH {
            return Err(DecodeError::LimitExceeded {
                field: "bytes",
                limit: MAX_BYTES_LENGTH,
                actual: len,
            });
        }
        let len = len as usize;
        if self.remaining() < len {
            return Err(DecodeError::UnexpectedEof);
        }
        let bytes = self.data[self.byte_pos..self.byte_pos + len].to_vec();
        self.byte_pos += len;
        Ok(bytes)
    }

    /// Read exactly `len` raw bytes with no length prefix.
    pub fn read_raw_bytes(&mut self, len: usize) -> Result<Vec<u8>, DecodeError> {
        self.flush_to_byte_boundary();
        if self.remaining() < len {
            return Err(DecodeError::UnexpectedEof);
        }
        let bytes = self.data[self.byte_pos..self.byte_pos + len].to_vec();
        self.byte_pos += len;
        Ok(bytes)
    }

    /// Read `len` bytes as a zero-copy slice, aligning to a byte boundary first.
    ///
    /// The returned slice borrows from the original buffer (lifetime `'a`).
    /// This is useful when you need to reference data without allocating.
    pub fn read_bytes_ref(&mut self, len: usize) -> Result<&'a [u8], DecodeError> {
        self.flush_to_byte_boundary();
        if self.remaining() < len {
            return Err(DecodeError::UnexpectedEof);
        }
        let slice = &self.data[self.byte_pos..self.byte_pos + len];
        self.byte_pos += len;
        Ok(slice)
    }

    /// Read a length-prefixed byte slice without copying.
    ///
    /// Reads a LEB128 length prefix, validates against [`MAX_BYTES_LENGTH`](crate::MAX_BYTES_LENGTH),
    /// and returns a slice backed by the original buffer (lifetime `'a`).
    ///
    /// For invalid UTF-8, returns [`DecodeError::InvalidUtf8`].
    pub fn read_bytes_var_ref(&mut self) -> Result<&'a [u8], DecodeError> {
        self.flush_to_byte_boundary();
        let len = self.read_leb128(crate::MAX_LENGTH_PREFIX_BYTES)?;
        if len > MAX_BYTES_LENGTH {
            return Err(DecodeError::LimitExceeded {
                field: "bytes",
                limit: MAX_BYTES_LENGTH,
                actual: len,
            });
        }
        let len = len as usize;
        if self.remaining() < len {
            return Err(DecodeError::UnexpectedEof);
        }
        let slice = &self.data[self.byte_pos..self.byte_pos + len];
        self.byte_pos += len;
        Ok(slice)
    }

    /// Read a length-prefixed UTF-8 string as a zero-copy reference.
    ///
    /// Reads a LEB128 length prefix, validates against [`MAX_BYTES_LENGTH`](crate::MAX_BYTES_LENGTH),
    /// validates UTF-8, and returns a `&str` backed by the original buffer (lifetime `'a`).
    ///
    /// For invalid UTF-8, returns [`DecodeError::InvalidUtf8`].
    pub fn read_string_ref(&mut self) -> Result<&'a str, DecodeError> {
        self.flush_to_byte_boundary();
        let len = self.read_leb128(crate::MAX_LENGTH_PREFIX_BYTES)?;
        if len > MAX_BYTES_LENGTH {
            return Err(DecodeError::LimitExceeded {
                field: "string",
                limit: MAX_BYTES_LENGTH,
                actual: len,
            });
        }
        let len = len as usize;
        if self.remaining() < len {
            return Err(DecodeError::UnexpectedEof);
        }
        let bytes = &self.data[self.byte_pos..self.byte_pos + len];
        let s = std::str::from_utf8(bytes).map_err(|_| DecodeError::InvalidUtf8)?;
        self.byte_pos += len;
        Ok(s)
    }

    /// Read all remaining bytes from the current position to the end.
    /// Flushes to byte boundary first. Returns an empty Vec if no bytes remain.
    pub fn read_remaining(&mut self) -> Vec<u8> {
        self.flush_to_byte_boundary();
        let remaining = self.data.len().saturating_sub(self.byte_pos);
        if remaining == 0 {
            return Vec::new();
        }
        let result = self.data[self.byte_pos..].to_vec();
        self.byte_pos = self.data.len();
        result
    }

    /// Increment recursion depth; return error if limit exceeded.
    pub fn enter_recursive(&mut self) -> Result<(), DecodeError> {
        self.recursion_depth += 1;
        if self.recursion_depth > MAX_RECURSION_DEPTH {
            return Err(DecodeError::RecursionLimitExceeded);
        }
        Ok(())
    }

    /// Decrement recursion depth.
    pub fn leave_recursive(&mut self) {
        self.recursion_depth = self.recursion_depth.saturating_sub(1);
    }
}

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

    #[test]
    fn read_single_bit() {
        let mut r = BitReader::new(&[0x01]);
        assert!(r.read_bool().unwrap());
    }

    #[test]
    fn round_trip_sub_byte() {
        let mut w = BitWriter::new();
        w.write_bits(5, 3);
        w.write_bits(19, 5);
        w.write_bits(42, 6);
        let buf = w.finish();
        let mut r = BitReader::new(&buf);
        assert_eq!(r.read_bits(3).unwrap(), 5);
        assert_eq!(r.read_bits(5).unwrap(), 19);
        assert_eq!(r.read_bits(6).unwrap(), 42);
    }

    #[test]
    fn round_trip_u16() {
        let mut w = BitWriter::new();
        w.write_u16(0x1234);
        let b = w.finish();
        assert_eq!(BitReader::new(&b).read_u16().unwrap(), 0x1234);
    }

    #[test]
    fn round_trip_i32_neg() {
        let mut w = BitWriter::new();
        w.write_i32(-42);
        let b = w.finish();
        assert_eq!(BitReader::new(&b).read_i32().unwrap(), -42);
    }

    #[test]
    fn round_trip_f32() {
        let mut w = BitWriter::new();
        w.write_f32(std::f32::consts::PI);
        let b = w.finish();
        assert_eq!(BitReader::new(&b).read_f32().unwrap(), std::f32::consts::PI);
    }

    #[test]
    fn round_trip_f64_nan() {
        let mut w = BitWriter::new();
        w.write_f64(f64::NAN);
        let b = w.finish();
        let v = BitReader::new(&b).read_f64().unwrap();
        assert!(v.is_nan());
        assert_eq!(v.to_bits(), 0x7FF8000000000000);
    }

    #[test]
    fn round_trip_string() {
        let mut w = BitWriter::new();
        w.write_string("hello");
        let b = w.finish();
        assert_eq!(BitReader::new(&b).read_string().unwrap(), "hello");
    }

    #[test]
    fn round_trip_leb128() {
        let mut w = BitWriter::new();
        w.write_leb128(300);
        let b = w.finish();
        assert_eq!(BitReader::new(&b).read_leb128(4).unwrap(), 300);
    }

    #[test]
    fn round_trip_zigzag() {
        let mut w = BitWriter::new();
        w.write_zigzag(-42, 64);
        let b = w.finish();
        assert_eq!(BitReader::new(&b).read_zigzag(64, 10).unwrap(), -42);
    }

    #[test]
    fn unexpected_eof() {
        assert_eq!(
            BitReader::new(&[]).read_u8().unwrap_err(),
            DecodeError::UnexpectedEof
        );
    }

    #[test]
    fn invalid_utf8() {
        let mut w = BitWriter::new();
        w.write_leb128(2);
        w.write_raw_bytes(&[0xFF, 0xFE]);
        let b = w.finish();
        assert_eq!(
            BitReader::new(&b).read_string().unwrap_err(),
            DecodeError::InvalidUtf8
        );
    }

    #[test]
    fn recursion_depth_limit() {
        let mut r = BitReader::new(&[]);
        for _ in 0..64 {
            r.enter_recursive().unwrap();
        }
        assert_eq!(
            r.enter_recursive().unwrap_err(),
            DecodeError::RecursionLimitExceeded
        );
    }

    #[test]
    fn recursion_depth_leave() {
        let mut r = BitReader::new(&[]);
        for _ in 0..64 {
            r.enter_recursive().unwrap();
        }
        r.leave_recursive();
        r.enter_recursive().unwrap();
    }

    #[test]
    fn trailing_bytes_not_rejected() {
        // Simulate v2-encoded message read by v1 decoder:
        // v2 wrote u32(42) + u16(99), v1 only reads u32(42)
        let data = [0x2a, 0x00, 0x00, 0x00, 0x63, 0x00];
        let mut r = BitReader::new(&data);
        let x = r.read_u32().unwrap();
        assert_eq!(x, 42);
        r.flush_to_byte_boundary();
        // Remaining bytes (0x63, 0x00) must not cause error.
        // BitReader can be dropped with unread data — no panic.
    }

    #[test]
    fn read_remaining_after_partial_decode() {
        let data = [0x2a, 0x00, 0x00, 0x00, 0x63, 0x00];
        let mut r = BitReader::new(&data);
        let _x = r.read_u32().unwrap();
        let remaining = r.read_remaining();
        assert_eq!(remaining, vec![0x63, 0x00]);
    }

    #[test]
    fn read_remaining_when_fully_consumed() {
        let data = [0x2a, 0x00, 0x00, 0x00];
        let mut r = BitReader::new(&data);
        let _x = r.read_u32().unwrap();
        let remaining = r.read_remaining();
        assert!(remaining.is_empty());
    }

    #[test]
    fn read_remaining_from_start() {
        let data = [0x01, 0x02, 0x03];
        let mut r = BitReader::new(&data);
        let remaining = r.read_remaining();
        assert_eq!(remaining, vec![0x01, 0x02, 0x03]);
    }

    #[test]
    fn read_bytes_ref_basic() {
        // read_bytes_ref reads raw bytes with no length prefix
        let data = [0x01, 0x02, 0x03, 0x04, 0x05, 0xFF];
        let mut r = BitReader::new(&data);
        let slice = r.read_bytes_ref(5).unwrap();
        assert_eq!(slice, &[0x01, 0x02, 0x03, 0x04, 0x05]);
        // Verify the slice has the correct lifetime (borrowed from input)
        assert_eq!(slice.as_ptr(), data[0..5].as_ptr());
        // Reader positioned after the slice
        assert_eq!(r.read_u8().unwrap(), 0xFF);
    }

    #[test]
    fn read_bytes_ref_eof() {
        let data = [0x01, 0x02];
        let mut r = BitReader::new(&data);
        assert_eq!(r.read_bytes_ref(5).unwrap_err(), DecodeError::UnexpectedEof);
    }

    #[test]
    fn read_bytes_var_ref_roundtrip() {
        let mut w = BitWriter::new();
        w.write_bytes(&[0x01, 0x02, 0x03, 0x04]);
        let b = w.finish();
        let mut r = BitReader::new(&b);
        let slice = r.read_bytes_var_ref().unwrap();
        assert_eq!(slice, &[0x01, 0x02, 0x03, 0x04]);
    }

    #[test]
    fn read_bytes_var_ref_zero_copy() {
        let data = [0x04, 0x41, 0x42, 0x43, 0x44]; // LEB128(4) + "ABCD"
        let mut r = BitReader::new(&data);
        let slice = r.read_bytes_var_ref().unwrap();
        // Verify zero-copy: slice points into original buffer
        assert_eq!(slice.as_ptr(), data[1..5].as_ptr());
    }

    #[test]
    fn read_bytes_var_ref_limit_exceeded() {
        let mut w = BitWriter::new();
        w.write_leb128(MAX_BYTES_LENGTH + 1);
        let b = w.finish();
        let mut r = BitReader::new(&b);
        assert_eq!(
            r.read_bytes_var_ref().unwrap_err(),
            DecodeError::LimitExceeded {
                field: "bytes",
                limit: MAX_BYTES_LENGTH,
                actual: MAX_BYTES_LENGTH + 1,
            }
        );
    }

    #[test]
    fn read_string_ref_roundtrip() {
        let mut w = BitWriter::new();
        w.write_string("hello");
        let b = w.finish();
        let mut r = BitReader::new(&b);
        let s = r.read_string_ref().unwrap();
        assert_eq!(s, "hello");
    }

    #[test]
    fn read_string_ref_zero_copy() {
        let data = [0x05, b'h', b'e', b'l', b'l', b'o']; // LEB128(5) + "hello"
        let mut r = BitReader::new(&data);
        let s = r.read_string_ref().unwrap();
        // Verify zero-copy: string points into original buffer
        assert_eq!(s.as_ptr(), data[1..6].as_ptr());
    }

    #[test]
    fn read_string_ref_invalid_utf8() {
        let mut w = BitWriter::new();
        w.write_leb128(2);
        w.write_raw_bytes(&[0xFF, 0xFE]);
        let b = w.finish();
        let mut r = BitReader::new(&b);
        assert_eq!(r.read_string_ref().unwrap_err(), DecodeError::InvalidUtf8);
    }

    #[test]
    fn read_string_ref_limit_exceeded() {
        let mut w = BitWriter::new();
        w.write_leb128(MAX_BYTES_LENGTH + 1);
        let b = w.finish();
        let mut r = BitReader::new(&b);
        assert_eq!(
            r.read_string_ref().unwrap_err(),
            DecodeError::LimitExceeded {
                field: "string",
                limit: MAX_BYTES_LENGTH,
                actual: MAX_BYTES_LENGTH + 1,
            }
        );
    }

    #[test]
    fn read_string_ref_eof_mid_string() {
        // Length prefix says 10 bytes, but only 3 available
        let mut w = BitWriter::new();
        w.write_leb128(10);
        w.write_raw_bytes(&[0x41, 0x42, 0x43]); // "ABC"
        let b = w.finish();
        let mut r = BitReader::new(&b);
        assert_eq!(r.read_string_ref().unwrap_err(), DecodeError::UnexpectedEof);
    }

    #[test]
    fn zero_copy_methods_after_bit_reads() {
        // Test that zero-copy methods properly flush to byte boundary
        let mut w = BitWriter::new();
        w.write_bits(0b101, 3); // 3 bits
        w.flush_to_byte_boundary();
        w.write_string("test");
        let b = w.finish();

        let mut r = BitReader::new(&b);
        assert_eq!(r.read_bits(3).unwrap(), 0b101);
        // read_string_ref should flush and read correctly
        let s = r.read_string_ref().unwrap();
        assert_eq!(s, "test");
    }

    #[test]
    fn read_string_equivalence() {
        // Ensure read_string and read_string_ref produce equivalent results
        let mut w = BitWriter::new();
        w.write_string("vexil rocks 🚀");
        let b = w.finish();

        let mut r1 = BitReader::new(&b);
        let mut r2 = BitReader::new(&b);

        let owned = r1.read_string().unwrap();
        let borrowed = r2.read_string_ref().unwrap();

        assert_eq!(owned, borrowed);
    }

    #[test]
    fn read_bytes_equivalence() {
        // Ensure read_bytes and read_bytes_var_ref produce equivalent results
        let mut w = BitWriter::new();
        w.write_bytes(&[0x00, 0x01, 0x02, 0x03]);
        let b = w.finish();

        let mut r1 = BitReader::new(&b);
        let mut r2 = BitReader::new(&b);

        let owned = r1.read_bytes().unwrap();
        let borrowed = r2.read_bytes_var_ref().unwrap();

        assert_eq!(owned, borrowed);
    }
}