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