vexil-runtime 0.5.1

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
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.
    pub fn read_bits(&mut self, count: u8) -> Result<u64, DecodeError> {
        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 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 flush_reader() {
        let mut w = BitWriter::new();
        w.write_bits(0b101, 3);
        w.flush_to_byte_boundary();
        w.write_u8(0xAB);
        let b = w.finish();
        let mut r = BitReader::new(&b);
        assert_eq!(r.read_bits(3).unwrap(), 0b101);
        r.flush_to_byte_boundary();
        assert_eq!(r.read_u8().unwrap(), 0xAB);
    }
}