Skip to main content

qubit_codec/transcode/engine/
transcode_decode_engine.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// =============================================================================
8//! Reusable buffered decoder engine.
9
10use core::num::NonZeroUsize;
11
12use super::super::internal::applied_decode_invalid_action::AppliedDecodeInvalidAction;
13use super::super::internal::decode_state::DecodeState;
14use super::super::internal::lifecycle_guard::LifecycleGuard;
15use super::DecodeContext;
16use super::DecodeIncompleteAction;
17use super::DecodeInvalidAction;
18use super::DecodeOutcome;
19use super::TranscodeDecodeHooks;
20use crate::CapacityError;
21use crate::Codec;
22use crate::DecodeFailure;
23use crate::TranscodeDecodeError;
24use crate::TranscodeDecodeErrorOf;
25use crate::TranscodeDecoder;
26use crate::TranscodeFailure;
27use crate::TranscodeProgress;
28use crate::Transcoder;
29use crate::codec::assert_unit_bounds;
30
31/// Reusable buffered decoding engine for codec-backed decoders.
32///
33/// The engine owns the low-level codec and hook object. It keeps the common
34/// buffered decoding loop private: input-index validation, output-capacity
35/// checks, calls to [`Codec::decode`], hook dispatch, and
36/// [`crate::TranscodeStatus`] reporting. Incomplete input tails are left in the
37/// caller-provided input slice; callers own input-buffer refill.
38///
39/// Use this type to build a streaming decoder over a one-value [`Codec`]. The
40/// engine decodes into a caller-provided output slice and returns
41/// [`TranscodeProgress`] instead of allocating. On success it writes decoded
42/// values directly to output. On codec errors it delegates to
43/// [`crate::engine::TranscodeDecodeHooks`], allowing a policy to skip invalid
44/// units, emit a replacement value, or fail.
45///
46/// The engine stops before reading an incomplete value when fewer than
47/// [`Codec::MIN_UNITS_PER_VALUE`] units are available. For variable-width
48/// codecs, the codec may still return an incomplete decode error after that
49/// minimum is satisfied. Both conditions return
50/// [`crate::TranscodeStatus::NeedInput`] while the stream is open; at EOF the
51/// hook selects whether to reject, skip, or replace the remaining tail.
52///
53/// For strict decoding that wraps codec errors, use
54/// [`crate::CodecTranscodeDecoder`]. Use `TranscodeDecodeEngine` directly when
55/// invalid input should be repaired, skipped, counted, or otherwise handled by
56/// policy.
57///
58/// # Examples
59///
60/// ```rust
61/// use core::num::NonZeroUsize;
62/// use qubit_codec::{
63///     Codec,
64///     TranscodeDecodeErrorOf,
65///     DecodeFailure,
66///     TranscodeStatus,
67/// };
68/// use qubit_codec::engine::{
69///     DecodeContext,
70///     DecodeInvalidAction,
71///     TranscodeDecodeEngine,
72///     TranscodeDecodeHooks,
73/// };
74///
75/// #[derive(Clone, Copy)]
76/// struct ByteCodec;
77///
78/// #[derive(Clone, Copy, Debug, Eq, PartialEq)]
79/// enum ByteDecodeError {
80///     Malformed { consumed: NonZeroUsize },
81/// }
82///
83/// impl Codec for ByteCodec {
84///     type Value = u8;
85///     type Unit = u8;
86///     type DecodeError = ByteDecodeError;
87///     type EncodeError = core::convert::Infallible;
88///
89///     const MIN_UNITS_PER_VALUE: usize = 1;
90///     const MAX_ENCODE_UNITS_PER_VALUE: usize = 1;
91///     const MAX_DECODE_UNITS_PER_VALUE: usize = 1;
92///
93///     unsafe fn decode(
94///         &mut self,
95///         input: &[u8],
96///         index: usize,
97///     ) -> Result<(u8, NonZeroUsize), DecodeFailure<Self::DecodeError>> {
98///         match input[index] {
99///             0xff => Err(DecodeFailure::invalid(
100///                 ByteDecodeError::Malformed {
101///                     consumed: NonZeroUsize::MIN,
102///                 },
103///                 NonZeroUsize::MIN,
104///             )),
105///             value => Ok((value, NonZeroUsize::MIN)),
106///         }
107///     }
108///
109///     unsafe fn encode(
110///         &mut self,
111///         value: &u8,
112///         output: &mut [u8],
113///         index: usize,
114///     ) -> Result<usize, Self::EncodeError> {
115///         output[index] = *value;
116///         Ok(1)
117///     }
118/// }
119///
120/// struct ReplacementHooks;
121///
122/// impl TranscodeDecodeHooks<ByteCodec> for ReplacementHooks {
123///     fn handle_invalid_decode(
124///         &mut self,
125///         _codec: &mut ByteCodec,
126///         error: &ByteDecodeError,
127///         consumed: Option<NonZeroUsize>,
128///         _context: DecodeContext,
129///     ) -> Result<DecodeInvalidAction<u8>, TranscodeDecodeErrorOf<ByteCodec>> {
130///         match error {
131///             ByteDecodeError::Malformed { .. } => {
132///                 Ok(DecodeInvalidAction::Emit {
133///                     value: b'?',
134///                     consumed: consumed.expect("codec reported malformed width"),
135///                 })
136///             }
137///         }
138///     }
139/// }
140///
141/// let mut engine = TranscodeDecodeEngine::<_, _>::new(ByteCodec, ReplacementHooks);
142/// let input = [b'a', 0xff, b'b'];
143/// let mut output = [0_u8; 3];
144/// let mut reset_output = [];
145/// engine.reset(&mut reset_output, 0)?;
146///
147/// let progress = engine.transcode(&input, 0, &mut output, 0)?;
148/// match progress.status() {
149///     TranscodeStatus::Complete => assert_eq!(&output[..progress.written()], b"a?b"),
150///     TranscodeStatus::NeedInput { .. } => {
151///         // Keep `input[input_index + progress.read()..]`, append more source
152///         // units, and resume.
153///     }
154///     TranscodeStatus::NeedOutput { .. } => {
155///         // Drain `output[..progress.written()]`, then resume with more output
156///         // room.
157///     }
158/// }
159/// # Ok::<(), qubit_codec::TranscodeDecodeError<ByteDecodeError>>(())
160/// ```
161///
162/// # Type Parameters
163///
164/// - `C`: Low-level codec used by the engine.
165/// - `H`: Policy hook object used by the engine.
166#[derive(Debug, Default)]
167pub struct TranscodeDecodeEngine<C, H> {
168    /// Low-level codec used for one-value decoding.
169    pub(super) codec: C,
170    /// Policy hooks used for decode failures.
171    pub(super) hooks: H,
172    /// Guard for the `reset → transcode* → finish` lifecycle in every build
173    /// profile.
174    lifecycle: LifecycleGuard,
175}
176
177/// Adds two independent decoded-value capacity bounds.
178///
179/// # Parameters
180///
181/// - `first`: First decoded-value bound.
182/// - `second`: Independent decoded-value bound to add.
183///
184/// # Returns
185///
186/// Returns the combined decoded-value bound.
187///
188/// # Errors
189///
190/// Returns `CapacityError::OutputLengthOverflow` if the sum exceeds
191/// `usize::MAX`.
192#[inline]
193fn add_decode_output_bounds(first: usize, second: usize) -> Result<usize, CapacityError> {
194    first.checked_add(second).ok_or(CapacityError::OutputLengthOverflow)
195}
196
197/// Adds reset, transcode, and finish decoded-value capacity bounds.
198///
199/// # Parameters
200///
201/// - `reset`: Maximum reset output.
202/// - `transcode`: Maximum streaming output.
203/// - `finish`: Maximum finalization output.
204///
205/// # Returns
206///
207/// Returns the complete-stream decoded-value bound.
208///
209/// # Errors
210///
211/// Returns `CapacityError::OutputLengthOverflow` if the sum exceeds
212/// `usize::MAX`.
213#[inline]
214fn sum_decode_output_bounds(reset: usize, transcode: usize, finish: usize) -> Result<usize, CapacityError> {
215    let before_finish = add_decode_output_bounds(reset, transcode)?;
216    add_decode_output_bounds(before_finish, finish)
217}
218
219impl<C, H> TranscodeDecodeEngine<C, H>
220where
221    C: Codec,
222    H: TranscodeDecodeHooks<C>,
223{
224    /// Creates a buffered decoder engine.
225    ///
226    /// # Parameters
227    ///
228    /// - `codec`: Low-level codec used for one-value decoding.
229    /// - `hooks`: Policy hooks used for decode failures.
230    ///
231    /// # Returns
232    ///
233    /// Returns a buffered decoder engine.
234    ///
235    /// # Compile-Time Checks
236    ///
237    /// Fails to compile when the supplied codec declares a zero decode unit
238    /// bound or when [`Codec::MIN_UNITS_PER_VALUE`] exceeds
239    /// [`Codec::MAX_DECODE_UNITS_PER_VALUE`].
240    #[inline]
241    #[must_use]
242    pub fn new(codec: C, hooks: H) -> Self {
243        assert_unit_bounds::<C>();
244        Self {
245            codec,
246            hooks,
247            lifecycle: LifecycleGuard::new(),
248        }
249    }
250
251    /// Returns the wrapped low-level codec.
252    ///
253    /// # Returns
254    ///
255    /// Returns a shared reference to the codec owned by this engine.
256    #[inline]
257    #[must_use]
258    pub const fn codec(&self) -> &C {
259        &self.codec
260    }
261
262    /// Returns the wrapped low-level codec mutably.
263    ///
264    /// # Returns
265    ///
266    /// Returns a mutable reference to the codec owned by this engine.
267    #[inline]
268    #[must_use]
269    pub fn codec_mut(&mut self) -> &mut C {
270        &mut self.codec
271    }
272
273    /// Returns the decode hooks used by this engine.
274    ///
275    /// # Returns
276    ///
277    /// Returns a shared reference to the hook object owned by this engine.
278    #[inline]
279    #[must_use]
280    pub const fn hooks(&self) -> &H {
281        &self.hooks
282    }
283
284    /// Returns the decode hooks mutably.
285    ///
286    /// # Returns
287    ///
288    /// Returns a mutable reference to the hook object owned by this engine.
289    #[inline]
290    #[must_use]
291    pub fn hooks_mut(&mut self) -> &mut H {
292        &mut self.hooks
293    }
294
295    /// Consumes the engine and returns its codec and hooks.
296    ///
297    /// Any lifecycle state owned by the engine is discarded.
298    ///
299    /// # Returns
300    ///
301    /// Returns the wrapped codec followed by the decode hooks.
302    #[inline]
303    #[must_use]
304    pub fn into_parts(self) -> (C, H) {
305        let Self { codec, hooks, .. } = self;
306        (codec, hooks)
307    }
308
309    /// Returns an upper bound for decoded values produced from `input_len`
310    /// units.
311    ///
312    /// This bound covers only the streaming decode phase. It is delegated to
313    /// [`TranscodeDecodeHooks::max_transcode_output_len`], so it includes hook
314    /// policy and is valid for every reachable transient codec and hook state.
315    /// Downstream decoders must use this engine-level API for capacity planning
316    /// instead of recomputing the bound from [`Codec`] constants.
317    ///
318    /// # Parameters
319    ///
320    /// - `input_len`: Number of source units the caller plans to decode.
321    ///
322    /// # Returns
323    ///
324    /// Returns a conservative upper bound, or a capacity error on arithmetic
325    /// overflow.
326    ///
327    /// # Errors
328    ///
329    /// Returns a capacity error when hook capacity arithmetic overflows.
330    #[inline]
331    #[must_use = "capacity planning can fail on overflow"]
332    pub fn max_transcode_output_len(&self, input_len: usize) -> Result<usize, CapacityError> {
333        self.hooks.max_transcode_output_len(&self.codec, input_len)
334    }
335
336    /// Returns the global maximum values emitted by finishing codec state and
337    /// finishing hook-owned state.
338    ///
339    /// # Returns
340    ///
341    /// Returns the sum of [`Codec::MAX_DECODE_FINISH_VALUES`] and the
342    /// hook-provided final-output bound. The codec finish portion covers values
343    /// written by [`Codec::decode_finish`]; hook implementations must not
344    /// include that portion in
345    /// [`TranscodeDecodeHooks::max_finish_output_len`]. Both component bounds
346    /// cover every reachable transient state.
347    ///
348    /// # Errors
349    ///
350    /// Returns a capacity error when the combined finish bound exceeds
351    /// `usize::MAX`.
352    #[inline]
353    #[must_use = "capacity planning can fail on overflow"]
354    pub fn max_finish_output_len(&self) -> Result<usize, CapacityError> {
355        add_decode_output_bounds(
356            C::MAX_DECODE_FINISH_VALUES,
357            self.hooks.max_finish_output_len(&self.codec),
358        )
359    }
360
361    /// Returns the global maximum values emitted when resetting stream state.
362    ///
363    /// # Returns
364    ///
365    /// Returns `Ok(Codec::MAX_DECODE_RESET_VALUES)` for the wrapped codec.
366    /// This query cannot fail.
367    /// Stateless decoders always return `0`.
368    #[inline]
369    pub fn max_reset_output_len(&self) -> Result<usize, CapacityError> {
370        Ok(C::MAX_DECODE_RESET_VALUES)
371    }
372
373    /// Returns the maximum values needed by a complete one-shot decode stream.
374    ///
375    /// The returned bound covers reset output, the streaming decode phase for
376    /// `input_len` units, and finish output. Its components are global across
377    /// transient state. Higher-level complete decode helpers should use this
378    /// engine-level bound instead of recomputing capacity from [`Codec`]
379    /// constants, because hook policy may change streaming or finish output.
380    ///
381    /// # Parameters
382    ///
383    /// - `input_len`: Number of source units in the complete stream.
384    ///
385    /// # Returns
386    ///
387    /// Returns the complete-stream output bound, or a capacity error on
388    /// arithmetic overflow.
389    ///
390    /// # Errors
391    ///
392    /// Returns a capacity error when a component or their sum overflows.
393    #[inline]
394    #[must_use = "capacity planning can fail on overflow"]
395    pub fn max_total_output_len(&self, input_len: usize) -> Result<usize, CapacityError> {
396        let transcode = self.max_transcode_output_len(input_len)?;
397        let finish = self.max_finish_output_len()?;
398        sum_decode_output_bounds(C::MAX_DECODE_RESET_VALUES, transcode, finish)
399    }
400
401    /// Resets codec decode state, runs reset hooks, and emits stream-start
402    /// values.
403    ///
404    /// The sequence is: validate capacity → run `reset_hooks` → call
405    /// [`Codec::decode_reset`]. Stateless decoders (`MAX_DECODE_RESET_VALUES
406    /// == 0`) write nothing and return `Ok(0)`.
407    ///
408    /// # Parameters
409    ///
410    /// - `output`: Complete output value slice visible to the decoder.
411    /// - `output_index`: Absolute output value index where writing starts.
412    ///
413    /// # Returns
414    ///
415    /// Returns the number of reset values written.
416    ///
417    /// # Errors
418    ///
419    /// Returns framework errors when the caller provides invalid or
420    /// insufficient output capacity. Returns domain errors when codec reset
421    /// or hook reset handling fails. Capacity and index failures occur before
422    /// any reset state is changed. Once reset execution starts, an error
423    /// poisons the engine until a later reset succeeds.
424    ///
425    /// # Panics
426    ///
427    /// Panics if the codec reports more than `MAX_DECODE_RESET_VALUES` written.
428    pub fn reset(&mut self, output: &mut [C::Value], output_index: usize) -> Result<usize, TranscodeDecodeErrorOf<C>> {
429        let required = C::MAX_DECODE_RESET_VALUES;
430        TranscodeFailure::ensure_output_capacity(output.len(), output_index, required)?;
431        self.lifecycle.on_reset_start();
432        self.hooks.reset_hooks(&mut self.codec);
433        let written = unsafe {
434            // SAFETY: The capacity check above reserves the codec's declared
435            // reset-output bound at `output_index`.
436            self.codec.decode_reset(output, output_index)
437        }
438        .map_err(TranscodeDecodeError::domain_reset)?;
439        assert!(written <= required, "Codec::decode_reset wrote beyond its reset bound",);
440        self.lifecycle.on_reset_success();
441        Ok(written)
442    }
443
444    /// Decodes source units into caller-provided output values.
445    ///
446    /// # Parameters
447    ///
448    /// - `input`: Complete input unit slice visible to the decoder.
449    /// - `input_index`: Absolute input unit index where decoding starts.
450    /// - `output`: Complete output value slice visible to the decoder.
451    /// - `output_index`: Absolute output value index where writing starts.
452    ///
453    /// # Returns
454    ///
455    /// Returns progress describing input units consumed, output values written,
456    /// and why decoding stopped.
457    ///
458    /// # Errors
459    ///
460    /// Returns framework errors when either index is outside its slice, and
461    /// domain errors when a concrete policy hook rejects a value. Returns
462    /// [`TranscodeFailure::TranscodeBeforeReset`] when the engine has not
463    /// completed its first reset. Returns
464    /// [`TranscodeFailure::TranscodeAfterFinish`] when the logical stream was
465    /// already finished and has not been reset, or
466    /// [`TranscodeFailure::LifecyclePoisoned`] when an earlier reset or finish
467    /// failed after execution started.
468    ///
469    /// # Panics
470    ///
471    /// Panics when codec or hook progress violates declared decode bounds.
472    pub fn transcode(
473        &mut self,
474        input: &[C::Unit],
475        input_index: usize,
476        output: &mut [C::Value],
477        output_index: usize,
478    ) -> Result<TranscodeProgress, TranscodeDecodeErrorOf<C>> {
479        self.transcode_with_eof(input, input_index, output, output_index, false)
480    }
481
482    /// Decodes source units after the caller has established end of input.
483    ///
484    /// This follows the normal streaming contract, except that codec attempts
485    /// use [`Codec::decode_eof`]. A codec may therefore resolve a trailing
486    /// prefix that would remain incomplete in an open stream.
487    ///
488    /// # Parameters
489    ///
490    /// - `input`: Complete source-unit slice.
491    /// - `input_index`: Absolute index of the next source unit.
492    /// - `output`: Destination for decoded values.
493    /// - `output_index`: Absolute index of the next destination slot.
494    ///
495    /// # Returns
496    ///
497    /// Returns consumed/written counts and the reason decoding stopped.
498    ///
499    /// # Errors
500    ///
501    /// Returns framework errors for invalid lifecycle state or slice indices,
502    /// and policy/domain errors for rejected input, including incomplete EOF
503    /// tails.
504    ///
505    /// # Panics
506    ///
507    /// Panics when codec or hook progress violates declared decode bounds.
508    pub fn transcode_eof(
509        &mut self,
510        input: &[C::Unit],
511        input_index: usize,
512        output: &mut [C::Value],
513        output_index: usize,
514    ) -> Result<TranscodeProgress, TranscodeDecodeErrorOf<C>> {
515        self.transcode_with_eof(input, input_index, output, output_index, true)
516    }
517
518    /// Finishes codec and hook-owned output after EOF.
519    ///
520    /// Finalization first finishes decode-side codec state through
521    /// [`Codec::decode_finish`], then lets hook implementations finish their
522    /// own retained state. The caller must provide enough output capacity for
523    /// [`TranscodeDecodeEngine::max_finish_output_len`], which includes both
524    /// the codec finish bound and the hook-owned finish bound.
525    ///
526    /// # Parameters
527    ///
528    /// - `output`: Complete output value slice visible to the decoder.
529    /// - `output_index`: Absolute output value index where writing starts.
530    ///
531    /// # Returns
532    ///
533    /// Returns the number of values written by finalization.
534    ///
535    /// # Errors
536    ///
537    /// Returns framework errors when the caller provides invalid or
538    /// insufficient output capacity. Returns domain errors when codec finish or
539    /// hook finalization fails. Returns
540    /// [`TranscodeFailure::FinishBeforeReset`] when the engine has not
541    /// completed its first reset. Returns
542    /// [`TranscodeFailure::FinishAfterFinish`] when the logical stream was
543    /// already finished and has not been reset, or
544    /// [`TranscodeFailure::LifecyclePoisoned`] when an earlier reset or finish
545    /// failed after execution started. Capacity and index failures occur before
546    /// finish execution and remain retryable; later failures poison the engine
547    /// until reset succeeds.
548    ///
549    /// # Panics
550    ///
551    /// Panics when the codec finish writes beyond
552    /// [`Codec::MAX_DECODE_FINISH_VALUES`] or when the combined codec and hook
553    /// finalization writes beyond
554    /// [`TranscodeDecodeEngine::max_finish_output_len`].
555    pub fn finish(&mut self, output: &mut [C::Value], output_index: usize) -> Result<usize, TranscodeDecodeErrorOf<C>> {
556        self.lifecycle.on_finish_attempt()?;
557        let required = self.max_finish_output_len()?;
558        TranscodeFailure::ensure_output_capacity(output.len(), output_index, required)?;
559        self.lifecycle.on_finish_start();
560        let finished =
561            unsafe { self.codec.decode_finish(output, output_index) }.map_err(TranscodeDecodeError::domain_finish)?;
562        assert!(
563            finished <= C::MAX_DECODE_FINISH_VALUES,
564            "Codec::decode_finish wrote beyond its finish bound",
565        );
566        let written = self
567            .hooks
568            .finish_hooks(&mut self.codec, output, output_index + finished)?;
569        assert!(
570            finished + written <= required,
571            "TranscodeDecodeEngine hook wrote beyond its finish bound",
572        );
573        self.lifecycle.on_finish_success();
574        Ok(finished + written)
575    }
576
577    /// Runs a complete one-shot `reset -> transcode -> finish` decode stream.
578    ///
579    /// The complete input is supplied as `input`, and output starts at index
580    /// `0` in `output`. Callers that need subranges should slice their
581    /// buffers before calling this method. Downstream one-shot decoder
582    /// helpers should call this engine method instead of reproducing the
583    /// reset, transcode, and finish sequence themselves.
584    ///
585    /// # Parameters
586    ///
587    /// - `input`: Complete source unit slice.
588    /// - `output`: Output value slice for the whole decoded stream.
589    ///
590    /// # Returns
591    ///
592    /// Returns the number of output values written.
593    ///
594    /// # Errors
595    ///
596    /// Returns framework errors for insufficient output, capacity overflow, or
597    /// an incomplete EOF tail, and domain errors from reset, decode, or
598    /// finish.
599    ///
600    /// # Panics
601    ///
602    /// Panics when codec or hook output violates reset, decode, or finish
603    /// bounds.
604    pub fn transcode_complete_into(
605        &mut self,
606        input: &[C::Unit],
607        output: &mut [C::Value],
608    ) -> Result<usize, TranscodeDecodeErrorOf<C>> {
609        <Self as Transcoder>::transcode_complete_into(self, input, output)
610    }
611
612    /// Decodes one source value attempt and delivers emitted values.
613    ///
614    /// # Parameters
615    ///
616    /// - `input`: Complete input unit slice visible to the caller.
617    /// - `context`: Decode context describing the current source and output
618    ///   cursors.
619    /// - `end_of_input`: Whether the source is final and EOF policy applies.
620    /// - `consume`: Callback invoked exactly once when this attempt emits a
621    ///   logical value.
622    ///
623    /// # Type Parameters
624    ///
625    /// - `R`: Value returned by the consumer when a decoded value is emitted.
626    /// - `F`: Consumer callback type.
627    ///
628    /// # Returns
629    ///
630    /// Returns the decode outcome and `Some` consumer result when a value was
631    /// emitted; returns `None` when input was skipped or more input is needed.
632    ///
633    /// # Errors
634    ///
635    /// Returns hook errors when the decode policy rejects the input.
636    ///
637    /// # Panics
638    ///
639    /// Panics when the codec reports consumption beyond the available input,
640    /// an incomplete-input requirement beyond
641    /// [`Codec::MAX_DECODE_UNITS_PER_VALUE`], or hooks return an action that
642    /// consumes beyond the available input. Also panics when reported consumed
643    /// width exceeds the codec maximum or an incomplete requirement does not
644    /// exceed available input. Debug builds reject an empty context.
645    pub(crate) fn decode_one<R, F>(
646        &mut self,
647        input: &[C::Unit],
648        context: DecodeContext,
649        end_of_input: bool,
650        consume: F,
651    ) -> Result<(DecodeOutcome, Option<R>), TranscodeDecodeErrorOf<C>>
652    where
653        F: FnOnce(C::Value, usize) -> R,
654    {
655        debug_assert!(
656            context.available() > 0,
657            "decode_one requires at least one source input unit",
658        );
659
660        if context.available() < C::MIN_UNITS_PER_VALUE {
661            let required_total =
662                NonZeroUsize::new(C::MIN_UNITS_PER_VALUE).expect("Codec::MIN_UNITS_PER_VALUE is non-zero");
663            if !end_of_input {
664                return Ok((DecodeOutcome::need_input(required_total), None));
665            }
666            return match self
667                .hooks
668                .handle_incomplete_decode(&mut self.codec, None, required_total, context)?
669            {
670                DecodeIncompleteAction::Reject => Err(TranscodeFailure::incomplete_input(
671                    context.input_index(),
672                    required_total.get(),
673                    context.available(),
674                )
675                .into()),
676                DecodeIncompleteAction::Skip => {
677                    let read = NonZeroUsize::new(context.available())
678                        .expect("incomplete decode tail must contain source units");
679                    Ok((DecodeOutcome::skipped(read), None))
680                }
681                DecodeIncompleteAction::Emit { value } => {
682                    let read = NonZeroUsize::new(context.available())
683                        .expect("incomplete decode tail must contain source units");
684                    let consumed_value = consume(value, context.input_index());
685                    Ok((DecodeOutcome::emitted(read, NonZeroUsize::MIN), Some(consumed_value)))
686                }
687            };
688        }
689
690        // SAFETY: The context reports at least `MIN_UNITS_PER_VALUE` source
691        // units available from `context.input_index()`.
692        let result = unsafe {
693            if end_of_input {
694                self.codec.decode_eof(input, context.input_index())
695            } else {
696                self.codec.decode(input, context.input_index())
697            }
698        };
699        match result {
700            Ok((value, consumed)) => {
701                assert!(
702                    consumed.get() <= context.available(),
703                    "Codec::decode consumed beyond available input",
704                );
705                assert!(
706                    consumed.get() <= C::MAX_DECODE_UNITS_PER_VALUE,
707                    "Codec::decode consumed beyond Codec::MAX_DECODE_UNITS_PER_VALUE",
708                );
709                let consumed_value = consume(value, context.input_index());
710                Ok((
711                    DecodeOutcome::emitted(consumed, NonZeroUsize::MIN),
712                    Some(consumed_value),
713                ))
714            }
715            Err(DecodeFailure::Incomplete { source, required_total }) => {
716                assert!(
717                    required_total.get() > context.available(),
718                    "Codec::decode incomplete required_total must exceed available input",
719                );
720                assert!(
721                    required_total.get() <= C::MAX_DECODE_UNITS_PER_VALUE,
722                    "Codec::decode incomplete required_total exceeded Codec::MAX_DECODE_UNITS_PER_VALUE",
723                );
724                if !end_of_input {
725                    return Ok((DecodeOutcome::need_input(required_total), None));
726                }
727                match self
728                    .hooks
729                    .handle_incomplete_decode(&mut self.codec, source.as_ref(), required_total, context)?
730                {
731                    DecodeIncompleteAction::Reject => match source {
732                        Some(source) => Err(TranscodeDecodeError::domain_main(source, context.input_index())),
733                        None => Err(TranscodeFailure::incomplete_input(
734                            context.input_index(),
735                            required_total.get(),
736                            context.available(),
737                        )
738                        .into()),
739                    },
740                    DecodeIncompleteAction::Skip => {
741                        let read = NonZeroUsize::new(context.available())
742                            .expect("incomplete decode tail must contain source units");
743                        Ok((DecodeOutcome::skipped(read), None))
744                    }
745                    DecodeIncompleteAction::Emit { value } => {
746                        let read = NonZeroUsize::new(context.available())
747                            .expect("incomplete decode tail must contain source units");
748                        let consumed_value = consume(value, context.input_index());
749                        Ok((DecodeOutcome::emitted(read, NonZeroUsize::MIN), Some(consumed_value)))
750                    }
751                }
752            }
753            Err(DecodeFailure::Invalid { source, consumed }) => {
754                let action = match self
755                    .hooks
756                    .handle_invalid_decode(&mut self.codec, &source, consumed, context)?
757                {
758                    DecodeInvalidAction::Reject => {
759                        return Err(TranscodeDecodeError::domain_main_with_consumed(
760                            source,
761                            context.input_index(),
762                            consumed,
763                        ));
764                    }
765                    DecodeInvalidAction::Skip { consumed } => AppliedDecodeInvalidAction::Skip { consumed },
766                    DecodeInvalidAction::Emit { value, consumed } => {
767                        AppliedDecodeInvalidAction::Emit { value, consumed }
768                    }
769                };
770                Ok(Self::apply_invalid_decode_action(action, context, consume))
771            }
772        }
773    }
774
775    /// Runs one decode step with an explicit end-of-input flag.
776    ///
777    /// The helper centralizes lifecycle validation and shared cursor handling
778    /// for the streaming and EOF-aware entry points.
779    ///
780    /// # Parameters
781    ///
782    /// - `input`: Complete source-unit slice.
783    /// - `input_index`: Absolute index of the next source unit.
784    /// - `output`: Destination for decoded values.
785    /// - `output_index`: Absolute index of the next destination slot.
786    /// - `end_of_input`: Whether to resolve incomplete tails through EOF
787    ///   policy.
788    ///
789    /// # Returns
790    ///
791    /// Returns consumed/written counts and the reason decoding stopped.
792    ///
793    /// # Errors
794    ///
795    /// Returns framework errors for invalid lifecycle state or slice indices,
796    /// and policy/domain errors for rejected input, including incomplete EOF
797    /// tails.
798    ///
799    /// # Panics
800    ///
801    /// Panics when codec or hook progress violates declared decode bounds.
802    fn transcode_with_eof(
803        &mut self,
804        input: &[C::Unit],
805        input_index: usize,
806        output: &mut [C::Value],
807        output_index: usize,
808        end_of_input: bool,
809    ) -> Result<TranscodeProgress, TranscodeDecodeErrorOf<C>> {
810        self.lifecycle.on_transcode()?;
811        TranscodeFailure::ensure_transcode_indices(input.len(), input_index, output.len(), output_index)?;
812
813        let min_units = NonZeroUsize::new(C::MIN_UNITS_PER_VALUE).expect("Codec::MIN_UNITS_PER_VALUE is non-zero");
814        let min_units_len = min_units.get();
815        let mut state = DecodeState::new(input, input_index, output, output_index);
816        while state.has_input() {
817            let context = state.context();
818            let available = context.available();
819            if available < min_units_len {
820                if !end_of_input {
821                    return Ok(state.need_input_progress_with(min_units));
822                }
823                match self
824                    .hooks
825                    .handle_incomplete_decode(&mut self.codec, None, min_units, context)?
826                {
827                    DecodeIncompleteAction::Reject => {
828                        return Err(TranscodeFailure::incomplete_input(
829                            context.input_index(),
830                            min_units.get(),
831                            available,
832                        )
833                        .into());
834                    }
835                    DecodeIncompleteAction::Skip => {
836                        let read =
837                            NonZeroUsize::new(available).expect("incomplete decode tail must contain source units");
838                        if let Some(progress) = state.apply_decode_outcome(DecodeOutcome::skipped(read)) {
839                            return Ok(progress);
840                        }
841                        continue;
842                    }
843                    DecodeIncompleteAction::Emit { value } => {
844                        if state.needs_output() {
845                            return Ok(state.need_output_progress());
846                        }
847                        let output_index = state.output_cursor();
848                        // SAFETY: `needs_output()` returned false, so the
849                        // output cursor points at a writable initialized slot.
850                        unsafe {
851                            *state.output_mut().get_unchecked_mut(output_index) = value;
852                        }
853                        let read =
854                            NonZeroUsize::new(available).expect("incomplete decode tail must contain source units");
855                        if let Some(progress) =
856                            state.apply_decode_outcome(DecodeOutcome::emitted(read, NonZeroUsize::MIN))
857                        {
858                            return Ok(progress);
859                        }
860                        continue;
861                    }
862                }
863            }
864            if state.needs_output() {
865                return Ok(state.need_output_progress());
866            }
867            let output_index = state.output_cursor();
868            let output = state.output_mut();
869            let (outcome, _) = self.decode_one(input, context, end_of_input, |value, _input_index| {
870                // SAFETY: `needs_output()` returned false, so the output
871                // cursor points at a writable initialized slot.
872                unsafe {
873                    *output.get_unchecked_mut(output_index) = value;
874                }
875            })?;
876            if let Some(progress) = state.apply_decode_outcome(outcome) {
877                return Ok(progress);
878            }
879        }
880
881        Ok(state.complete_progress())
882    }
883
884    /// Applies a hook-selected invalid-decode action after reject handling.
885    ///
886    /// # Type Parameters
887    ///
888    /// - `R`: Consumer result for an emitted value.
889    /// - `F`: Callback consuming an emitted value and its source index.
890    ///
891    /// # Parameters
892    ///
893    /// - `action`: Validated policy action to skip or emit.
894    /// - `context`: Source cursor and available input.
895    /// - `consume`: Callback invoked only for an emitted value.
896    ///
897    /// # Returns
898    ///
899    /// Returns progress with `Some` callback result for Emit, or `None` for
900    /// Skip.
901    ///
902    /// # Panics
903    ///
904    /// Panics if the action consumes more units than the context makes
905    /// available.
906    fn apply_invalid_decode_action<R, F>(
907        action: AppliedDecodeInvalidAction<C::Value>,
908        context: DecodeContext,
909        consume: F,
910    ) -> (DecodeOutcome, Option<R>)
911    where
912        F: FnOnce(C::Value, usize) -> R,
913    {
914        match action {
915            AppliedDecodeInvalidAction::Skip { consumed } => {
916                let read = DecodeInvalidAction::<C::Value>::bound_consumed(consumed, context.available());
917                (DecodeOutcome::skipped(read), None)
918            }
919            AppliedDecodeInvalidAction::Emit { value, consumed } => {
920                let read = DecodeInvalidAction::<C::Value>::bound_consumed(consumed, context.available());
921                let consumed_value = consume(value, context.input_index());
922                (DecodeOutcome::emitted(read, NonZeroUsize::MIN), Some(consumed_value))
923            }
924        }
925    }
926}
927
928impl<C, H> Transcoder for TranscodeDecodeEngine<C, H>
929where
930    C: Codec,
931    H: TranscodeDecodeHooks<C>,
932{
933    /// Source units accepted by the wrapped codec.
934    type Input = C::Unit;
935    /// Logical values decoded by the wrapped codec.
936    type Output = C::Value;
937    /// Framework failures and the wrapped codec's decode errors.
938    type Error = TranscodeDecodeErrorOf<C>;
939
940    /// Returns an upper bound for decoded values produced from `input_len`
941    /// units.
942    ///
943    /// # Parameters
944    ///
945    /// - `input_len`: Number of source units to decode.
946    ///
947    /// # Returns
948    ///
949    /// Returns the conservative streaming output bound.
950    ///
951    /// # Errors
952    ///
953    /// Returns a capacity error on hook arithmetic overflow.
954    #[inline]
955    fn max_transcode_output_len(&self, input_len: usize) -> Result<usize, CapacityError> {
956        TranscodeDecodeEngine::max_transcode_output_len(self, input_len)
957    }
958
959    /// Returns an upper bound for values produced by finishing codec and hook
960    /// state.
961    ///
962    /// # Returns
963    ///
964    /// Returns the combined codec and hook finish bound.
965    ///
966    /// # Errors
967    ///
968    /// Returns a capacity error if that sum overflows.
969    #[inline]
970    fn max_finish_output_len(&self) -> Result<usize, CapacityError> {
971        TranscodeDecodeEngine::max_finish_output_len(self)
972    }
973
974    /// Returns an upper bound for values emitted when resetting stream state.
975    ///
976    /// # Returns
977    ///
978    /// Returns the codec reset bound as `Ok`; this query cannot fail.
979    #[inline]
980    fn max_reset_output_len(&self) -> Result<usize, CapacityError> {
981        TranscodeDecodeEngine::max_reset_output_len(self)
982    }
983
984    /// Resets hooks and codec state, emitting any stream-start values.
985    ///
986    /// # Parameters
987    ///
988    /// - `output`: Destination value slice.
989    /// - `output_index`: First writable value index.
990    ///
991    /// # Returns
992    ///
993    /// Returns the number of stream-start values written.
994    ///
995    /// # Errors
996    ///
997    /// Returns invalid-capacity/index errors or codec reset domain errors.
998    ///
999    /// # Panics
1000    ///
1001    /// Panics if codec reset output exceeds its declared bound.
1002    fn reset(&mut self, output: &mut [C::Value], output_index: usize) -> Result<usize, TranscodeDecodeErrorOf<C>> {
1003        TranscodeDecodeEngine::reset(self, output, output_index)
1004    }
1005
1006    /// Decodes source units into logical values.
1007    ///
1008    /// # Parameters
1009    ///
1010    /// - `input`: Source unit slice.
1011    /// - `input_index`: First source index.
1012    /// - `output`: Destination value slice.
1013    /// - `output_index`: First destination index.
1014    ///
1015    /// # Returns
1016    ///
1017    /// Returns consumed/written counts and the stop status.
1018    ///
1019    /// # Errors
1020    ///
1021    /// Returns lifecycle/index errors or rejected-input domain errors.
1022    ///
1023    /// # Panics
1024    ///
1025    /// Panics if codec or hook progress violates decode bounds.
1026    fn transcode(
1027        &mut self,
1028        input: &[C::Unit],
1029        input_index: usize,
1030        output: &mut [C::Value],
1031        output_index: usize,
1032    ) -> Result<TranscodeProgress, TranscodeDecodeErrorOf<C>> {
1033        TranscodeDecodeEngine::transcode(self, input, input_index, output, output_index)
1034    }
1035
1036    /// Decodes source units after end of input is known.
1037    ///
1038    /// # Parameters
1039    ///
1040    /// - `input`: Final source unit slice.
1041    /// - `input_index`: First source index.
1042    /// - `output`: Destination value slice.
1043    /// - `output_index`: First destination index.
1044    ///
1045    /// # Returns
1046    ///
1047    /// Returns consumed/written counts and the stop status.
1048    ///
1049    /// # Errors
1050    ///
1051    /// Returns lifecycle/index errors or rejected input and incomplete-tail
1052    /// errors.
1053    ///
1054    /// # Panics
1055    ///
1056    /// Panics if codec or hook progress violates decode bounds.
1057    fn transcode_eof(
1058        &mut self,
1059        input: &[C::Unit],
1060        input_index: usize,
1061        output: &mut [C::Value],
1062        output_index: usize,
1063    ) -> Result<TranscodeProgress, TranscodeDecodeErrorOf<C>> {
1064        TranscodeDecodeEngine::transcode_eof(self, input, input_index, output, output_index)
1065    }
1066
1067    /// Finishes internally retained output after EOF.
1068    ///
1069    /// # Parameters
1070    ///
1071    /// - `output`: Destination value slice.
1072    /// - `output_index`: First writable value index.
1073    ///
1074    /// # Returns
1075    ///
1076    /// Returns the number of final values written.
1077    ///
1078    /// # Errors
1079    ///
1080    /// Returns lifecycle/capacity/index errors or codec/hook finish errors.
1081    ///
1082    /// # Panics
1083    ///
1084    /// Panics if finalization output exceeds its declared bounds.
1085    fn finish(&mut self, output: &mut [C::Value], output_index: usize) -> Result<usize, TranscodeDecodeErrorOf<C>> {
1086        TranscodeDecodeEngine::finish(self, output, output_index)
1087    }
1088}
1089
1090impl<C, H> TranscodeDecoder for TranscodeDecodeEngine<C, H>
1091where
1092    C: Codec,
1093    H: TranscodeDecodeHooks<C>,
1094{
1095    /// Domain error reported by the wrapped codec while decoding.
1096    type DecodeError = C::DecodeError;
1097}