qubit-codec 0.8.0

Core codec traits and buffer conversion primitives for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Errors reported by transcode engines and transcoder adapters.

use core::fmt;

/// Error reported by a transcode operation.
///
/// The enum keeps caller-contract failures in the framework layer and stores
/// codec-, charset-, or policy-specific failures in [`TranscodeError::Domain`].
///
/// # Type Parameters
///
/// - `E`: Domain error reported by the concrete transcoder.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum TranscodeError<E> {
    /// The caller supplied an input index beyond the input slice length.
    InvalidInputIndex {
        /// Invalid input index supplied by the caller.
        index: usize,
        /// Length of the input slice.
        len: usize,
    },
    /// The caller supplied an output index beyond the output slice length.
    InvalidOutputIndex {
        /// Invalid output index supplied by the caller.
        index: usize,
        /// Length of the output slice.
        len: usize,
    },
    /// The output slice cannot hold required one-shot reset or finish output.
    InsufficientOutput {
        /// Output index supplied by the caller.
        output_index: usize,
        /// Required writable output units.
        required: usize,
        /// Available writable output units.
        available: usize,
    },
    /// Output length arithmetic overflowed.
    OutputLengthOverflow,
    /// Domain-specific codec, charset, or policy error.
    Domain(E),
}

impl<E> TranscodeError<E> {
    /// Creates a domain-specific transcode error.
    ///
    /// # Parameters
    ///
    /// - `error`: Domain error reported by the concrete transcoder.
    ///
    /// # Returns
    ///
    /// Returns a transcode error wrapping `error`.
    #[inline(always)]
    pub const fn domain(error: E) -> Self {
        Self::Domain(error)
    }

    /// Creates an invalid-input-index error.
    ///
    /// # Parameters
    ///
    /// - `index`: Invalid input index supplied by the caller.
    /// - `len`: Length of the input slice.
    ///
    /// # Returns
    ///
    /// Returns the invalid-input-index error.
    #[inline(always)]
    pub const fn invalid_input_index(index: usize, len: usize) -> Self {
        Self::InvalidInputIndex { index, len }
    }

    /// Creates an invalid-output-index error.
    ///
    /// # Parameters
    ///
    /// - `index`: Invalid output index supplied by the caller.
    /// - `len`: Length of the output slice.
    ///
    /// # Returns
    ///
    /// Returns the invalid-output-index error.
    #[inline(always)]
    pub const fn invalid_output_index(index: usize, len: usize) -> Self {
        Self::InvalidOutputIndex { index, len }
    }

    /// Creates an insufficient-output error.
    ///
    /// # Parameters
    ///
    /// - `output_index`: Output index supplied by the caller.
    /// - `required`: Output units required to finish in one call.
    /// - `available`: Output units available from `output_index`.
    ///
    /// # Returns
    ///
    /// Returns the insufficient-output error.
    #[inline(always)]
    pub const fn insufficient_output(
        output_index: usize,
        required: usize,
        available: usize,
    ) -> Self {
        Self::InsufficientOutput {
            output_index,
            required,
            available,
        }
    }

    /// Returns whether this error wraps a domain error.
    ///
    /// # Returns
    ///
    /// Returns `true` for [`TranscodeError::Domain`].
    #[must_use]
    #[inline(always)]
    pub const fn is_domain(&self) -> bool {
        matches!(self, Self::Domain(_))
    }

    /// Borrows the wrapped domain error.
    ///
    /// # Returns
    ///
    /// Returns `Some(error)` for [`TranscodeError::Domain`] and `None` for
    /// framework contract errors.
    #[must_use]
    #[inline(always)]
    pub const fn domain_ref(&self) -> Option<&E> {
        match self {
            Self::Domain(error) => Some(error),
            _ => None,
        }
    }

    /// Maps the wrapped domain error while preserving framework errors.
    ///
    /// # Type Parameters
    ///
    /// - `F`: Mapping function type.
    /// - `T`: Target domain error type.
    ///
    /// # Parameters
    ///
    /// - `f`: Function applied to the wrapped domain error.
    ///
    /// # Returns
    ///
    /// Returns the mapped transcode error.
    #[inline]
    pub fn map_domain<F, T>(self, f: F) -> TranscodeError<T>
    where
        F: FnOnce(E) -> T,
    {
        match self {
            Self::InvalidInputIndex { index, len } => {
                TranscodeError::InvalidInputIndex { index, len }
            }
            Self::InvalidOutputIndex { index, len } => {
                TranscodeError::InvalidOutputIndex { index, len }
            }
            Self::InsufficientOutput {
                output_index,
                required,
                available,
            } => TranscodeError::InsufficientOutput {
                output_index,
                required,
                available,
            },
            Self::OutputLengthOverflow => TranscodeError::OutputLengthOverflow,
            Self::Domain(error) => TranscodeError::Domain(f(error)),
        }
    }

    /// Validates that `input_index` is within an input slice.
    ///
    /// # Parameters
    ///
    /// - `input_len`: Length of the input slice.
    /// - `input_index`: Input index supplied by the caller.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` when `input_index <= input_len`.
    ///
    /// # Errors
    ///
    /// Returns an invalid-input-index error when `input_index` is beyond the
    /// slice.
    #[inline]
    pub fn ensure_input_index(
        input_len: usize,
        input_index: usize,
    ) -> Result<(), Self> {
        if input_index > input_len {
            return Err(Self::invalid_input_index(input_index, input_len));
        }
        Ok(())
    }

