qubit-io 0.4.0

Small stream I/O trait utilities for Rust
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
/*******************************************************************************
 *
 *    Copyright (c) 2026 Haixing Hu.
 *
 *    SPDX-License-Identifier: Apache-2.0
 *
 *    Licensed under the Apache License, Version 2.0.
 *
 ******************************************************************************/

use core::marker::PhantomData;

use crate::{
    DecodePolicy,
    Leb128DecodeError,
    Leb128DecodeErrorKind,
    NonStrict,
};

/// Type-level unchecked LEB128 codec.
///
/// `T` selects the decoded integer type and `P` selects the decoding policy.
/// Encoding is always canonical; `P` only affects decoding.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct Leb128Codec<T, P = NonStrict> {
    marker: PhantomData<fn() -> (T, P)>,
}

macro_rules! impl_unsigned_leb128_codec {
    ($ty:ty) => {
        impl<P> Leb128Codec<$ty, P>
        where
            P: DecodePolicy,
        {
            /// Minimum number of bytes required to encode or decode this type.
            pub const REQUIRED_MIN_BUFFER_LEN: usize = (<$ty>::BITS as usize).div_ceil(7);

            /// Decodes a value from `input` starting at `index` without bounds checks.
            ///
            /// # Parameters
            ///
            /// - `input`: Source byte buffer.
            /// - `index`: Start index in `input`.
            ///
            /// # Returns
            ///
            /// Returns the decoded value and the number of consumed bytes.
            ///
            /// # Errors
            ///
            /// Returns [`Leb128DecodeError`] if the bytes are malformed or strict
            /// decoding rejects a non-canonical representation.
            ///
            /// # Safety
            ///
            /// The caller must guarantee that `input.as_ptr().add(index)` is valid to
            /// read [`Self::REQUIRED_MIN_BUFFER_LEN`] bytes, or that a valid terminating byte
            /// appears before that limit.
            #[inline(always)]
            pub unsafe fn read_unchecked(input: &[u8], index: usize) -> Result<($ty, usize), Leb128DecodeError> {
                // SAFETY: The caller guarantees enough readable bytes for this type.
                let (value, consumed) =
                    unsafe { read_uleb_unchecked::<P>(input, index, <$ty>::BITS, Self::REQUIRED_MIN_BUFFER_LEN)? };
                Ok((value as $ty, consumed))
            }

            /// Tries to decode from the currently available bytes without bounds checks.
            ///
            /// This internal entry point is used by buffered readers that may have
            /// only part of a variable-length payload in their input buffer. It
            /// decodes while scanning for the terminating byte, so callers do not
            /// need a separate terminator pre-scan before calling the codec.
            ///
            /// # Parameters
            ///
            /// - `input`: Source byte buffer.
            /// - `index`: Start index in `input`.
            /// - `available`: Number of readable bytes currently available from
            ///   `index`.
            ///
            /// # Returns
            ///
            /// Returns `Ok(Some((value, consumed)))` when a complete value is
            /// decoded. Returns `Ok(None)` when more bytes are needed. Returns
            /// `Err((error, consumed))` when the payload is invalid and should be
            /// consumed before the error is reported.
            ///
            /// # Safety
            ///
            /// The caller must guarantee that `input.as_ptr().add(index)` is valid
            /// to read `available` bytes and that `available` is no greater than
            /// [`Self::REQUIRED_MIN_BUFFER_LEN`].
            #[inline(always)]
            pub(crate) unsafe fn read_available_unchecked(
                input: &[u8],
                index: usize,
                available: usize,
            ) -> Result<Option<($ty, usize)>, (Leb128DecodeError, usize)> {
                // SAFETY: The caller guarantees that exactly `available` bytes
                // are readable from `index`.
                unsafe {
                    read_uleb_available_unchecked::<P>(
                        input,
                        index,
                        <$ty>::BITS,
                        Self::REQUIRED_MIN_BUFFER_LEN,
                        available,
                    )
                }
                .map(|result| result.map(|(value, consumed)| (value as $ty, consumed)))
            }

            /// Encodes `value` into `output` starting at `index` without bounds checks.
            ///
            /// # Parameters
            ///
            /// - `output`: Destination byte buffer.
            /// - `index`: Start index in `output`.
            /// - `value`: Value to encode.
            ///
            /// # Returns
            ///
            /// Returns the number of written bytes.
            ///
            /// # Safety
            ///
            /// The caller must guarantee that `output.as_mut_ptr().add(index)` is valid
            /// to write [`Self::REQUIRED_MIN_BUFFER_LEN`] bytes.
            #[inline(always)]
            pub unsafe fn write_unchecked(output: &mut [u8], index: usize, value: $ty) -> usize {
                // SAFETY: The caller guarantees enough writable bytes for this type.
                unsafe { write_uleb_unchecked(output, index, value as u128) }
            }
        }
    };
}

