Skip to main content

qubit_codec_binary/codec/
leb128_decode_error.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// =============================================================================
8use core::fmt;
9use core::fmt::Display;
10use core::fmt::Formatter;
11use core::num::NonZeroUsize;
12use std::error::Error;
13
14use qubit_utils::nonzero;
15
16use super::internal::leb128_decode_error_details::Leb128DecodeErrorDetails;
17use crate::Leb128DecodeErrorKind;
18
19/// Error reported while decoding a LEB128 integer from a byte buffer.
20///
21/// # Examples
22///
23/// ```
24/// use core::num::NonZeroUsize;
25/// use qubit_codec_binary::Leb128DecodeError;
26///
27/// let error = Leb128DecodeError::incomplete(
28///     4,
29///     NonZeroUsize::new(3).expect("three is non-zero"),
30///     1,
31/// );
32/// assert_eq!(error.start_index(), 4);
33/// assert_eq!(error.required().map(NonZeroUsize::get), Some(3));
34/// assert_eq!(error.additional().map(NonZeroUsize::get), Some(2));
35/// ```
36#[must_use]
37#[derive(Clone, Copy, Debug, Eq, PartialEq)]
38pub struct Leb128DecodeError {
39    /// Absolute byte index where the attempted value starts.
40    start_index: usize,
41    /// Absolute byte index where the error became observable.
42    error_index: usize,
43    /// Kind-specific context for the decode failure.
44    details: Leb128DecodeErrorDetails,
45}
46
47impl Leb128DecodeError {
48    /// Creates an incomplete-input decoding error.
49    ///
50    /// # Parameters
51    ///
52    /// - `start_index`: Byte index where the incomplete value starts.
53    /// - `required`: Non-zero lower bound for total bytes that must be readable
54    ///   from `start_index` before decoding can make progress.
55    /// - `available`: Bytes currently available from `start_index`.
56    ///
57    /// # Returns
58    ///
59    /// Returns an error carrying incomplete-input context.
60    ///
61    /// # Panics
62    ///
63    /// Panics when `required <= available`, or when the one-past-available
64    /// error boundary overflows `usize`.
65    pub const fn incomplete(start_index: usize, required: NonZeroUsize, available: usize) -> Self {
66        assert!(
67            required.get() > available,
68            "incomplete LEB128 required bytes must exceed available bytes",
69        );
70        Self {
71            start_index,
72            error_index: add_offset(start_index, available),
73            details: Leb128DecodeErrorDetails::Incomplete { required, available },
74        }
75    }
76
77    /// Creates a malformed-input decoding error.
78    ///
79    /// # Parameters
80    ///
81    /// - `start_index`: Byte index where the malformed value starts.
82    /// - `error_index`: Byte index at which the malformed input was detected.
83    /// - `consumed`: Non-zero bytes the caller may consume to make progress.
84    ///
85    /// # Returns
86    ///
87    /// Returns an error carrying malformed-input context.
88    ///
89    /// # Panics
90    ///
91    /// Panics when the consumed span end overflows `usize`, or when
92    /// `error_index` is outside the consumed span.
93    pub const fn malformed(start_index: usize, error_index: usize, consumed: NonZeroUsize) -> Self {
94        assert_error_index_in_consumed_span(start_index, error_index, consumed);
95        Self {
96            start_index,
97            error_index,
98            details: Leb128DecodeErrorDetails::Invalid {
99                kind: Leb128DecodeErrorKind::Malformed,
100                consumed,
101            },
102        }
103    }
104
105    /// Creates a non-canonical-input decoding error.
106    ///
107    /// # Parameters
108    ///
109    /// - `start_index`: Byte index where the non-canonical value starts.
110    /// - `consumed`: Non-zero bytes the caller may consume to make progress.
111    ///
112    /// # Returns
113    ///
114    /// Returns an error carrying non-canonical-input context.
115    ///
116    /// # Panics
117    ///
118    /// Panics when the last consumed byte index overflows `usize`.
119    pub const fn noncanonical(start_index: usize, consumed: NonZeroUsize) -> Self {
120        Self {
121            start_index,
122            error_index: last_consumed_index(start_index, consumed),
123            details: Leb128DecodeErrorDetails::Invalid {
124                kind: Leb128DecodeErrorKind::NonCanonical,
125                consumed,
126            },
127        }
128    }
129
130    /// Returns the decoding error kind.
131    ///
132    /// # Returns
133    ///
134    /// Returns [`Leb128DecodeErrorKind::Incomplete`] for an incomplete prefix,
135    /// or the specific invalid-input kind for a rejected payload.
136    #[inline]
137    pub const fn kind(self) -> Leb128DecodeErrorKind {
138        match self.details {
139            Leb128DecodeErrorDetails::Incomplete { .. } => Leb128DecodeErrorKind::Incomplete,
140            Leb128DecodeErrorDetails::Invalid { kind, .. } => kind,
141        }
142    }
143
144    /// Returns the absolute byte index where the attempted value starts.
145    ///
146    /// # Returns
147    ///
148    /// Returns the byte offset at which decoding began.
149    #[must_use]
150    #[inline]
151    pub const fn start_index(self) -> usize {
152        self.start_index
153    }
154
155    /// Returns the absolute byte index where the error was detected.
156    ///
157    /// # Returns
158    ///
159    /// Returns the byte index that made the error observable. For incomplete
160    /// input this is the one-past-available boundary where the next byte would
161    /// be required, so it may be equal to the input length visible to the
162    /// caller.
163    #[must_use]
164    #[inline]
165    pub const fn error_index(self) -> usize {
166        self.error_index
167    }
168
169    /// Returns bytes that may be consumed after an invalid-input error.
170    ///
171    /// # Returns
172    ///
173    /// Returns `Some(consumed)` for invalid input, or `None` for incomplete
174    /// input.
175    ///
176    /// An unterminated over-width value may leave its tail unread after this
177    /// count. Advancing by the reported count does not establish the start of
178    /// the next protocol field. Recover only at an outer framing boundary or
179    /// a trusted checkpoint. The codec itself does not advance a caller-owned
180    /// cursor.
181    ///
182    /// # Examples
183    ///
184    /// ```
185    /// use qubit_codec_binary::{Leb128Codec, Leb128DecodeErrorKind, NonStrict};
186    ///
187    /// let input = [0x80, 0x80, 0x01, 0x2a];
188    /// // SAFETY: The non-empty slice provides the required first readable byte.
189    /// let error = unsafe { Leb128Codec::<u8, NonStrict>::decode(&input, 0) }
190    ///     .expect_err("u8 cannot use two unterminated LEB128 bytes");
191    /// assert_eq!(Leb128DecodeErrorKind::Malformed, error.kind());
192    /// assert_eq!(Some(2), error.consumed().map(|count| count.get()));
193    /// // The unread 0x01 may still belong to the rejected over-width value.
194    /// // An outer framing boundary is needed before decoding the next field.
195    /// ```
196    #[inline]
197    pub const fn consumed(self) -> Option<NonZeroUsize> {
198        match self.details {
199            Leb128DecodeErrorDetails::Incomplete { .. } => None,
200            Leb128DecodeErrorDetails::Invalid { consumed, .. } => Some(consumed),
201        }
202    }
203
204    /// Returns whether this error reports an incomplete input prefix.
205    ///
206    /// # Returns
207    ///
208    /// Returns `true` only for an incomplete input prefix.
209    #[must_use]
210    #[inline]
211    pub const fn is_incomplete(self) -> bool {
212        matches!(self.details, Leb128DecodeErrorDetails::Incomplete { .. })
213    }
214
215    /// Returns whether this error reports malformed input.
216    ///
217    /// # Returns
218    ///
219    /// Returns `true` only for a malformed payload.
220    #[must_use]
221    #[inline]
222    pub const fn is_malformed(self) -> bool {
223        matches!(
224            self.details,
225            Leb128DecodeErrorDetails::Invalid {
226                kind: Leb128DecodeErrorKind::Malformed,
227                ..
228            }
229        )
230    }
231
232    /// Returns whether this error reports a non-canonical representation.
233    ///
234    /// # Returns
235    ///
236    /// Returns `true` only for a non-canonical payload rejected by strict
237    /// decoding.
238    #[must_use]
239    #[inline]
240    pub const fn is_noncanonical(self) -> bool {
241        matches!(
242            self.details,
243            Leb128DecodeErrorDetails::Invalid {
244                kind: Leb128DecodeErrorKind::NonCanonical,
245                ..
246            }
247        )
248    }
249
250    /// Returns a lower bound for bytes required to continue incomplete
251    /// decoding.
252    ///
253    /// # Returns
254    ///
255    /// Returns `Some(required)` for incomplete input, or `None` otherwise. The
256    /// returned value is a non-zero lower bound for the total readable bytes
257    /// required from [`Self::start_index`] before decoding can make progress;
258    /// it does not guarantee that the value will be complete at exactly that
259    /// length.
260    #[inline]
261    pub const fn required(self) -> Option<NonZeroUsize> {
262        match self.details {
263            Leb128DecodeErrorDetails::Incomplete { required, .. } => Some(required),
264            Leb128DecodeErrorDetails::Invalid { .. } => None,
265        }
266    }
267
268    /// Returns additional bytes required to continue incomplete decoding.
269    ///
270    /// # Returns
271    ///
272    /// Returns `Some(additional)` for incomplete input, or `None` otherwise.
273    /// The value is `required - available` and is guaranteed to be non-zero.
274    #[inline]
275    pub const fn additional(self) -> Option<NonZeroUsize> {
276        match self.details {
277            Leb128DecodeErrorDetails::Incomplete { required, available } => {
278                let additional = required.get() - available;
279                Some(nonzero(additional))
280            }
281            Leb128DecodeErrorDetails::Invalid { .. } => None,
282        }
283    }
284
285    /// Returns bytes available for an incomplete value.
286    ///
287    /// # Returns
288    ///
289    /// Returns `Some(available)` for incomplete input, or `None` otherwise.
290    #[inline]
291    pub const fn available(self) -> Option<usize> {
292        match self.details {
293            Leb128DecodeErrorDetails::Incomplete { available, .. } => Some(available),
294            Leb128DecodeErrorDetails::Invalid { .. } => None,
295        }
296    }
297}
298
299impl Display for Leb128DecodeError {
300    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
301        match self.details {
302            Leb128DecodeErrorDetails::Incomplete { required, available } => {
303                write!(
304                    formatter,
305                    "{} at byte {}: need at least {} bytes, only {} available (next byte boundary {})",
306                    Leb128DecodeErrorKind::Incomplete,
307                    self.start_index,
308                    required,
309                    available,
310                    self.error_index,
311                )
312            }
313            Leb128DecodeErrorDetails::Invalid { kind, consumed } => {
314                write!(
315                    formatter,
316                    "{} at byte {}: detected at byte {}; consumable byte count: {}",
317                    kind, self.start_index, self.error_index, consumed,
318                )
319            }
320        }
321    }
322}
323
324impl Error for Leb128DecodeError {}
325
326/// Adds an absolute byte offset to an index.
327///
328/// # Parameters
329///
330/// - `index`: Base byte index.
331/// - `offset`: Byte offset to add.
332///
333/// # Returns
334///
335/// Returns `index + offset`.
336///
337/// # Panics
338///
339/// Panics when the sum overflows `usize`.
340const fn add_offset(index: usize, offset: usize) -> usize {
341    match index.checked_add(offset) {
342        Some(value) => value,
343        None => panic!("LEB128 byte index overflow"),
344    }
345}
346
347/// Returns the absolute index of the last consumed byte.
348///
349/// # Parameters
350///
351/// - `start_index`: Byte index where the value starts.
352/// - `consumed`: Non-zero number of consumed bytes.
353///
354/// # Returns
355///
356/// Returns `start_index + consumed - 1`.
357///
358/// # Panics
359///
360/// Panics when the index overflows `usize`.
361const fn last_consumed_index(start_index: usize, consumed: NonZeroUsize) -> usize {
362    add_offset(start_index, consumed.get() - 1)
363}
364
365/// Validates that an error index lies inside a consumed byte span.
366///
367/// # Parameters
368///
369/// - `start_index`: Byte index where the value starts.
370/// - `error_index`: Byte index where the error was detected.
371/// - `consumed`: Non-zero number of consumed bytes.
372///
373/// # Panics
374///
375/// Panics when `error_index` is before `start_index` or after the last consumed
376/// byte.
377const fn assert_error_index_in_consumed_span(start_index: usize, error_index: usize, consumed: NonZeroUsize) {
378    let last_index = last_consumed_index(start_index, consumed);
379    assert!(
380        error_index >= start_index,
381        "LEB128 error index must not precede value start",
382    );
383    assert!(
384        error_index <= last_index,
385        "LEB128 error index must lie inside consumed input",
386    );
387}