qubit-codec 0.17.4

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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Errors reported by transcode converters.

use thiserror::Error;

use super::capacity_error::CapacityError;
use super::transcode_decode_errors::TranscodeDecodeError;
use super::transcode_domain_error::TranscodeDomainError;
use super::transcode_encode_error::TranscodeEncodeError;
use super::transcode_failure::TranscodeFailure;
use crate::Codec;

/// Convert transcode error for a codec-backed converter.
///
/// # Type Parameters
///
/// - `D`: Source codec providing decode errors and the intermediate value type.
/// - `E`: Target codec providing encode errors for the same value type.
pub type TranscodeConvertErrorOf<D, E> =
    TranscodeConvertError<<D as Codec>::DecodeError, <E as Codec>::EncodeError, <D as Codec>::Value>;

/// Error reported by a unit-to-unit transcode conversion.
///
/// # Type Parameters
///
/// - `DE`: Source decoder domain error.
/// - `EE`: Target encoder domain error.
/// - `V`: Owned intermediate value retained when encoding is rejected.
///
/// For values emitted by the source codec's decode reset or finish phase, the
/// converter uses placeholder input index 0 in encode contexts and errors.
/// Such values have no source-unit position, and index 0 cannot distinguish
/// them from a value decoded at source index 0. Ordinary decoded values retain
/// their index in the input slice supplied to the decode call that produced
/// them. A pending value keeps that index across calls; it is not rebased to a
/// later input slice and is not a whole-stream offset. The retained index may
/// be outside the bounds of a later input slice. Error phases describe the
/// underlying codec operation, so encoding a lifecycle-generated value uses
/// the main encode path even during converter reset or finish.
///
/// # Examples
///
/// ```
/// use qubit_codec::TranscodeConvertError;
///
/// let error = TranscodeConvertError::<&str, &str, u8>::unencodable(3, 42);
/// assert_eq!(error.unencodable_ref(), Some((3, Some(&42))));
/// assert_eq!(error.failure_ref(), None);
/// ```
#[derive(Clone, Debug, Eq, Error, Hash, PartialEq)]
#[must_use]
pub enum TranscodeConvertError<DE, EE, V> {
    /// Framework-level transcode failure.
    #[error(transparent)]
    Failure(
        /// Framework contract, capacity, or lifecycle failure.
        #[from]
        TranscodeFailure,
    ),

    /// Source-side domain error.
    #[error("decode side failed: {0}")]
    DecodeDomain(
        /// Owned source error with its lifecycle phase and input context.
        #[source]
        TranscodeDomainError<DE>,
    ),

    /// Target-side domain error.
    #[error("encode side failed: {0}")]
    EncodeDomain(
        /// Owned target error with its lifecycle phase and input context.
        #[source]
        TranscodeDomainError<EE>,
    ),

    /// The decoded intermediate value cannot be encoded by the target codec and
    /// policy.
    #[error("unencodable value at input index {input_index}")]
    Unencodable {
        /// Source input index of the value being encoded. Lifecycle-generated
        /// converter values use placeholder 0 because they have no source-unit
        /// position; ordinary decoded values retain their index in the input
        /// slice supplied to the decode call that produced them, including
        /// when kept pending across calls.
        input_index: usize,
        /// `Some` retains the decoded intermediate value; `None` means value
        /// context was unavailable or intentionally omitted.
        value: Option<V>,
    },
}

impl<DE, EE, V> TranscodeConvertError<DE, EE, V> {
    /// Creates a source reset-phase domain-specific converter error.
    ///
    /// # Parameters
    ///
    /// - `source`: Owned source error raised during reset.
    ///
    /// # Returns
    ///
    /// Returns a source-domain reset error.
    #[inline]
    pub const fn decode_domain_reset(source: DE) -> Self {
        Self::DecodeDomain(TranscodeDomainError::reset(source))
    }

