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;
186 /// use qubit_codec_binary::Leb128DecodeErrorKind;
187 /// use qubit_codec_binary::NonStrict;
188 ///
189 /// let input = [0x80, 0x80, 0x01, 0x2a];
190 /// // SAFETY: The non-empty slice provides the required first readable byte.
191 /// let error = unsafe { Leb128Codec::<u8, NonStrict>::decode(&input, 0) }
192 /// .expect_err("u8 cannot use two unterminated LEB128 bytes");
193 /// assert_eq!(Leb128DecodeErrorKind::Malformed, error.kind());
194 /// assert_eq!(Some(2), error.consumed().map(|count| count.get()));
195 /// // The unread 0x01 may still belong to the rejected over-width value.
196 /// // An outer framing boundary is needed before decoding the next field.
197 /// ```
198 #[inline]
199 pub const fn consumed(self) -> Option<NonZeroUsize> {
200 match self.details {
201 Leb128DecodeErrorDetails::Incomplete { .. } => None,
202 Leb128DecodeErrorDetails::Invalid { consumed, .. } => Some(consumed),
203 }
204 }
205
206 /// Returns whether this error reports an incomplete input prefix.
207 ///
208 /// # Returns
209 ///
210 /// Returns `true` only for an incomplete input prefix.
211 #[must_use]
212 #[inline]
213 pub const fn is_incomplete(self) -> bool {
214 matches!(self.details, Leb128DecodeErrorDetails::Incomplete { .. })
215 }
216
217 /// Returns whether this error reports malformed input.
218 ///
219 /// # Returns
220 ///
221 /// Returns `true` only for a malformed payload.
222 #[must_use]
223 #[inline]
224 pub const fn is_malformed(self) -> bool {
225 matches!(
226 self.details,
227 Leb128DecodeErrorDetails::Invalid {
228 kind: Leb128DecodeErrorKind::Malformed,
229 ..
230 }
231 )
232 }
233
234 /// Returns whether this error reports a non-canonical representation.
235 ///
236 /// # Returns
237 ///
238 /// Returns `true` only for a non-canonical payload rejected by strict
239 /// decoding.
240 #[must_use]
241 #[inline]
242 pub const fn is_noncanonical(self) -> bool {
243 matches!(
244 self.details,
245 Leb128DecodeErrorDetails::Invalid {
246 kind: Leb128DecodeErrorKind::NonCanonical,
247 ..
248 }
249 )
250 }
251
252 /// Returns a lower bound for bytes required to continue incomplete
253 /// decoding.
254 ///
255 /// # Returns
256 ///
257 /// Returns `Some(required)` for incomplete input, or `None` otherwise. The
258 /// returned value is a non-zero lower bound for the total readable bytes
259 /// required from [`Self::start_index`] before decoding can make progress;
260 /// it does not guarantee that the value will be complete at exactly that
261 /// length.
262 #[inline]
263 pub const fn required(self) -> Option<NonZeroUsize> {
264 match self.details {
265 Leb128DecodeErrorDetails::Incomplete { required, .. } => Some(required),
266 Leb128DecodeErrorDetails::Invalid { .. } => None,
267 }
268 }
269
270 /// Returns additional bytes required to continue incomplete decoding.
271 ///
272 /// # Returns
273 ///
274 /// Returns `Some(additional)` for incomplete input, or `None` otherwise.
275 /// The value is `required - available` and is guaranteed to be non-zero.
276 #[inline]
277 pub const fn additional(self) -> Option<NonZeroUsize> {
278 match self.details {
279 Leb128DecodeErrorDetails::Incomplete { required, available } => {
280 let additional = required.get() - available;
281 Some(nonzero(additional))
282 }
283 Leb128DecodeErrorDetails::Invalid { .. } => None,
284 }
285 }
286
287 /// Returns bytes available for an incomplete value.
288 ///
289 /// # Returns
290 ///
291 /// Returns `Some(available)` for incomplete input, or `None` otherwise.
292 #[inline]
293 pub const fn available(self) -> Option<usize> {
294 match self.details {
295 Leb128DecodeErrorDetails::Incomplete { available, .. } => Some(available),
296 Leb128DecodeErrorDetails::Invalid { .. } => None,
297 }
298 }
299}
300
301impl Display for Leb128DecodeError {
302 /// Formats the error with its kind, byte positions, and recovery context.
303 ///
304 /// # Parameters
305 ///
306 /// - `formatter`: Destination formatter for the error message.
307 ///
308 /// # Errors
309 ///
310 /// Returns [`fmt::Error`] if writing the formatted message fails.
311 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
312 match self.details {
313 Leb128DecodeErrorDetails::Incomplete { required, available } => {
314 write!(
315 formatter,
316 "{} at byte {}: need at least {} bytes, only {} available (next byte boundary {})",
317 Leb128DecodeErrorKind::Incomplete,
318 self.start_index,
319 required,
320 available,
321 self.error_index,
322 )
323 }
324 Leb128DecodeErrorDetails::Invalid { kind, consumed } => {
325 write!(
326 formatter,
327 "{} at byte {}: detected at byte {}; consumable byte count: {}",
328 kind, self.start_index, self.error_index, consumed,
329 )
330 }
331 }
332 }
333}
334
335impl Error for Leb128DecodeError {}
336
337/// Adds an absolute byte offset to an index.
338///
339/// # Parameters
340///
341/// - `index`: Base byte index.
342/// - `offset`: Byte offset to add.
343///
344/// # Returns
345///
346/// Returns `index + offset`.
347///
348/// # Panics
349///
350/// Panics when the sum overflows `usize`.
351const fn add_offset(index: usize, offset: usize) -> usize {
352 match index.checked_add(offset) {
353 Some(value) => value,
354 None => panic!("LEB128 byte index overflow"),
355 }
356}
357
358/// Returns the absolute index of the last consumed byte.
359///
360/// # Parameters
361///
362/// - `start_index`: Byte index where the value starts.
363/// - `consumed`: Non-zero number of consumed bytes.
364///
365/// # Returns
366///
367/// Returns `start_index + consumed - 1`.
368///
369/// # Panics
370///
371/// Panics when the index overflows `usize`.
372const fn last_consumed_index(start_index: usize, consumed: NonZeroUsize) -> usize {
373 add_offset(start_index, consumed.get() - 1)
374}
375
376/// Validates that an error index lies inside a consumed byte span.
377///
378/// # Parameters
379///
380/// - `start_index`: Byte index where the value starts.
381/// - `error_index`: Byte index where the error was detected.
382/// - `consumed`: Non-zero number of consumed bytes.
383///
384/// # Panics
385///
386/// Panics when `error_index` is before `start_index` or after the last consumed
387/// byte.
388const fn assert_error_index_in_consumed_span(start_index: usize, error_index: usize, consumed: NonZeroUsize) {
389 let last_index = last_consumed_index(start_index, consumed);
390 assert!(
391 error_index >= start_index,
392 "LEB128 error index must not precede value start",
393 );
394 assert!(
395 error_index <= last_index,
396 "LEB128 error index must lie inside consumed input",
397 );
398}