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