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