macro_rules! impl_signed_leb128_codec {
    ($ty:ty) => {
        impl<P> Leb128Codec<$ty, P>
        where
            P: DecodePolicy,
        {
            /// Minimum number of bytes required to encode or decode this type.
            pub const REQUIRED_MIN_BUFFER_LEN: usize = (<$ty>::BITS as usize).div_ceil(7);

            /// Decodes a value from `input` starting at `index` without bounds checks.
            ///
            /// # Parameters
            ///
            /// - `input`: Source byte buffer.
            /// - `index`: Start index in `input`.
            ///
            /// # Returns
            ///
            /// Returns the decoded value and the number of consumed bytes.
            ///
            /// # Errors
            ///
            /// Returns [`Leb128DecodeError`] if the bytes are malformed or strict
            /// decoding rejects a non-canonical representation.
            ///
            /// # Safety
            ///
            /// The caller must guarantee that `input.as_ptr().add(index)` is valid to
            /// read [`Self::REQUIRED_MIN_BUFFER_LEN`] bytes, or that a valid terminating byte
            /// appears before that limit.
            #[inline(always)]
            pub unsafe fn read_unchecked(input: &[u8], index: usize) -> Result<($ty, usize), Leb128DecodeError> {
                // SAFETY: The caller guarantees enough readable bytes for this type.
                let (value, consumed) =
                    unsafe { read_sleb_unchecked::<P>(input, index, <$ty>::BITS, Self::REQUIRED_MIN_BUFFER_LEN)? };
                Ok((value as $ty, consumed))
            }

            /// Tries to decode from the currently available bytes without bounds checks.
            ///
            /// This internal entry point is used by buffered readers that may have
            /// only part of a variable-length payload in their input buffer. It
            /// decodes while scanning for the terminating byte, so callers do not
            /// need a separate terminator pre-scan before calling the codec.
            ///
            /// # Parameters
            ///
            /// - `input`: Source byte buffer.
            /// - `index`: Start index in `input`.
            /// - `available`: Number of readable bytes currently available from
            ///   `index`.
            ///
            /// # Returns
            ///
            /// Returns `Ok(Some((value, consumed)))` when a complete value is
            /// decoded. Returns `Ok(None)` when more bytes are needed. Returns
            /// `Err((error, consumed))` when the payload is invalid and should be
            /// consumed before the error is reported.
            ///
            /// # Safety
            ///
            /// The caller must guarantee that `input.as_ptr().add(index)` is valid
            /// to read `available` bytes and that `available` is no greater than
            /// [`Self::REQUIRED_MIN_BUFFER_LEN`].
            #[inline(always)]
            pub(crate) unsafe fn read_available_unchecked(
                input: &[u8],
                index: usize,
                available: usize,
            ) -> Result<Option<($ty, usize)>, (Leb128DecodeError, usize)> {
                // SAFETY: The caller guarantees that exactly `available` bytes
                // are readable from `index`.
                unsafe {
                    read_sleb_available_unchecked::<P>(
                        input,
                        index,
                        <$ty>::BITS,
                        Self::REQUIRED_MIN_BUFFER_LEN,
                        available,
                    )
                }
                .map(|result| result.map(|(value, consumed)| (value as $ty, consumed)))
            }

            /// Encodes `value` into `output` starting at `index` without bounds checks.
            ///
            /// # Parameters
            ///
            /// - `output`: Destination byte buffer.
            /// - `index`: Start index in `output`.
            /// - `value`: Value to encode.
            ///
            /// # Returns
            ///
            /// Returns the number of written bytes.
            ///
            /// # Safety
            ///
            /// The caller must guarantee that `output.as_mut_ptr().add(index)` is valid
            /// to write [`Self::REQUIRED_MIN_BUFFER_LEN`] bytes.
            #[inline(always)]
            pub unsafe fn write_unchecked(output: &mut [u8], index: usize, value: $ty) -> usize {
                // SAFETY: The caller guarantees enough writable bytes for this type.
                unsafe { write_sleb_unchecked(output, index, value as i128) }
            }
        }
    };
}

impl_unsigned_leb128_codec!(u8);
impl_unsigned_leb128_codec!(u16);
impl_unsigned_leb128_codec!(u32);
impl_unsigned_leb128_codec!(u64);
impl_unsigned_leb128_codec!(u128);
impl_unsigned_leb128_codec!(usize);

impl_signed_leb128_codec!(i8);
impl_signed_leb128_codec!(i16);
impl_signed_leb128_codec!(i32);
impl_signed_leb128_codec!(i64);
impl_signed_leb128_codec!(i128);
impl_signed_leb128_codec!(isize);

