Skip to main content

qubit_codec_binary/codec/
leb128_codec.rs

1// =============================================================================
2//    Copyright (c) 2026 Haixing Hu.
3//
4//    SPDX-License-Identifier: Apache-2.0
5//
6//    Licensed under the Apache License, Version 2.0.
7// =============================================================================
8
9use core::convert::Infallible;
10use core::marker::PhantomData;
11use core::num::NonZeroUsize;
12
13use qubit_codec::Codec;
14use qubit_codec::DecodeFailure;
15use qubit_utils::UncheckedSlice;
16use qubit_utils::nonzero;
17
18use crate::Leb128DecodeError;
19use crate::Leb128DecodePolicy;
20
21/// Maps detailed LEB128 decoding failures to the generic codec failure type.
22///
23/// Incomplete input preserves its minimum total byte requirement. Malformed
24/// and non-canonical input retains the original error and its consumed byte
25/// count so callers can advance past the invalid payload.
26#[inline]
27pub(in crate::codec) fn map_leb128_decode_failure(error: Leb128DecodeError) -> DecodeFailure<Leb128DecodeError> {
28    if let Some(required) = error.required() {
29        DecodeFailure::incomplete_with_source(error, required)
30    } else {
31        let consumed = error
32            .consumed()
33            .expect("invalid LEB128 decode errors always report consumed bytes");
34        DecodeFailure::invalid(error, consumed)
35    }
36}
37
38/// Type-level unchecked LEB128 codec.
39///
40/// Encoding is always canonical; `P` only affects decoding. Encoding-only
41/// callers should conventionally use [`crate::NonStrict`] because no decoding
42/// policy is applied on that path.
43///
44/// # Type Parameters
45///
46/// - `T`: Integer value type to decode from LEB128 bytes and encode into
47///   canonical LEB128 bytes.
48/// - `P`: Required type-level decoding policy implementing
49///   [`Leb128DecodePolicy`]. Use [`crate::Strict`] to reject non-canonical
50///   inputs, or [`crate::NonStrict`] to accept non-canonical inputs. This
51///   parameter does not affect canonical encoding.
52///
53/// The decoding policy is intentionally required so wire-format callers make
54/// the canonicality contract explicit.
55///
56/// ```compile_fail
57/// use qubit_codec_binary::Leb128Codec;
58///
59/// let _ = Leb128Codec::<u64>::default();
60/// ```
61///
62/// # Examples
63///
64/// ```
65/// use qubit_codec_binary::{
66///     Leb128Codec,
67///     NonStrict,
68/// };
69///
70/// let mut output = [0_u8; Leb128Codec::<u64, NonStrict>::MAX_ENCODE_UNITS_PER_VALUE];
71/// let written = unsafe {
72///     Leb128Codec::<u64, NonStrict>::encode(300, &mut output, 0)
73/// };
74/// assert_eq!(2, written);
75///
76/// let (decoded, consumed) = unsafe {
77///     Leb128Codec::<u64, NonStrict>::decode(&output[..written], 0)
78/// }.expect("canonical LEB128 value should decode");
79/// assert_eq!(300, decoded);
80/// assert_eq!(2, consumed.get());
81/// ```
82#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
83pub struct Leb128Codec<T, P> {
84    /// Associates the value and decode-policy types without storing either.
85    marker: PhantomData<fn() -> (T, P)>,
86}
87
88macro_rules! impl_unsigned_leb128_codec {
89    ($ty:ty) => {
90        impl<P> Leb128Codec<$ty, P>
91        where
92            P: Leb128DecodePolicy,
93        {
94            /// Minimum number of bytes that can represent a complete value.
95            pub const MIN_UNITS_PER_VALUE: usize = <Self as Codec>::MIN_UNITS_PER_VALUE;
96
97            /// Maximum number of bytes emitted when encoding this type.
98            pub const MAX_ENCODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_ENCODE_UNITS_PER_VALUE;
99
100            /// Maximum number of bytes consumed when decoding this type.
101            pub const MAX_DECODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_DECODE_UNITS_PER_VALUE;
102
103            /// Decodes a value from `input` starting at `input_index` without
104            /// bounds checks.
105            ///
106            /// # Parameters
107            ///
108            /// - `input`: Source byte buffer.
109            /// - `input_index`: Start index in `input`.
110            ///
111            /// # Returns
112            ///
113            /// Returns the decoded value and the non-zero number of consumed
114            /// bytes.
115            ///
116            /// # Errors
117            ///
118            /// Returns [`Leb128DecodeError`] if the bytes are incomplete,
119            /// malformed, or strict decoding rejects a non-canonical
120            /// representation.
121            ///
122            /// # Safety
123            ///
124            /// The caller must guarantee that `input_index` is a valid boundary
125            /// and at least [`Self::MIN_UNITS_PER_VALUE`] byte is readable
126            /// from `input_index`.
127            #[inline]
128            pub unsafe fn decode(input: &[u8], input_index: usize) -> Result<($ty, NonZeroUsize), Leb128DecodeError> {
129                debug_assert!(input.len().saturating_sub(input_index) >= Self::MIN_UNITS_PER_VALUE);
130
131                // SAFETY: The caller guarantees enough readable bytes for this
132                // type.
133                let (value, consumed) = unsafe {
134                    read_uleb_unchecked::<P>(input, input_index, <$ty>::BITS, Self::MAX_DECODE_UNITS_PER_VALUE)?
135                };
136                Ok((value as $ty, consumed))
137            }
138
139            /// Encodes `value` into `output` starting at `output_index` without
140            /// bounds checks.
141            ///
142            /// # Parameters
143            ///
144            /// - `value`: Value to encode.
145            /// - `output`: Destination byte buffer.
146            /// - `output_index`: Start index in `output`.
147            ///
148            /// # Returns
149            ///
150            /// Returns the number of written bytes.
151            ///
152            /// # Safety
153            ///
154            /// The caller must guarantee that the canonical unsigned LEB128
155            /// byte width of `value` is writable starting at `output_index`.
156            /// Reserving [`Self::MAX_ENCODE_UNITS_PER_VALUE`] bytes always satisfies
157            /// this requirement; for a known value, the exact
158            /// [`Codec::encode_len`] is sufficient.
159            #[must_use = "the returned byte count determines the encoded payload range"]
160            #[inline]
161            pub unsafe fn encode(value: $ty, output: &mut [u8], output_index: usize) -> usize {
162                // SAFETY: The caller guarantees enough writable bytes for the
163                // canonical representation of this value.
164                unsafe { write_uleb_unchecked(output, output_index, value as u128) }
165            }
166        }
167
168        impl<P> Codec for Leb128Codec<$ty, P>
169        where
170            P: Leb128DecodePolicy,
171        {
172            type Value = $ty;
173            type Unit = u8;
174            type DecodeError = Leb128DecodeError;
175            type EncodeError = Infallible;
176
177            const MIN_UNITS_PER_VALUE: usize = 1;
178            const MAX_ENCODE_UNITS_PER_VALUE: usize = (<$ty>::BITS as usize).div_ceil(7);
179            const MAX_DECODE_UNITS_PER_VALUE: usize = (<$ty>::BITS as usize).div_ceil(7);
180
181            #[inline]
182            fn encode_len(&self, value: &$ty) -> usize {
183                uleb_encoded_len(*value as u128)
184            }
185
186            #[inline]
187            unsafe fn decode(
188                &mut self,
189                input: &[u8],
190                input_index: usize,
191            ) -> Result<($ty, NonZeroUsize), DecodeFailure<Self::DecodeError>> {
192                debug_assert!(input.len().saturating_sub(input_index) >= Self::MIN_UNITS_PER_VALUE);
193
194                // SAFETY: The caller upholds the `Codec::decode`
195                // contract.
196                unsafe { Self::decode(input, input_index) }.map_err(map_leb128_decode_failure)
197            }
198
199            #[inline]
200            unsafe fn encode(
201                &mut self,
202                value: &$ty,
203                output: &mut [u8],
204                output_index: usize,
205            ) -> Result<usize, Self::EncodeError> {
206                let required = self.encode_len(value);
207                debug_assert!(output.len().saturating_sub(output_index) >= required);
208
209                // SAFETY: The `Codec::encode` contract provides either the
210                // exact canonical width or this type's maximum width.
211                let written = unsafe { Self::encode(*value, output, output_index) };
212                Ok(written)
213            }
214        }
215    };
216}
217
218macro_rules! impl_signed_leb128_codec {
219    ($ty:ty) => {
220        impl<P> Leb128Codec<$ty, P>
221        where
222            P: Leb128DecodePolicy,
223        {
224            /// Minimum number of bytes that can represent a complete value.
225            pub const MIN_UNITS_PER_VALUE: usize = <Self as Codec>::MIN_UNITS_PER_VALUE;
226
227            /// Maximum number of bytes emitted when encoding this type.
228            pub const MAX_ENCODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_ENCODE_UNITS_PER_VALUE;
229
230            /// Maximum number of bytes consumed when decoding this type.
231            pub const MAX_DECODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_DECODE_UNITS_PER_VALUE;
232
233            /// Decodes a value from `input` starting at `input_index` without bounds
234            /// checks.
235            ///
236            /// # Parameters
237            ///
238            /// - `input`: Source byte buffer.
239            /// - `input_index`: Start index in `input`.
240            ///
241            /// # Returns
242            ///
243            /// Returns the decoded value and the non-zero number of consumed
244            /// bytes.
245            ///
246            /// # Errors
247            ///
248            /// Returns [`Leb128DecodeError`] if the bytes are incomplete,
249            /// malformed, or strict decoding rejects a non-canonical
250            /// representation.
251            ///
252            /// # Safety
253            ///
254            /// The caller must guarantee that `input_index` is a valid boundary
255            /// and at least [`Self::MIN_UNITS_PER_VALUE`] byte is readable
256            /// from `input_index`.
257            #[inline]
258            pub unsafe fn decode(input: &[u8], input_index: usize) -> Result<($ty, NonZeroUsize), Leb128DecodeError> {
259                debug_assert!(input.len().saturating_sub(input_index) >= Self::MIN_UNITS_PER_VALUE);
260
261                // SAFETY: The caller guarantees enough readable bytes for this
262                // type.
263                let (value, consumed) = unsafe {
264                    read_sleb_unchecked::<P>(input, input_index, <$ty>::BITS, Self::MAX_DECODE_UNITS_PER_VALUE)?
265                };
266                Ok((value as $ty, consumed))
267            }
268
269            /// Encodes `value` into `output` starting at `output_index` without bounds
270            /// checks.
271            ///
272            /// # Parameters
273            ///
274            /// - `value`: Value to encode.
275            /// - `output`: Destination byte buffer.
276            /// - `output_index`: Start index in `output`.
277            ///
278            /// # Returns
279            ///
280            /// Returns the number of written bytes.
281            ///
282            /// # Safety
283            ///
284            /// The caller must guarantee that the canonical signed LEB128 byte
285            /// width of `value` is writable starting at `output_index`.
286            /// Reserving [`Self::MAX_ENCODE_UNITS_PER_VALUE`] bytes always satisfies
287            /// this requirement; for a known value, the exact
288            /// [`Codec::encode_len`] is sufficient.
289            #[must_use = "the returned byte count determines the encoded payload range"]
290            #[inline]
291            pub unsafe fn encode(value: $ty, output: &mut [u8], output_index: usize) -> usize {
292                // SAFETY: The caller guarantees enough writable bytes for the
293                // canonical representation of this value.
294                unsafe { write_sleb_unchecked(output, output_index, value as i128) }
295            }
296        }
297
298        impl<P> Codec for Leb128Codec<$ty, P>
299        where
300            P: Leb128DecodePolicy,
301        {
302            type Value = $ty;
303            type Unit = u8;
304            type DecodeError = Leb128DecodeError;
305            type EncodeError = Infallible;
306
307            const MIN_UNITS_PER_VALUE: usize = 1;
308            const MAX_ENCODE_UNITS_PER_VALUE: usize = (<$ty>::BITS as usize).div_ceil(7);
309            const MAX_DECODE_UNITS_PER_VALUE: usize = (<$ty>::BITS as usize).div_ceil(7);
310
311            #[inline]
312            fn encode_len(&self, value: &$ty) -> usize {
313                sleb_encoded_len(*value as i128)
314            }
315
316            #[inline]
317            unsafe fn decode(
318                &mut self,
319                input: &[u8],
320                input_index: usize,
321            ) -> Result<($ty, NonZeroUsize), DecodeFailure<Self::DecodeError>> {
322                debug_assert!(input.len().saturating_sub(input_index) >= Self::MIN_UNITS_PER_VALUE);
323
324                // SAFETY: The caller upholds the `Codec::decode`
325                // contract.
326                unsafe { Self::decode(input, input_index) }.map_err(map_leb128_decode_failure)
327            }
328
329            #[inline]
330            unsafe fn encode(
331                &mut self,
332                value: &$ty,
333                output: &mut [u8],
334                output_index: usize,
335            ) -> Result<usize, Self::EncodeError> {
336                let required = self.encode_len(value);
337                debug_assert!(output.len().saturating_sub(output_index) >= required);
338
339                // SAFETY: The `Codec::encode` contract provides either the
340                // exact canonical width or this type's maximum width.
341                let written = unsafe { Self::encode(*value, output, output_index) };
342                Ok(written)
343            }
344        }
345    };
346}
347
348impl_unsigned_leb128_codec!(u8);
349impl_unsigned_leb128_codec!(u16);
350impl_unsigned_leb128_codec!(u32);
351impl_unsigned_leb128_codec!(u64);
352impl_unsigned_leb128_codec!(u128);
353impl_unsigned_leb128_codec!(usize);
354
355impl_signed_leb128_codec!(i8);
356impl_signed_leb128_codec!(i16);
357impl_signed_leb128_codec!(i32);
358impl_signed_leb128_codec!(i64);
359impl_signed_leb128_codec!(i128);
360impl_signed_leb128_codec!(isize);
361
362/// Decodes an unsigned LEB128 value without bounds checks.
363///
364/// # Type Parameters
365///
366/// - `P`: Type-level decoding policy used to decide whether non-canonical
367///   encodings are accepted.
368///
369/// # Parameters
370///
371/// - `input`: Source byte buffer.
372/// - `index`: Start index in `input`.
373/// - `bits`: Bit width of the target integer type.
374/// - `max_bytes`: Maximum number of bytes allowed for that target width.
375///
376/// # Returns
377///
378/// Returns the decoded value and the non-zero number of consumed bytes.
379///
380/// # Errors
381///
382/// Returns [`Leb128DecodeError`] when the byte sequence is incomplete,
383/// malformed, or when `P` rejects a non-canonical encoding.
384///
385/// # Safety
386///
387/// The caller must guarantee that at least one byte is readable from `index`.
388#[inline]
389unsafe fn read_uleb_unchecked<P>(
390    input: &[u8],
391    index: usize,
392    bits: u32,
393    max_bytes: usize,
394) -> Result<(u128, NonZeroUsize), Leb128DecodeError>
395where
396    P: Leb128DecodePolicy,
397{
398    debug_assert!(input.len().saturating_sub(index) >= 1);
399
400    let available = input.len().saturating_sub(index).min(max_bytes);
401    // SAFETY: The caller guarantees that the currently available bytes are
402    // readable from `index`.
403    match unsafe { read_uleb_prefix_unchecked::<P>(input, index, bits, max_bytes, available) } {
404        Ok(Some((value, consumed))) => {
405            debug_assert!(consumed > 0);
406            // SAFETY: Prefix readers only return `Some` after consuming at
407            // least one terminating byte.
408            let consumed = nonzero(consumed);
409            Ok((value, consumed))
410        }
411        Ok(None) => {
412            debug_assert!(available < usize::MAX, "available byte count overflowed");
413            // SAFETY: Adding one to the available byte count produces a
414            // non-zero retry lower bound.
415            let required = nonzero(available + 1);
416            Err(Leb128DecodeError::incomplete(index, required, available))
417        }
418        Err(error) => Err(error),
419    }
420}
421
422/// Tries to decode an unsigned LEB128 value from currently available bytes.
423///
424/// # Type Parameters
425///
426/// - `P`: Type-level decoding policy used to decide whether non-canonical
427///   encodings are accepted.
428///
429/// # Parameters
430///
431/// - `input`: Source byte buffer.
432/// - `index`: Start index in `input`.
433/// - `bits`: Bit width of the target integer type.
434/// - `max_bytes`: Maximum number of bytes allowed for that target width.
435/// - `available`: Number of bytes currently readable from `index`.
436///
437/// # Returns
438///
439/// Returns `Ok(Some((value, consumed)))` when a complete value is decoded,
440/// `Ok(None)` when more bytes are needed, or `Err(error)` when the payload is
441/// invalid. Invalid errors carry the consumable byte count.
442///
443/// # Safety
444///
445/// The caller must guarantee that `input.as_ptr().add(index)` is valid to read
446/// `available` bytes and that `available <= max_bytes`.
447#[inline]
448unsafe fn read_uleb_prefix_unchecked<P>(
449    input: &[u8],
450    index: usize,
451    bits: u32,
452    max_bytes: usize,
453    available: usize,
454) -> Result<Option<(u128, usize)>, Leb128DecodeError>
455where
456    P: Leb128DecodePolicy,
457{
458    debug_assert!(available <= max_bytes, "available bytes exceed LEB128 maximum width");
459    let mut value = 0u128;
460    let mut shift = 0u32;
461    for offset in 0..available {
462        // SAFETY: The caller guarantees enough readable bytes for this loop.
463        let byte = unsafe { UncheckedSlice::read(input, index + offset) };
464        let payload = u128::from(byte & 0x7F);
465        value |= payload << shift;
466        if byte & 0x80 == 0 {
467            if offset == max_bytes - 1 && !unsigned_final_payload_fits(byte, bits, offset) {
468                return Err(malformed_decode_error(index, index + offset, offset + 1));
469            }
470            let consumed = offset + 1;
471            if P::STRICT && !is_canonical_uleb_terminal(offset, byte) {
472                return Err(noncanonical_decode_error(index, consumed));
473            }
474            return Ok(Some((value, consumed)));
475        }
476        shift += 7;
477    }
478    if available < max_bytes {
479        return Ok(None);
480    }
481    Err(malformed_decode_error(index, index + max_bytes - 1, max_bytes))
482}
483
484/// Decodes a signed LEB128 value without bounds checks.
485///
486/// # Type Parameters
487///
488/// - `P`: Type-level decoding policy used to decide whether non-canonical
489///   encodings are accepted.
490///
491/// # Parameters
492///
493/// - `input`: Source byte buffer.
494/// - `index`: Start index in `input`.
495/// - `bits`: Bit width of the target integer type.
496/// - `max_bytes`: Maximum number of bytes allowed for that target width.
497///
498/// # Returns
499///
500/// Returns the decoded value and the non-zero number of consumed bytes.
501///
502/// # Errors
503///
504/// Returns [`Leb128DecodeError`] when the byte sequence is incomplete,
505/// malformed, or when `P` rejects a non-canonical encoding.
506///
507/// # Safety
508///
509/// The caller must guarantee that at least one byte is readable from `index`.
510#[inline]
511unsafe fn read_sleb_unchecked<P>(
512    input: &[u8],
513    index: usize,
514    bits: u32,
515    max_bytes: usize,
516) -> Result<(i128, NonZeroUsize), Leb128DecodeError>
517where
518    P: Leb128DecodePolicy,
519{
520    debug_assert!(input.len().saturating_sub(index) >= 1);
521
522    let available = input.len().saturating_sub(index).min(max_bytes);
523    // SAFETY: The caller guarantees that the currently available bytes are
524    // readable from `index`.
525    match unsafe { read_sleb_prefix_unchecked::<P>(input, index, bits, max_bytes, available) } {
526        Ok(Some((value, consumed))) => {
527            debug_assert!(consumed > 0);
528            // SAFETY: Prefix readers only return `Some` after consuming at
529            // least one terminating byte.
530            let consumed = nonzero(consumed);
531            Ok((value, consumed))
532        }
533        Ok(None) => {
534            debug_assert!(available < usize::MAX, "available byte count overflowed");
535            // SAFETY: Adding one to the available byte count produces a
536            // non-zero retry lower bound.
537            let required = nonzero(available + 1);
538            Err(Leb128DecodeError::incomplete(index, required, available))
539        }
540        Err(error) => Err(error),
541    }
542}
543
544/// Tries to decode a signed LEB128 value from currently available bytes.
545///
546/// # Type Parameters
547///
548/// - `P`: Type-level decoding policy used to decide whether non-canonical
549///   encodings are accepted.
550///
551/// # Parameters
552///
553/// - `input`: Source byte buffer.
554/// - `index`: Start index in `input`.
555/// - `bits`: Bit width of the target integer type.
556/// - `max_bytes`: Maximum number of bytes allowed for that target width.
557/// - `available`: Number of bytes currently readable from `index`.
558///
559/// # Returns
560///
561/// Returns `Ok(Some((value, consumed)))` when a complete value is decoded,
562/// `Ok(None)` when more bytes are needed, or `Err(error)` when the payload is
563/// invalid. Invalid errors carry the consumable byte count.
564///
565/// # Safety
566///
567/// The caller must guarantee that `input.as_ptr().add(index)` is valid to read
568/// `available` bytes and that `available <= max_bytes`.
569#[inline]
570unsafe fn read_sleb_prefix_unchecked<P>(
571    input: &[u8],
572    index: usize,
573    bits: u32,
574    max_bytes: usize,
575    available: usize,
576) -> Result<Option<(i128, usize)>, Leb128DecodeError>
577where
578    P: Leb128DecodePolicy,
579{
580    debug_assert!(available <= max_bytes, "available bytes exceed LEB128 maximum width");
581    let mut value = 0i128;
582    let mut shift = 0u32;
583    let mut previous_byte = 0u8;
584    for offset in 0..available {
585        // SAFETY: The caller guarantees enough readable bytes for this loop.
586        let byte = unsafe { UncheckedSlice::read(input, index + offset) };
587        let payload = i128::from(byte & 0x7F);
588        value |= payload << shift;
589        if byte & 0x80 == 0 {
590            if offset == max_bytes - 1 && !signed_final_payload_fits(byte, bits, offset) {
591                return Err(malformed_decode_error(index, index + offset, offset + 1));
592            }
593            if byte & 0x40 != 0 && shift + 7 < i128::BITS {
594                value |= (!0i128) << (shift + 7);
595            }
596            let consumed = offset + 1;
597            if P::STRICT && !is_canonical_sleb_terminal(offset, previous_byte, byte) {
598                return Err(noncanonical_decode_error(index, consumed));
599            }
600            return Ok(Some((value, consumed)));
601        }
602        previous_byte = byte;
603        shift += 7;
604    }
605    if available < max_bytes {
606        return Ok(None);
607    }
608    Err(malformed_decode_error(index, index + max_bytes - 1, max_bytes))
609}
610
611/// Builds a malformed LEB128 error on the cold error path.
612///
613/// # Parameters
614///
615/// - `start_index`: Absolute byte index where the malformed payload starts.
616/// - `error_index`: Absolute byte index associated with the malformed payload.
617/// - `consumed`: Number of bytes that should be consumed before reporting the
618///   error.
619///
620/// # Returns
621///
622/// Returns the error carrying the byte count to consume.
623#[cold]
624fn malformed_decode_error(start_index: usize, error_index: usize, consumed: usize) -> Leb128DecodeError {
625    debug_assert!(consumed > 0, "malformed LEB128 errors must consume bytes");
626    // SAFETY: All malformed call sites pass either `offset + 1` or `max_bytes`,
627    // both of which are non-zero for supported LEB128 codecs.
628    let consumed = nonzero(consumed);
629    Leb128DecodeError::malformed(start_index, error_index, consumed)
630}
631
632/// Builds a non-canonical LEB128 error on the cold error path.
633///
634/// # Parameters
635///
636/// - `index`: Absolute byte index at which the non-canonical payload starts.
637/// - `consumed`: Number of bytes that should be consumed before reporting the
638///   error.
639///
640/// # Returns
641///
642/// Returns the error carrying the byte count to consume.
643#[cold]
644fn noncanonical_decode_error(index: usize, consumed: usize) -> Leb128DecodeError {
645    debug_assert!(consumed > 0, "non-canonical LEB128 errors must consume bytes");
646    // SAFETY: Non-canonical errors are detected only after reading at least one
647    // terminating byte.
648    let consumed = nonzero(consumed);
649    Leb128DecodeError::noncanonical(index, consumed)
650}
651
652/// Checks whether the final unsigned LEB128 payload byte fits the target width.
653///
654/// # Parameters
655///
656/// - `byte`: Final LEB128 byte to validate.
657/// - `bits`: Bit width of the target unsigned integer type.
658/// - `offset`: Zero-based byte offset of `byte` within the encoded value.
659///
660/// # Returns
661///
662/// Returns `true` if the unused payload bits are all zero.
663#[must_use]
664#[inline]
665fn unsigned_final_payload_fits(byte: u8, bits: u32, offset: usize) -> bool {
666    let used_bits = bits - offset as u32 * 7;
667    byte >> used_bits == 0
668}
669
670/// Checks whether the final signed LEB128 payload byte fits the target width.
671///
672/// # Parameters
673///
674/// - `byte`: Final LEB128 byte to validate.
675/// - `bits`: Bit width of the target signed integer type.
676/// - `offset`: Zero-based byte offset of `byte` within the encoded value.
677///
678/// # Returns
679///
680/// Returns `true` if the unused payload bits are a valid sign extension.
681#[must_use]
682#[inline]
683fn signed_final_payload_fits(byte: u8, bits: u32, offset: usize) -> bool {
684    let used_bits = bits - offset as u32 * 7;
685    let payload = byte & 0x7F;
686    let used_mask = ((1u16 << used_bits) - 1) as u8;
687    let unused_mask = 0x7F & !used_mask;
688    let sign_bit = 1u8 << (used_bits - 1);
689    if payload & sign_bit == 0 {
690        payload & unused_mask == 0
691    } else {
692        payload & unused_mask == unused_mask
693    }
694}
695
696/// Checks whether an unsigned LEB128 terminal byte is canonical.
697///
698/// # Parameters
699///
700/// - `offset`: Zero-based byte offset of the terminal byte.
701/// - `byte`: Terminal byte without a continuation flag.
702///
703/// # Returns
704///
705/// Returns `true` when the terminal byte is necessary to encode the value.
706#[must_use]
707#[inline]
708fn is_canonical_uleb_terminal(offset: usize, byte: u8) -> bool {
709    offset == 0 || byte & 0x7F != 0
710}
711
712/// Checks whether a signed LEB128 terminal byte is canonical.
713///
714/// # Parameters
715///
716/// - `offset`: Zero-based byte offset of the terminal byte.
717/// - `previous_byte`: The preceding continuation byte when `offset` is
718///   non-zero.
719/// - `byte`: Terminal byte without a continuation flag.
720///
721/// # Returns
722///
723/// Returns `true` when the terminal byte is necessary to preserve the signed
724/// value represented by the preceding byte.
725#[must_use]
726#[inline]
727fn is_canonical_sleb_terminal(offset: usize, previous_byte: u8, byte: u8) -> bool {
728    if offset == 0 {
729        return true;
730    }
731    let payload = byte & 0x7F;
732    !((payload == 0 && previous_byte & 0x40 == 0) || (payload == 0x7F && previous_byte & 0x40 != 0))
733}
734
735/// Encodes an unsigned integer as canonical LEB128 without bounds checks.
736///
737/// # Parameters
738///
739/// - `output`: Destination byte buffer.
740/// - `index`: Start index in `output`.
741/// - `value`: Unsigned value to encode.
742///
743/// # Returns
744///
745/// Returns the number of written bytes.
746///
747/// # Safety
748///
749/// The caller must guarantee that `output.as_mut_ptr().add(index)` is valid to
750/// write the full canonical LEB128 representation of `value`.
751unsafe fn write_uleb_unchecked(output: &mut [u8], index: usize, mut value: u128) -> usize {
752    let mut offset = 0;
753    loop {
754        let mut byte = (value & 0x7F) as u8;
755        value >>= 7;
756        if value != 0 {
757            byte |= 0x80;
758        }
759        // SAFETY: The caller guarantees enough writable bytes for the encoded
760        // value.
761        unsafe {
762            UncheckedSlice::write(output, index + offset, byte);
763        }
764        offset += 1;
765        if value == 0 {
766            return offset;
767        }
768    }
769}
770
771/// Computes the canonical unsigned LEB128 byte width for `value`.
772#[must_use]
773#[inline]
774pub(in crate::codec) fn uleb_encoded_len(mut value: u128) -> usize {
775    let mut len = 0;
776    loop {
777        value >>= 7;
778        len += 1;
779        if value == 0 {
780            return len;
781        }
782    }
783}
784
785/// Encodes a signed integer as canonical LEB128 without bounds checks.
786///
787/// # Parameters
788///
789/// - `output`: Destination byte buffer.
790/// - `index`: Start index in `output`.
791/// - `value`: Signed value to encode.
792///
793/// # Returns
794///
795/// Returns the number of written bytes.
796///
797/// # Safety
798///
799/// The caller must guarantee that `output.as_mut_ptr().add(index)` is valid to
800/// write the full canonical LEB128 representation of `value`.
801unsafe fn write_sleb_unchecked(output: &mut [u8], index: usize, mut value: i128) -> usize {
802    let mut offset = 0;
803    loop {
804        let mut byte = (value & 0x7F) as u8;
805        let sign_bit_set = byte & 0x40 != 0;
806        value >>= 7;
807        let done = (value == 0 && !sign_bit_set) || (value == -1 && sign_bit_set);
808        if !done {
809            byte |= 0x80;
810        }
811        // SAFETY: The caller guarantees enough writable bytes for the encoded
812        // value.
813        unsafe {
814            UncheckedSlice::write(output, index + offset, byte);
815        }
816        offset += 1;
817        if done {
818            return offset;
819        }
820    }
821}
822
823/// Computes the canonical signed LEB128 byte width for `value`.
824#[must_use]
825#[inline]
826fn sleb_encoded_len(mut value: i128) -> usize {
827    let mut len = 0;
828    loop {
829        let byte = (value & 0x7F) as u8;
830        let sign_bit_set = byte & 0x40 != 0;
831        value >>= 7;
832        let done = (value == 0 && !sign_bit_set) || (value == -1 && sign_bit_set);
833        len += 1;
834        if done {
835            return len;
836        }
837    }
838}