    /// Validates that `output_index` is within an output slice.
    ///
    /// # Parameters
    ///
    /// - `output_len`: Length of the output slice.
    /// - `output_index`: Output index supplied by the caller.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` when `output_index <= output_len`.
    ///
    /// # Errors
    ///
    /// Returns an invalid-output-index error when `output_index` is beyond the
    /// slice.
    #[inline]
    pub fn ensure_output_index(
        output_len: usize,
        output_index: usize,
    ) -> Result<(), Self> {
        if output_index > output_len {
            return Err(Self::invalid_output_index(output_index, output_len));
        }
        Ok(())
    }

    /// Validates input and output start indices for a transcode call.
    ///
    /// # Parameters
    ///
    /// - `input_len`: Length of the input slice.
    /// - `input_index`: Input index supplied by the caller.
    /// - `output_len`: Length of the output slice.
    /// - `output_index`: Output index supplied by the caller.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` when both indices are within their slices.
    ///
    /// # Errors
    ///
    /// Returns an invalid-input-index or invalid-output-index error when either
    /// index is beyond its slice.
    #[inline]
    pub fn ensure_transcode_indices(
        input_len: usize,
        input_index: usize,
        output_len: usize,
        output_index: usize,
    ) -> Result<(), Self> {
        Self::ensure_input_index(input_len, input_index)?;
        Self::ensure_output_index(output_len, output_index)
    }

    /// Validates that an output slice can hold one-shot finalization output.
    ///
    /// # Parameters
    ///
    /// - `output_len`: Length of the output slice.
    /// - `output_index`: Output index supplied by the caller.
    /// - `required`: Output units required to finish in one call.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` when output capacity is sufficient.
    ///
    /// # Errors
    ///
    /// Returns an invalid-output-index error when `output_index` is beyond the
    /// slice, or an insufficient-output error when fewer than `required` units
    /// are writable from `output_index`.
    #[inline]
    pub fn ensure_output_capacity(
        output_len: usize,
        output_index: usize,
        required: usize,
    ) -> Result<(), Self> {
        Self::ensure_output_index(output_len, output_index)?;
        let available = output_len - output_index;
        if available < required {
            return Err(Self::insufficient_output(
                output_index,
                required,
                available,
            ));
        }
        Ok(())
    }

    /// Validates an indexed output range and its minimum writable capacity.
    ///
    /// # Parameters
    ///
    /// - `output_len`: Length of the output slice.
    /// - `output_index`: Output index supplied by the caller.
    /// - `range_len`: Length of the writable range starting at `output_index`.
    /// - `required`: Minimum output units required inside the range.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` when the range fits inside the slice and can hold
    /// `required` units.
    ///
    /// # Errors
    ///
    /// Returns an invalid-output-index error when the range overflows or
    /// extends beyond the slice, or an insufficient-output error when
    /// `range_len` is smaller than `required`.
    #[inline]
    pub fn ensure_output_range(
        output_len: usize,
        output_index: usize,
        range_len: usize,
        required: usize,
    ) -> Result<(), Self> {
        Self::ensure_output_index(output_len, output_index)?;
        if !qubit_io::UncheckedSlice::range_fits(
            output_len,
            output_index,
            range_len,
        ) {
            return Err(Self::invalid_output_index(output_index, output_len));
        }
        if range_len < required {
            return Err(Self::insufficient_output(
                output_index,
                required,
                range_len,
            ));
        }
        Ok(())
    }
}

impl<E> From<E> for TranscodeError<E> {
    /// Wraps a domain error in [`TranscodeError::Domain`].
    ///
    /// # Parameters
    ///
    /// - `error`: Domain error to wrap.
    ///
    /// # Returns
    ///
    /// Returns the wrapped transcode error.
    #[inline(always)]
    fn from(error: E) -> Self {
        Self::Domain(error)
    }
}

impl<E> fmt::Display for TranscodeError<E>
where
    E: fmt::Display,
{
    /// Formats the transcode error.
    ///
    /// # Parameters
    ///
    /// - `f`: Destination formatter.
    ///
    /// # Returns
    ///
    /// Returns the formatter result.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidInputIndex { index, len } => {
                write!(f, "invalid input index {index}; input length is {len}")
            }
            Self::InvalidOutputIndex { index, len } => {
                write!(
                    f,
                    "invalid output index {index}; output length is {len}"
                )
            }
            Self::InsufficientOutput {
                output_index,
                required,
                available,
            } => write!(
                f,
                "insufficient output at index {output_index}; required {required}, available {available}"
            ),
            Self::OutputLengthOverflow => {
                f.write_str("output length arithmetic overflow")
            }
            Self::Domain(error) => error.fmt(f),
        }
    }
}

impl<E> std::error::Error for TranscodeError<E>
where
    E: std::error::Error + 'static,
{
    /// Returns the source domain error, if any.
    ///
    /// # Returns
    ///
    /// Returns `Some(error)` for [`TranscodeError::Domain`] and `None` for
    /// framework contract errors.
    #[inline(always)]
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Domain(error) => Some(error),
            _ => None,
        }
    }
}