#[inline(always)]
unsafe fn read_uleb_unchecked<P>(
    input: &[u8],
    index: usize,
    bits: u32,
    max_bytes: usize,
) -> Result<(u128, usize), Leb128DecodeError>
where
    P: DecodePolicy,
{
    // SAFETY: The caller guarantees enough readable bytes for the full maximum
    // payload width, which is exactly the `available` value passed here.
    match unsafe { read_uleb_available_unchecked::<P>(input, index, bits, max_bytes, max_bytes) } {
        Ok(Some(value)) => Ok(value),
        Ok(None) => unreachable!("maximum-width LEB128 input must complete or fail"),
        Err((error, _consumed)) => Err(error),
    }
}

#[inline(always)]
unsafe fn read_uleb_available_unchecked<P>(
    input: &[u8],
    index: usize,
    bits: u32,
    max_bytes: usize,
    available: usize,
) -> Result<Option<(u128, usize)>, (Leb128DecodeError, usize)>
where
    P: DecodePolicy,
{
    debug_assert!(available <= max_bytes, "available bytes exceed LEB128 maximum width");
    let mut value = 0u128;
    let mut shift = 0u32;
    // SAFETY: The caller guarantees that `available` bytes are readable from
    // `index`, so this base pointer can be advanced by every loop offset.
    let base = unsafe { input.as_ptr().add(index) };
    for offset in 0..available {
        // SAFETY: The caller guarantees enough readable bytes for this loop.
        let byte = unsafe { *base.add(offset) };
        let payload = u128::from(byte & 0x7F);
        value |= payload << shift;
        if byte & 0x80 == 0 {
            if offset == max_bytes - 1 && !unsigned_final_payload_fits(byte, bits, offset) {
                return Err(malformed_decode_error(index + offset, offset + 1));
            }
            let consumed = offset + 1;
            if P::STRICT && !has_canonical_uleb_len(value, consumed) {
                return Err(noncanonical_decode_error(index, consumed));
            }
            return Ok(Some((value, consumed)));
        }
        shift += 7;
    }
    if available < max_bytes {
        return Ok(None);
    }
    Err(malformed_decode_error(index + max_bytes - 1, max_bytes))
}

#[inline(always)]
unsafe fn read_sleb_unchecked<P>(
    input: &[u8],
    index: usize,
    bits: u32,
    max_bytes: usize,
) -> Result<(i128, usize), Leb128DecodeError>
where
    P: DecodePolicy,
{
    // SAFETY: The caller guarantees enough readable bytes for the full maximum
    // payload width, which is exactly the `available` value passed here.
    match unsafe { read_sleb_available_unchecked::<P>(input, index, bits, max_bytes, max_bytes) } {
        Ok(Some(value)) => Ok(value),
        Ok(None) => unreachable!("maximum-width LEB128 input must complete or fail"),
        Err((error, _consumed)) => Err(error),
    }
}

#[inline(always)]
unsafe fn read_sleb_available_unchecked<P>(
    input: &[u8],
    index: usize,
    bits: u32,
    max_bytes: usize,
    available: usize,
) -> Result<Option<(i128, usize)>, (Leb128DecodeError, usize)>
where
    P: DecodePolicy,
{
    debug_assert!(available <= max_bytes, "available bytes exceed LEB128 maximum width");
    let mut value = 0i128;
    let mut shift = 0u32;
    // SAFETY: The caller guarantees that `available` bytes are readable from
    // `index`, so this base pointer can be advanced by every loop offset.
    let base = unsafe { input.as_ptr().add(index) };
    for offset in 0..available {
        // SAFETY: The caller guarantees enough readable bytes for this loop.
        let byte = unsafe { *base.add(offset) };
        let payload = i128::from(byte & 0x7F);
        value |= payload << shift;
        if byte & 0x80 == 0 {
            if offset == max_bytes - 1 && !signed_final_payload_fits(byte, bits, offset) {
                return Err(malformed_decode_error(index + offset, offset + 1));
            }
            if byte & 0x40 != 0 && shift + 7 < i128::BITS {
                value |= (!0i128) << (shift + 7);
            }
            let consumed = offset + 1;
            if P::STRICT && !has_canonical_sleb_len(value, consumed) {
                return Err(noncanonical_decode_error(index, consumed));
            }
            return Ok(Some((value, consumed)));
        }
        shift += 7;
    }
    if available < max_bytes {
        return Ok(None);
    }
    Err(malformed_decode_error(index + max_bytes - 1, max_bytes))
}

/// Builds a malformed LEB128 error on the cold error path.
///
/// # Parameters
///
/// - `index`: Absolute byte index associated with the malformed payload.
/// - `consumed`: Number of bytes that should be consumed before reporting the
///   error.
///
/// # Returns
///
/// Returns the error and the byte count to consume.
#[cold]
#[inline(never)]
fn malformed_decode_error(index: usize, consumed: usize) -> (Leb128DecodeError, usize) {
    (
        Leb128DecodeError::new(Leb128DecodeErrorKind::Malformed, index),
        consumed,
    )
}

