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