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    #[inline]
473    pub fn transcode(
474        &mut self,
475        input: &[C::Unit],
476        input_index: usize,
477        output: &mut [C::Value],
478        output_index: usize,
479    ) -> Result<TranscodeProgress, TranscodeDecodeErrorOf<C>> {
480        self.transcode_with_eof(input, input_index, output, output_index, false)
481    }
482
483    /// Decodes source units after the caller has established end of input.
484    ///
485    /// This follows the normal streaming contract, except that codec attempts
486    /// use [`Codec::decode_eof`]. A codec may therefore resolve a trailing
487    /// prefix that would remain incomplete in an open stream.
488    ///
489    /// # Parameters
490    ///
491    /// - `input`: Complete source-unit slice.
492    /// - `input_index`: Absolute index of the next source unit.
493    /// - `output`: Destination for decoded values.
494    /// - `output_index`: Absolute index of the next destination slot.
495    ///
496    /// # Returns
497    ///
498    /// Returns consumed/written counts and the reason decoding stopped.
499    ///
500    /// # Errors
501    ///
502    /// At confirmed EOF, an incomplete tail requires one writable output slot
503    /// before the incomplete-input hook runs, including when that hook might
504    /// skip or reject. A capacity shortage leaves both the tail and hook state
505    /// untouched; errors after hook execution do not roll back hook mutations.
506    ///
507    /// Returns framework errors for invalid lifecycle state or slice indices,
508    /// and policy/domain errors for rejected input, including incomplete EOF
509    /// tails.
510    ///
511    /// # Panics
512    ///
513    /// Panics when codec or hook progress violates declared decode bounds.
514    #[inline]
515    pub fn transcode_eof(
516        &mut self,
517        input: &[C::Unit],
518        input_index: usize,
519        output: &mut [C::Value],
520        output_index: usize,
521    ) -> Result<TranscodeProgress, TranscodeDecodeErrorOf<C>> {
522        self.transcode_with_eof(input, input_index, output, output_index, true)
523    }
524
525    /// Finishes codec and hook-owned output after EOF.
526    ///
527    /// Finalization first finishes decode-side codec state through
528    /// [`Codec::decode_finish`], then lets hook implementations finish their
529    /// own retained state. The caller must provide enough output capacity for
530    /// [`TranscodeDecodeEngine::max_finish_output_len`], which includes both
531    /// the codec finish bound and the hook-owned finish bound.
532    ///
533    /// # Parameters
534    ///
535    /// - `output`: Complete output value slice visible to the decoder.
536    /// - `output_index`: Absolute output value index where writing starts.
537    ///
538    /// # Returns
539    ///
540    /// Returns the number of values written by finalization.
541    ///
542    /// # Errors
543    ///
544    /// Returns framework errors when the caller provides invalid or
545    /// insufficient output capacity. Returns domain errors when codec finish or
546    /// hook finalization fails. Returns
547    /// [`TranscodeFailure::FinishBeforeReset`] when the engine has not
548    /// completed its first reset. Returns
549    /// [`TranscodeFailure::FinishAfterFinish`] when the logical stream was
550    /// already finished and has not been reset, or
551    /// [`TranscodeFailure::LifecyclePoisoned`] when an earlier reset or finish
552    /// failed after execution started. Capacity and index failures occur before
553    /// finish execution and remain retryable; later failures poison the engine
554    /// until reset succeeds.
555    ///
556    /// # Panics
557    ///
558    /// Panics when the codec finish or finish hooks write beyond their
559    /// independently declared output bounds.
560    pub fn finish(&mut self, output: &mut [C::Value], output_index: usize) -> Result<usize, TranscodeDecodeErrorOf<C>> {
561        self.lifecycle.on_finish_attempt()?;
562        let hook_required = self.hooks.max_finish_output_len(&self.codec);
563        let required = C::MAX_DECODE_FINISH_VALUES
564            .checked_add(hook_required)
565            .ok_or(CapacityError::OutputLengthOverflow)?;
566        TranscodeFailure::ensure_output_capacity(output.len(), output_index, required)?;
567        self.lifecycle.on_finish_start();
568        let finished =
569            unsafe { self.codec.decode_finish(output, output_index) }.map_err(TranscodeDecodeError::domain_finish)?;
570        assert!(
571            finished <= C::MAX_DECODE_FINISH_VALUES,
572            "Codec::decode_finish wrote beyond its finish bound",
573        );
574        let written = self
575            .hooks
576            .finish_hooks(&mut self.codec, output, output_index + finished)?;
577        assert!(
578            written <= hook_required,
579            "TranscodeDecodeEngine hook wrote beyond its finish bound",
580        );
581        self.lifecycle.on_finish_success();
582        Ok(finished + written)
583    }
584
585    /// Runs a complete one-shot `reset -> transcode -> finish` decode stream.
586    ///
587    /// The complete input is supplied as `input`, and output starts at index
588    /// `0` in `output`. Callers that need subranges should slice their
589    /// buffers before calling this method. Downstream one-shot decoder
590    /// helpers should call this engine method instead of reproducing the
591    /// reset, transcode, and finish sequence themselves.
592    ///
593    /// # Parameters
594    ///
595    /// - `input`: Complete source unit slice.
596    /// - `output`: Output value slice for the whole decoded stream.
597    ///
598    /// # Returns
599    ///
600    /// Returns the number of output values written.
601    ///
602    /// # Errors
603    ///
604    /// Returns framework errors for insufficient output, capacity overflow, or
605    /// an incomplete EOF tail, and domain errors from reset, decode, or
606    /// finish.
607    ///
608    /// # Panics
609    ///
610    /// Panics when codec or hook output violates reset, decode, or finish
611    /// bounds.
612    #[inline]
613    pub fn transcode_complete_into(
614        &mut self,
615        input: &[C::Unit],
616        output: &mut [C::Value],
617    ) -> Result<usize, TranscodeDecodeErrorOf<C>> {
618        <Self as Transcoder>::transcode_complete_into(self, input, output)
619    }
620
621    /// Decodes one source value attempt and delivers emitted values.
622    ///
623    /// # Parameters
624    ///
625    /// - `input`: Complete input unit slice visible to the caller.
626    /// - `context`: Decode context describing the current source and output
627    ///   cursors.
628    /// - `end_of_input`: Whether the source is final and EOF policy applies.
629    /// - `consume`: Callback invoked exactly once when this attempt emits a
630    ///   logical value.
631    ///
632    /// # Type Parameters
633    ///
634    /// - `R`: Value returned by the consumer when a decoded value is emitted.
635    /// - `F`: Consumer callback type.
636    ///
637    /// # Returns
638    ///
639    /// Returns the decode outcome and `Some` consumer result when a value was
640    /// emitted; returns `None` when input was skipped or more input is needed.
641    ///
642    /// # Errors
643    ///
644    /// Returns hook errors when the decode policy rejects the input.
645    ///
646    /// # Panics
647    ///
648    /// Panics when the codec reports consumption beyond the available input,
649    /// an incomplete-input requirement beyond
650    /// [`Codec::MAX_DECODE_UNITS_PER_VALUE`], or hooks return an action that
651    /// consumes beyond the available input. Also panics when reported consumed
652    /// width exceeds the codec maximum or an incomplete requirement does not
653    /// exceed available input. Debug builds reject an empty context.
654    pub(crate) fn decode_one<R, F>(
655        &mut self,
656        input: &[C::Unit],
657        context: DecodeContext,
658        end_of_input: bool,
659        consume: F,
660    ) -> Result<(DecodeOutcome, Option<R>), TranscodeDecodeErrorOf<C>>
661    where
662        F: FnOnce(C::Value, usize) -> R,
663    {
664        debug_assert!(
665            context.available() > 0,
666            "decode_one requires at least one source input unit",
667        );
668
669        if context.available() < C::MIN_UNITS_PER_VALUE {
670            let required_total =
671                NonZeroUsize::new(C::MIN_UNITS_PER_VALUE).expect("Codec::MIN_UNITS_PER_VALUE is non-zero");
672            if !end_of_input {
673                return Ok((DecodeOutcome::need_input(required_total), None));
674            }
675            return self.apply_incomplete_decode(None, required_total, context, consume);
676        }
677
678        // SAFETY: The context reports at least `MIN_UNITS_PER_VALUE` source
679        // units available from `context.input_index()`.
680        let result = unsafe {
681            if end_of_input {
682                self.codec.decode_eof(input, context.input_index())
683            } else {
684                self.codec.decode(input, context.input_index())
685            }
686        };
687        match result {
688            Ok((value, consumed)) => {
689                assert!(
690                    consumed.get() <= context.available(),
691                    "Codec::decode consumed beyond available input",
692                );
693                assert!(
694                    consumed.get() <= C::MAX_DECODE_UNITS_PER_VALUE,
695                    "Codec::decode consumed beyond Codec::MAX_DECODE_UNITS_PER_VALUE",
696                );
697                let consumed_value = consume(value, context.input_index());
698                Ok((
699                    DecodeOutcome::emitted(consumed, NonZeroUsize::MIN),
700                    Some(consumed_value),
701                ))
702            }
703            Err(DecodeFailure::Incomplete { source, required_total }) => {
704                assert!(
705                    required_total.get() > context.available(),
706                    "Codec::decode incomplete required_total must exceed available input",
707                );
708                assert!(
709                    required_total.get() <= C::MAX_DECODE_UNITS_PER_VALUE,
710                    "Codec::decode incomplete required_total exceeded Codec::MAX_DECODE_UNITS_PER_VALUE",
711                );
712                if !end_of_input {
713                    return Ok((DecodeOutcome::need_input(required_total), None));
714                }
715                self.apply_incomplete_decode(source, required_total, context, consume)
716            }
717            Err(DecodeFailure::Invalid { source, consumed }) => {
718                let action = match self
719                    .hooks
720                    .handle_invalid_decode(&mut self.codec, &source, consumed, context)?
721                {
722                    DecodeInvalidAction::Reject => {
723                        return Err(TranscodeDecodeError::domain_main_with_consumed(
724                            source,
725                            context.input_index(),
726                            consumed,
727                        ));
728                    }
729                    DecodeInvalidAction::Skip { consumed } => AppliedDecodeInvalidAction::Skip { consumed },
730                    DecodeInvalidAction::Emit { value, consumed } => {
731                        AppliedDecodeInvalidAction::Emit { value, consumed }
732                    }
733                };
734                Ok(Self::apply_invalid_decode_action(action, context, consume))
735            }
736        }
737    }
738
739    /// Runs one decode step with an explicit end-of-input flag.
740    ///
741    /// The helper centralizes lifecycle validation and shared cursor handling
742    /// for the streaming and EOF-aware entry points.
743    ///
744    /// # Parameters
745    ///
746    /// - `input`: Complete source-unit slice.
747    /// - `input_index`: Absolute index of the next source unit.
748    /// - `output`: Destination for decoded values.
749    /// - `output_index`: Absolute index of the next destination slot.
750    /// - `end_of_input`: Whether to resolve incomplete tails through EOF
751    ///   policy.
752    ///
753    /// # Returns
754    ///
755    /// Returns consumed/written counts and the reason decoding stopped.
756    ///
757    /// # Errors
758    ///
759    /// Returns framework errors for invalid lifecycle state or slice indices,
760    /// and policy/domain errors for rejected input, including incomplete EOF
761    /// tails.
762    ///
763    /// # Panics
764    ///
765    /// Panics when codec or hook progress violates declared decode bounds.
766    fn transcode_with_eof(
767        &mut self,
768        input: &[C::Unit],
769        input_index: usize,
770        output: &mut [C::Value],
771        output_index: usize,
772        end_of_input: bool,
773    ) -> Result<TranscodeProgress, TranscodeDecodeErrorOf<C>> {
774        self.lifecycle.on_transcode()?;
775        TranscodeFailure::ensure_transcode_indices(input.len(), input_index, output.len(), output_index)?;
776
777        let min_units = NonZeroUsize::new(C::MIN_UNITS_PER_VALUE).expect("Codec::MIN_UNITS_PER_VALUE is non-zero");
778        let min_units_len = min_units.get();
779        let mut state = DecodeState::new(input, input_index, output, output_index);
780        while state.has_input() {
781            let context = state.context();
782            let available = context.available();
783            if available < min_units_len {
784                if !end_of_input {
785                    return Ok(state.need_input_progress_with(min_units));
786                }
787                if state.needs_output() {
788                    return Ok(state.need_output_progress());
789                }
790                let output_index = state.output_cursor();
791                let output = state.output_mut();
792                let (outcome, _) = self.decode_one(input, context, true, |value, _input_index| {
793                    // SAFETY: The empty-output check above proved this slot writable.
794                    unsafe {
795                        *output.get_unchecked_mut(output_index) = value;
796                    }
797                })?;
798                if let Some(progress) = state.apply_decode_outcome(outcome) {
799                    return Ok(progress);
800                }
801                continue;
802            }
803            if state.needs_output() {
804                return Ok(state.need_output_progress());
805            }
806            let output_index = state.output_cursor();
807            let output = state.output_mut();
808            let (outcome, _) = self.decode_one(input, context, end_of_input, |value, _input_index| {
809                // SAFETY: `needs_output()` returned false, so the output
810                // cursor points at a writable initialized slot.
811                unsafe {
812                    *output.get_unchecked_mut(output_index) = value;
813                }
814            })?;
815            if let Some(progress) = state.apply_decode_outcome(outcome) {
816                return Ok(progress);
817            }
818        }
819
820        Ok(state.complete_progress())
821    }
822
823    /// Applies a hook-selected invalid-decode action after reject handling.
824    ///
825    /// # Type Parameters
826    ///
827    /// - `R`: Consumer result for an emitted value.
828    /// - `F`: Callback consuming an emitted value and its source index.
829    ///
830    /// # Parameters
831    ///
832    /// - `action`: Validated policy action to skip or emit.
833    /// - `context`: Source cursor and available input.
834    /// - `consume`: Callback invoked only for an emitted value.
835    ///
836    /// # Returns
837    ///
838    /// Returns progress with `Some` callback result for Emit, or `None` for
839    /// Skip.
840    ///
841    /// # Panics
842    ///
843    /// Panics if the action consumes more units than the context makes
844    /// available.
845    fn apply_invalid_decode_action<R, F>(
846        action: AppliedDecodeInvalidAction<C::Value>,
847        context: DecodeContext,
848        consume: F,
849    ) -> (DecodeOutcome, Option<R>)
850    where
851        F: FnOnce(C::Value, usize) -> R,
852    {
853        match action {
854            AppliedDecodeInvalidAction::Skip { consumed } => {
855                let read = DecodeInvalidAction::<C::Value>::bound_consumed(consumed, context.available());
856                (DecodeOutcome::skipped(read), None)
857            }
858            AppliedDecodeInvalidAction::Emit { value, consumed } => {
859                let read = DecodeInvalidAction::<C::Value>::bound_consumed(consumed, context.available());
860                let consumed_value = consume(value, context.input_index());
861                (DecodeOutcome::emitted(read, NonZeroUsize::MIN), Some(consumed_value))
862            }
863        }
864    }
865
866    /// Applies the hook policy to an incomplete input tail.
867    ///
868    /// # Parameters
869    ///
870    /// - `source`: Optional codec error associated with the incomplete tail.
871    /// - `required_total`: Minimum total input width needed to decode a value.
872    /// - `context`: Decode cursors and the number of visible source units.
873    /// - `consume`: Callback used once when the policy emits a value.
874    ///
875    /// # Returns
876    ///
877    /// Returns the resulting decode outcome and an optional consumer result.
878    ///
879    /// # Errors
880    ///
881    /// Returns the hook error or the appropriate incomplete-input rejection,
882    /// preserving a codec error source when one was supplied.
883    fn apply_incomplete_decode<R, F>(
884        &mut self,
885        source: Option<C::DecodeError>,
886        required_total: NonZeroUsize,
887        context: DecodeContext,
888        consume: F,
889    ) -> Result<(DecodeOutcome, Option<R>), TranscodeDecodeErrorOf<C>>
890    where
891        F: FnOnce(C::Value, usize) -> R,
892    {
893        match self
894            .hooks
895            .handle_incomplete_decode(&mut self.codec, source.as_ref(), required_total, context)?
896        {
897            DecodeIncompleteAction::Reject => match source {
898                Some(source) => Err(TranscodeDecodeError::domain_main(source, context.input_index())),
899                None => Err(TranscodeFailure::incomplete_input(
900                    context.input_index(),
901                    required_total.get(),
902                    context.available(),
903                )
904                .into()),
905            },
906            DecodeIncompleteAction::Skip => {
907                let read =
908                    NonZeroUsize::new(context.available()).expect("incomplete decode tail must contain source units");
909                Ok((DecodeOutcome::skipped(read), None))
910            }
911            DecodeIncompleteAction::Emit { value } => {
912                let read =
913                    NonZeroUsize::new(context.available()).expect("incomplete decode tail must contain source units");
914                let result = consume(value, context.input_index());
915                Ok((DecodeOutcome::emitted(read, NonZeroUsize::MIN), Some(result)))
916            }
917        }
918    }
919}
920
921impl<C, H> Transcoder for TranscodeDecodeEngine<C, H>
922where
923    C: Codec,
924    H: TranscodeDecodeHooks<C>,
925{
926    /// Source units accepted by the wrapped codec.
927    type Input = C::Unit;
928    /// Logical values decoded by the wrapped codec.
929    type Output = C::Value;
930    /// Framework failures and the wrapped codec's decode errors.
931    type Error = TranscodeDecodeErrorOf<C>;
932
933    /// Returns an upper bound for decoded values produced from `input_len`
934    /// units.
935    ///
936    /// # Parameters
937    ///
938    /// - `input_len`: Number of source units to decode.
939    ///
940    /// # Returns
941    ///
942    /// Returns the conservative streaming output bound.
943    ///
944    /// # Errors
945    ///
946    /// Returns a capacity error on hook arithmetic overflow.
947    #[inline]
948    fn max_transcode_output_len(&self, input_len: usize) -> Result<usize, CapacityError> {
949        TranscodeDecodeEngine::max_transcode_output_len(self, input_len)
950    }
951
952    /// Returns an upper bound for values produced by finishing codec and hook
953    /// state.
954    ///
955    /// # Returns
956    ///
957    /// Returns the combined codec and hook finish bound.
958    ///
959    /// # Errors
960    ///
961    /// Returns a capacity error if that sum overflows.
962    #[inline]
963    fn max_finish_output_len(&self) -> Result<usize, CapacityError> {
964        TranscodeDecodeEngine::max_finish_output_len(self)
965    }
966
967    /// Returns an upper bound for values emitted when resetting stream state.
968    ///
969    /// # Returns
970    ///
971    /// Returns the codec reset bound as `Ok`; this query cannot fail.
972    #[inline]
973    fn max_reset_output_len(&self) -> Result<usize, CapacityError> {
974        TranscodeDecodeEngine::max_reset_output_len(self)
975    }
976
977    /// Resets hooks and codec state, emitting any stream-start values.
978    ///
979    /// # Parameters
980    ///
981    /// - `output`: Destination value slice.
982    /// - `output_index`: First writable value index.
983    ///
984    /// # Returns
985    ///
986    /// Returns the number of stream-start values written.
987    ///
988    /// # Errors
989    ///
990    /// Returns invalid-capacity/index errors or codec reset domain errors.
991    ///
992    /// # Panics
993    ///
994    /// Panics if codec reset output exceeds its declared bound.
995    fn reset(&mut self, output: &mut [C::Value], output_index: usize) -> Result<usize, TranscodeDecodeErrorOf<C>> {
996        TranscodeDecodeEngine::reset(self, output, output_index)
997    }
998
999    /// Decodes source units into logical values.
1000    ///
1001    /// # Parameters
1002    ///
1003    /// - `input`: Source unit slice.
1004    /// - `input_index`: First source index.
1005    /// - `output`: Destination value slice.
1006    /// - `output_index`: First destination index.
1007    ///
1008    /// # Returns
1009    ///
1010    /// Returns consumed/written counts and the stop status.
1011    ///
1012    /// # Errors
1013    ///
1014    /// Returns lifecycle/index errors or rejected-input domain errors.
1015    ///
1016    /// # Panics
1017    ///
1018    /// Panics if codec or hook progress violates decode bounds.
1019    fn transcode(
1020        &mut self,
1021        input: &[C::Unit],
1022        input_index: usize,
1023        output: &mut [C::Value],
1024        output_index: usize,
1025    ) -> Result<TranscodeProgress, TranscodeDecodeErrorOf<C>> {
1026        TranscodeDecodeEngine::transcode(self, input, input_index, output, output_index)
1027    }
1028
1029    /// Decodes source units after end of input is known.
1030    ///
1031    /// # Parameters
1032    ///
1033    /// - `input`: Final source unit slice.
1034    /// - `input_index`: First source index.
1035    /// - `output`: Destination value slice.
1036    /// - `output_index`: First destination index.
1037    ///
1038    /// # Returns
1039    ///
1040    /// Returns consumed/written counts and the stop status.
1041    ///
1042    /// # Errors
1043    ///
1044    /// Returns lifecycle/index errors or rejected input and incomplete-tail
1045    /// errors.
1046    ///
1047    /// # Panics
1048    ///
1049    /// Panics if codec or hook progress violates decode bounds.
1050    fn transcode_eof(
1051        &mut self,
1052        input: &[C::Unit],
1053        input_index: usize,
1054        output: &mut [C::Value],
1055        output_index: usize,
1056    ) -> Result<TranscodeProgress, TranscodeDecodeErrorOf<C>> {
1057        TranscodeDecodeEngine::transcode_eof(self, input, input_index, output, output_index)
1058    }
1059
1060    /// Finishes internally retained output after EOF.
1061    ///
1062    /// # Parameters
1063    ///
1064    /// - `output`: Destination value slice.
1065    /// - `output_index`: First writable value index.
1066    ///
1067    /// # Returns
1068    ///
1069    /// Returns the number of final values written.
1070    ///
1071    /// # Errors
1072    ///
1073    /// Returns lifecycle/capacity/index errors or codec/hook finish errors.
1074    ///
1075    /// # Panics
1076    ///
1077    /// Panics if finalization output exceeds its declared bounds.
1078    fn finish(&mut self, output: &mut [C::Value], output_index: usize) -> Result<usize, TranscodeDecodeErrorOf<C>> {
1079        TranscodeDecodeEngine::finish(self, output, output_index)
1080    }
1081}
1082
1083impl<C, H> TranscodeDecoder for TranscodeDecodeEngine<C, H>
1084where
1085    C: Codec,
1086    H: TranscodeDecodeHooks<C>,
1087{
1088    /// Domain error reported by the wrapped codec while decoding.
1089    type DecodeError = C::DecodeError;
1090}