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