    /// Creates a source main-phase domain-specific converter error.
    ///
    /// # Parameters
    ///
    /// - `source`: Owned source error raised during conversion.
    /// - `input_index`: Absolute source position of the failed operation.
    ///
    /// # Returns
    ///
    /// Returns a source-domain main-phase error at the supplied input index.
    #[inline]
    pub const fn decode_domain_main(source: DE, input_index: usize) -> Self {
        Self::DecodeDomain(TranscodeDomainError::main(source, input_index))
    }

    /// Creates a source main-phase converter error with decode consumption
    /// context.
    ///
    /// # Parameters
    ///
    /// - `source`: Owned source error raised during conversion.
    /// - `input_index`: Source index for the failed operation. For a
    ///   lifecycle-generated converter value, use placeholder 0 because it has
    ///   no source-unit position; an ordinary decoded value retains its index
    ///   in the slice supplied to the decode call that produced it, even when
    ///   kept pending across calls.
    /// - `input_consumed`: `Some` records invalid units consumed; `None` means
    ///   unknown.
    ///
    /// # Returns
    ///
    /// Returns a source-domain main-phase error retaining consumption context.
    #[inline]
    pub const fn decode_domain_main_with_consumed(
        source: DE,
        input_index: usize,
        input_consumed: Option<core::num::NonZeroUsize>,
    ) -> Self {
        Self::DecodeDomain(TranscodeDomainError::main_with_consumed(
            source,
            input_index,
            input_consumed,
        ))
    }

    /// Creates a source finish-phase domain-specific converter error.
    ///
    /// # Parameters
    ///
    /// - `source`: Owned source error raised during finalization.
    ///
    /// # Returns
    ///
    /// Returns a source-domain finish error.
    #[inline]
    pub const fn decode_domain_finish(source: DE) -> Self {
        Self::DecodeDomain(TranscodeDomainError::finish(source))
    }

    /// Creates a target reset-phase domain-specific converter error.
    ///
    /// # Parameters
    ///
    /// - `source`: Owned target error raised during reset.
    ///
    /// # Returns
    ///
    /// Returns a target-domain reset error.
    #[inline]
    pub const fn encode_domain_reset(source: EE) -> Self {
        Self::EncodeDomain(TranscodeDomainError::reset(source))
    }

    /// Creates a target main-phase domain-specific converter error.
    ///
    /// # Parameters
    ///
    /// - `source`: Owned target error raised during conversion.
    /// - `input_index`: Source index for the failed operation. For a
    ///   lifecycle-generated converter value, use placeholder 0 because it has
    ///   no source-unit position; an ordinary decoded value retains its index
    ///   in the slice supplied to the decode call that produced it, even when
    ///   kept pending across calls.
    ///
    /// # Returns
    ///
    /// Returns a target-domain main-phase error at the supplied input index.
    /// The main phase identifies the underlying encode operation, including
    /// when a converter invokes it during reset or finish.
    #[inline]
    pub const fn encode_domain_main(source: EE, input_index: usize) -> Self {
        Self::EncodeDomain(TranscodeDomainError::main(source, input_index))
    }

    /// Creates a target finish-phase domain-specific converter error.
    ///
    /// # Parameters
    ///
    /// - `source`: Owned target error raised during finalization.
    ///
    /// # Returns
    ///
    /// Returns a target-domain finish error.
    #[inline]
    pub const fn encode_domain_finish(source: EE) -> Self {
        Self::EncodeDomain(TranscodeDomainError::finish(source))
    }

    /// Creates an unencodable intermediate-value error with value context.
    ///
    /// # Parameters
    ///
    /// - `input_index`: Source index of the rejected value. Lifecycle-generated
    ///   converter values use placeholder 0 because they have no source-unit
    ///   position; an ordinary decoded value retains its index in the slice
    ///   supplied to the decode call that produced it, even when kept pending
    ///   across calls.
    /// - `value`: Intermediate value moved into the error for recovery.
    ///
    /// # Returns
    ///
    /// Returns an unencodable error owning `Some(value)`.
    #[inline]
    pub fn unencodable(input_index: usize, value: V) -> Self {
        Self::Unencodable {
            input_index,
            value: Some(value),
        }
    }