/// Builds a non-canonical LEB128 error on the cold error path.
///
/// # Parameters
///
/// - `index`: Absolute byte index at which the non-canonical payload starts.
/// - `consumed`: Number of bytes that should be consumed before reporting the
///   error.
///
/// # Returns
///
/// Returns the error and the byte count to consume.
#[cold]
#[inline(never)]
fn noncanonical_decode_error(index: usize, consumed: usize) -> (Leb128DecodeError, usize) {
    (
        Leb128DecodeError::new(Leb128DecodeErrorKind::NonCanonical, index),
        consumed,
    )
}

#[must_use]
#[inline(always)]
fn unsigned_final_payload_fits(byte: u8, bits: u32, offset: usize) -> bool {
    let used_bits = bits - offset as u32 * 7;
    byte >> used_bits == 0
}

#[must_use]
#[inline(always)]
fn signed_final_payload_fits(byte: u8, bits: u32, offset: usize) -> bool {
    let used_bits = bits - offset as u32 * 7;
    let payload = byte & 0x7F;
    let used_mask = ((1u16 << used_bits) - 1) as u8;
    let unused_mask = 0x7F & !used_mask;
    let sign_bit = 1u8 << (used_bits - 1);
    if payload & sign_bit == 0 {
        payload & unused_mask == 0
    } else {
        payload & unused_mask == unused_mask
    }
}

/// Checks whether an unsigned LEB128 value used its canonical encoded length.
///
/// # Parameters
///
/// - `value`: Decoded unsigned value.
/// - `actual_len`: Number of bytes consumed from the input.
///
/// # Returns
///
/// Returns `true` if `actual_len` is the canonical encoded length of `value`.
#[must_use]
#[inline(always)]
fn has_canonical_uleb_len(value: u128, actual_len: usize) -> bool {
    canonical_uleb_len(value) == actual_len
}

/// Checks whether a signed LEB128 value used its canonical encoded length.
///
/// # Parameters
///
/// - `value`: Decoded signed value.
/// - `actual_len`: Number of bytes consumed from the input.
///
/// # Returns
///
/// Returns `true` if `actual_len` is the canonical encoded length of `value`.
#[must_use]
#[inline(always)]
fn has_canonical_sleb_len(value: i128, actual_len: usize) -> bool {
    canonical_sleb_len(value) == actual_len
}

/// Computes the canonical unsigned LEB128 encoded length.
///
/// # Parameters
///
/// - `value`: Unsigned value to measure.
///
/// # Returns
///
/// Returns the number of bytes used by the canonical unsigned LEB128 encoding.
#[must_use]
#[inline(always)]
fn canonical_uleb_len(mut value: u128) -> usize {
    let mut len = 1;
    while value >= 0x80 {
        value >>= 7;
        len += 1;
    }
    len
}

/// Computes the canonical signed LEB128 encoded length.
///
/// # Parameters
///
/// - `value`: Signed value to measure.
///
/// # Returns
///
/// Returns the number of bytes used by the canonical signed LEB128 encoding.
#[must_use]
#[inline(always)]
fn canonical_sleb_len(mut value: i128) -> usize {
    let mut len = 0;
    loop {
        let byte = (value & 0x7F) as u8;
        let sign_bit_set = byte & 0x40 != 0;
        value >>= 7;
        len += 1;
        if (value == 0 && !sign_bit_set) || (value == -1 && sign_bit_set) {
            return len;
        }
    }
}

unsafe fn write_uleb_unchecked(output: &mut [u8], index: usize, mut value: u128) -> usize {
    let mut offset = 0;
    loop {
        let mut byte = (value & 0x7F) as u8;
        value >>= 7;
        if value != 0 {
            byte |= 0x80;
        }
        // SAFETY: The caller guarantees enough writable bytes for the encoded value.
        unsafe {
            *output.as_mut_ptr().add(index + offset) = byte;
        }
        offset += 1;
        if value == 0 {
            return offset;
        }
    }
}

unsafe fn write_sleb_unchecked(output: &mut [u8], index: usize, mut value: i128) -> usize {
    let mut offset = 0;
    loop {
        let mut byte = (value & 0x7F) as u8;
        let sign_bit_set = byte & 0x40 != 0;
        value >>= 7;
        let done = (value == 0 && !sign_bit_set) || (value == -1 && sign_bit_set);
        if !done {
            byte |= 0x80;
        }
        // SAFETY: The caller guarantees enough writable bytes for the encoded value.
        unsafe {
            *output.as_mut_ptr().add(index + offset) = byte;
        }
        offset += 1;
        if done {
            return offset;
        }
    }
}