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