    /// Creates an unencodable intermediate-value error without value context.
    ///
    /// # Parameters
    ///
    /// - `input_index`: Source index of the rejected value. Lifecycle-generated
    ///   converter values use placeholder 0 because they have no source-unit
    ///   position; an ordinary decoded value retains its index in the slice
    ///   supplied to the decode call that produced it, even when kept pending
    ///   across calls.
    ///
    /// # Returns
    ///
    /// Returns an unencodable error with absent (`None`) value context.
    #[inline]
    pub const fn unencodable_without_context(input_index: usize) -> Self {
        Self::Unencodable {
            input_index,
            value: None,
        }
    }

    /// Converts an encode error into a converter error while adding fallback
    /// value context to unencodable errors that lack it.
    ///
    /// # Parameters
    ///
    /// - `error`: Owned target-side error to convert.
    /// - `fallback_value`: Value moved into absent context, or dropped if not
    ///   needed.
    ///
    /// # Returns
    ///
    /// Returns the converted error, adding the fallback only when unencodable
    /// value context is absent.
    #[inline]
    pub fn from_encode_error_with_value(error: TranscodeEncodeError<EE, V>, fallback_value: V) -> Self {
        match error {
            TranscodeEncodeError::Unencodable {
                input_index,
                value: None,
            } => Self::Unencodable {
                input_index,
                value: Some(fallback_value),
            },
            other => Self::from(other),
        }
    }

    /// Returns the framework failure carried by this error.
    ///
    /// # Returns
    ///
    /// Returns `Some` for a framework failure, or `None` for domain and
    /// unencodable errors.
    #[inline]
    pub const fn failure_ref(&self) -> Option<&TranscodeFailure> {
        match self {
            Self::Failure(failure) => Some(failure),
            Self::DecodeDomain(_) | Self::EncodeDomain(_) | Self::Unencodable { .. } => None,
        }
    }

    /// Borrows the unencodable value context carried by this error.
    ///
    /// # Returns
    ///
    /// Returns `Some((index, value))` for an unencodable error and `None`
    /// otherwise. The inner `Some` borrows retained value context; inner
    /// `None` means it is absent.
    #[inline]
    pub const fn unencodable_ref(&self) -> Option<(usize, Option<&V>)> {
        match self {
            Self::Unencodable { input_index, value } => Some((*input_index, value.as_ref())),
            Self::Failure(_) | Self::DecodeDomain(_) | Self::EncodeDomain(_) => None,
        }
    }

    /// Maps the source domain error while preserving other errors.
    ///
    /// # Type Parameters
    ///
    /// - `F`: One-shot transformation from `DE` to `T`.
    /// - `T`: Replacement payload type.
    ///
    /// # Parameters
    ///
    /// - `f`: Invoked only for a source-domain error; otherwise dropped without
    ///   being called.
    ///
    /// # Returns
    ///
    /// Returns an owned error preserving all other variants and positional
    /// context.
    ///
    /// # Panics
    ///
    /// Propagates a panic if the invoked transformation panics.
    #[inline]
    pub fn map_decode_domain<F, T>(self, f: F) -> TranscodeConvertError<T, EE, V>
    where
        F: FnOnce(DE) -> T,
    {
        match self {
            Self::Failure(failure) => TranscodeConvertError::Failure(failure),
            Self::DecodeDomain(error) => TranscodeConvertError::DecodeDomain(error.map_source(f)),
            Self::EncodeDomain(error) => TranscodeConvertError::EncodeDomain(error),
            Self::Unencodable { input_index, value } => TranscodeConvertError::Unencodable { input_index, value },
        }
    }

