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