    /// Maps the target domain error while preserving other errors.
    ///
    /// # Type Parameters
    ///
    /// - `F`: One-shot transformation from `EE` to `T`.
    /// - `T`: Replacement payload type.
    ///
    /// # Parameters
    ///
    /// - `f`: Invoked only for a target-domain error; otherwise dropped without
    ///   being called.
    ///
    /// # Returns
    ///
    /// Returns an owned error preserving all other variants and positional
    /// context.
    ///
    /// # Panics
    ///
    /// Propagates a panic if the invoked transformation panics.
    #[inline]
    pub fn map_encode_domain<F, T>(self, f: F) -> TranscodeConvertError<DE, T, V>
    where
        F: FnOnce(EE) -> T,
    {
        match self {
            Self::Failure(failure) => TranscodeConvertError::Failure(failure),
            Self::DecodeDomain(error) => TranscodeConvertError::DecodeDomain(error),
            Self::EncodeDomain(error) => TranscodeConvertError::EncodeDomain(error.map_source(f)),
            Self::Unencodable { input_index, value } => TranscodeConvertError::Unencodable { input_index, value },
        }
    }

    /// Maps value context carried by unencodable-value errors.
    ///
    /// # Type Parameters
    ///
    /// - `F`: One-shot transformation from `V` to `W`.
    /// - `W`: Replacement payload type.
    ///
    /// # Parameters
    ///
    /// - `f`: Invoked only for present unencodable value context; otherwise
    ///   dropped without being called.
    ///
    /// # Returns
    ///
    /// Returns an owned error preserving all other variants and positional
    /// context.
    ///
    /// # Panics
    ///
    /// Propagates a panic if the invoked transformation panics.
    #[inline]
    pub fn map_value<F, W>(self, f: F) -> TranscodeConvertError<DE, EE, W>
    where
        F: FnOnce(V) -> W,
    {
        match self {
            Self::Failure(failure) => TranscodeConvertError::Failure(failure),
            Self::DecodeDomain(error) => TranscodeConvertError::DecodeDomain(error),
            Self::EncodeDomain(error) => TranscodeConvertError::EncodeDomain(error),
            Self::Unencodable { input_index, value } => TranscodeConvertError::Unencodable {
                input_index,
                value: value.map(f),
            },
        }
    }
}

impl<DE, EE, V> From<TranscodeDecodeError<DE>> for TranscodeConvertError<DE, EE, V> {
    /// Converts a source-side decode error into a converter error.
    ///
    /// # Parameters
    ///
    /// - `error`: Owned failure to convert without discarding its context.
    ///
    /// # Returns
    ///
    /// Returns the corresponding converter variant preserving the original
    /// cause.
    #[inline]
    fn from(error: TranscodeDecodeError<DE>) -> Self {
        match error {
            TranscodeDecodeError::Failure(failure) => Self::Failure(failure),
            TranscodeDecodeError::Domain(error) => Self::DecodeDomain(error),
        }
    }
}

impl<DE, EE, V> From<TranscodeEncodeError<EE, V>> for TranscodeConvertError<DE, EE, V> {
    /// Converts a target-side encode error into a converter error.
    ///
    /// # Parameters
    ///
    /// - `error`: Owned failure to convert without discarding its context.
    ///
    /// # Returns
    ///
    /// Returns the corresponding converter variant preserving the original
    /// cause.
    #[inline]
    fn from(error: TranscodeEncodeError<EE, V>) -> Self {
        match error {
            TranscodeEncodeError::Failure(failure) => Self::Failure(failure),
            TranscodeEncodeError::Unencodable { input_index, value } => Self::Unencodable { input_index, value },
            TranscodeEncodeError::Domain(error) => Self::EncodeDomain(error),
        }
    }
}

impl<DE, EE, V> From<CapacityError> for TranscodeConvertError<DE, EE, V> {
    /// Converts capacity planning errors into transcode framework errors.
    ///
    /// # Parameters
    ///
    /// - `error`: Owned failure to convert without discarding its context.
    ///
    /// # Returns
    ///
    /// Returns the corresponding converter variant preserving the original
    /// cause.
    #[inline]
    fn from(error: CapacityError) -> Self {
        TranscodeFailure::from(error).into()
    }
}