qubit_codec/transcode/transcoder.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// =============================================================================
8use super::capacity_error::CapacityError;
9use super::transcode_failure::TranscodeFailure;
10use super::transcode_progress::TranscodeProgress;
11use super::transcode_status::TranscodeStatus;
12
13/// Validates one-shot transcode progress and returns completed output length.
14///
15/// Keeping progress classification independent of the concrete transcoder
16/// ensures every implementation receives identical trailing-input and
17/// streaming-stop handling.
18///
19/// # Parameters
20///
21/// - `progress`: Progress returned by the streaming transcode phase.
22/// - `input_len`: Total complete-input length supplied to the one-shot call.
23/// - `output_index`: Absolute output index used for the transcode phase.
24/// - `output_len`: Total output slice length.
25///
26/// # Returns
27///
28/// Returns the number of output units written when progress is complete.
29///
30/// # Errors
31///
32/// Returns a trailing-input, incomplete-input, or insufficient-output failure
33/// when progress reports a non-complete one-shot result.
34///
35/// # Panics
36///
37/// Panics when the transcoder reports progress inconsistent with the supplied
38/// input and output bounds.
39fn complete_progress_written(
40 progress: TranscodeProgress,
41 input_len: usize,
42 output_index: usize,
43 output_len: usize,
44) -> Result<usize, TranscodeFailure> {
45 assert!(
46 progress
47 .validate(0, input_len, output_index, output_len.saturating_sub(output_index),)
48 .is_ok(),
49 "Transcoder::transcode returned invalid progress",
50 );
51 match progress.status() {
52 TranscodeStatus::Complete => Ok(progress.written()),
53 TranscodeStatus::NeedOutput { required } => Err(TranscodeFailure::insufficient_output(
54 output_index + progress.written(),
55 required.get(),
56 output_len - output_index - progress.written(),
57 )),
58 TranscodeStatus::NeedInput { required } => Err(TranscodeFailure::incomplete_input(
59 progress.read(),
60 required.get(),
61 input_len - progress.read(),
62 )),
63 }
64}
65
66/// Adds two independent output-capacity bounds.
67///
68/// # Parameters
69///
70/// - `first`: First output-capacity bound.
71/// - `second`: Second output-capacity bound.
72///
73/// # Returns
74///
75/// Returns the sum of both bounds.
76///
77/// # Errors
78///
79/// Returns [`CapacityError::OutputLengthOverflow`] when the sum overflows.
80fn add_output_bounds(first: usize, second: usize) -> Result<usize, CapacityError> {
81 first.checked_add(second).ok_or(CapacityError::OutputLengthOverflow)
82}
83
84/// Adds the reset, transcode, and finish output-capacity bounds.
85///
86/// # Parameters
87///
88/// - `reset`: Reset-phase output-capacity bound.
89/// - `transcode`: Streaming transcode-phase output-capacity bound.
90/// - `finish`: Finish-phase output-capacity bound.
91///
92/// # Returns
93///
94/// Returns the complete lifecycle output-capacity bound.
95///
96/// # Errors
97///
98/// Returns [`CapacityError::OutputLengthOverflow`] when either addition
99/// overflows.
100fn sum_output_bounds(reset: usize, transcode: usize, finish: usize) -> Result<usize, CapacityError> {
101 let before_finish = add_output_bounds(reset, transcode)?;
102 add_output_bounds(before_finish, finish)
103}
104
105/// Converts one logical stream of input units into one logical stream of output
106/// units.
107///
108/// `transcode` is the main streaming API. It transforms a provided input
109/// segment and writes as much output as available buffer space allows. A
110/// successful `transcode` call must stop with exactly one of three meanings:
111/// all visible input was consumed (`Complete`), an incomplete tail remains
112/// caller-owned (`NeedInput`), or output capacity prevented further progress
113/// (`NeedOutput`).
114///
115/// A transcoder instance has a simple lifecycle:
116///
117/// 1. A newly created instance is uninitialized; call [`Transcoder::reset`]
118/// before the first stream. A reset instance is ready for a new logical
119/// stream.
120/// 2. Call [`Transcoder::transcode`] zero or more times while input is
121/// available.
122/// 3. Preserve any tail reported by [`crate::TranscodeStatus::NeedInput`] in
123/// the caller-owned input buffer.
124/// 4. Call [`Transcoder::finish`] after the caller knows no more input remains
125/// and has handled any incomplete tail. Size this final output with
126/// [`Transcoder::max_finish_output_len`].
127/// 5. After [`Transcoder::finish`] succeeds, call [`Transcoder::reset`] with a
128/// buffer sized by [`Transcoder::max_reset_output_len`] before starting
129/// another logical stream with the same instance.
130///
131/// The method is suitable for:
132/// - pull-style consumers that call conversion repeatedly as buffers arrive;
133/// - bounded output sinks that use `NeedOutput` progress during `transcode`;
134/// - stateless and stateful codecs that all return progress-oriented stopping
135/// reasons.
136///
137/// `finish` finalizes retained state only; it does not receive source input and
138/// does not reinterpret a tail previously reported by `NeedInput`. For
139/// codec-backed decoders, streaming uses
140/// [`Codec::decode`](crate::Codec::decode) and an explicit EOF call may use
141/// [`Codec::decode_eof`](crate::Codec::decode_eof)
142/// through [`Transcoder::transcode_eof`]. If a format needs EOF-aware
143/// maximal-munch parsing or must delay whether a prefix is complete until the
144/// next chunk or EOF, implement that policy in the codec or override
145/// `transcode_eof`.
146///
147/// `Transcoder` is intentionally independent from any charset
148/// semantics:
149///
150/// - Use `Transcoder` directly for custom, policy-free unit transforms.
151/// - Use `Transcoder` when you want to own malformed/unmappable decisions at
152/// the call site.
153///
154/// # Examples
155///
156/// Streaming byte-to-word decoding:
157///
158/// ```rust
159/// use core::convert::Infallible;
160/// use core::num::NonZeroUsize;
161///
162/// use qubit_codec::CapacityError;
163/// use qubit_codec::TranscodeDecodeError;
164/// use qubit_codec::TranscodeFailure;
165/// use qubit_codec::TranscodeProgress;
166/// use qubit_codec::TranscodeStatus;
167/// use qubit_codec::Transcoder;
168///
169/// #[derive(Default)]
170/// struct U16BeBytesDecoder;
171///
172/// impl Transcoder for U16BeBytesDecoder {
173/// type Input = u8;
174/// type Output = u16;
175/// type Error = TranscodeDecodeError<Infallible>;
176///
177/// fn max_transcode_output_len(&self, input_len: usize) -> Result<usize, CapacityError> {
178/// Ok(input_len / 2)
179/// }
180///
181/// fn reset(
182/// &mut self,
183/// output: &mut [u16],
184/// output_index: usize,
185/// ) -> Result<usize, Self::Error> {
186/// TranscodeFailure::ensure_output_index(output.len(), output_index)?;
187/// Ok(0)
188/// }
189///
190/// fn transcode(
191/// &mut self,
192/// input: &[u8],
193/// input_index: usize,
194/// output: &mut [u16],
195/// output_index: usize,
196/// ) -> Result<TranscodeProgress, Self::Error> {
197/// TranscodeFailure::ensure_transcode_indices(
198/// input.len(),
199/// input_index,
200/// output.len(),
201/// output_index,
202/// )?;
203///
204/// let mut read = 0;
205/// let mut written = 0;
206/// while input_index + read + 1 < input.len() {
207/// if output_index + written == output.len() {
208/// let status = TranscodeStatus::NeedOutput {
209/// required: NonZeroUsize::MIN,
210/// };
211/// return Ok(TranscodeProgress::new(status, read, written));
212/// }
213/// let high = input[input_index + read] as u16;
214/// let low = input[input_index + read + 1] as u16;
215/// output[output_index + written] = (high << 8) | low;
216/// read += 2;
217/// written += 1;
218/// }
219/// if input_index + read == input.len() {
220/// Ok(TranscodeProgress::complete(read, written))
221/// } else {
222/// let status = TranscodeStatus::NeedInput {
223/// required: NonZeroUsize::new(2).expect("two is non-zero"),
224/// };
225/// Ok(TranscodeProgress::new(status, read, written))
226/// }
227/// }
228///
229/// fn finish(
230/// &mut self,
231/// output: &mut [u16],
232/// output_index: usize,
233/// ) -> Result<usize, Self::Error> {
234/// TranscodeFailure::ensure_output_index(output.len(), output_index)?;
235/// Ok(0)
236/// }
237/// }
238///
239/// let mut transcoder = U16BeBytesDecoder::default();
240/// let mut reset_output = [];
241/// transcoder
242/// .reset(&mut reset_output, 0)
243/// .expect("stateless decoder reset cannot fail");
244/// let mut output = [0_u16; 1];
245/// let progress = transcoder
246/// .transcode(&[0x12, 0x34, 0xab, 0xcd], 0, &mut output, 0)
247/// .expect("decoding cannot fail");
248/// assert_eq!(TranscodeStatus::NeedOutput {
249/// required: NonZeroUsize::MIN,
250/// }, progress.status());
251/// assert_eq!(2, progress.read());
252/// assert_eq!(1, progress.written());
253/// assert_eq!([0x1234], output);
254///
255/// let mut output = [0_u16; 2];
256/// let progress = transcoder
257/// .transcode(&[0x12, 0x34, 0xab], 0, &mut output, 0)
258/// .expect("decoding cannot fail");
259/// assert_eq!(TranscodeStatus::NeedInput {
260/// required: NonZeroUsize::new(2).expect("two is non-zero"),
261/// }, progress.status());
262/// assert_eq!(2, progress.read());
263/// assert_eq!(1, progress.written());
264/// assert_eq!([0x1234, 0], output);
265///
266/// assert!(matches!(
267/// transcoder.transcode(&[0x12], 2, &mut output, 0),
268/// Err(TranscodeDecodeError::Failure(
269/// TranscodeFailure::InvalidInputIndex { .. }
270/// )),
271/// ));
272/// assert!(matches!(
273/// transcoder.transcode(&[0x12], 0, &mut output, 3),
274/// Err(TranscodeDecodeError::Failure(
275/// TranscodeFailure::InvalidOutputIndex { .. }
276/// )),
277/// ));
278/// ```
279///
280/// The trait is intentionally independent from charset concepts. Implementors
281/// use `input_index` and `output_index` as absolute positions in the supplied
282/// slices. Returned progress counters are relative counts from those positions.
283/// For raw codecs this gives a compact API; higher-level workflows can wrap
284/// this trait with their own semantic policies.
285pub trait Transcoder {
286 /// Input unit type accepted by this transcoder.
287 type Input;
288
289 /// Output unit type produced by this transcoder.
290 type Output;
291
292 /// Complete error type produced by this transcoder.
293 type Error: From<TranscodeFailure>;
294
295 /// Returns an upper bound for output units emitted when resetting stream
296 /// state.
297 ///
298 /// Stateful encoders may need a stream-start sequence, such as a byte
299 /// order mark, before the first encoded value. Callers use this bound to
300 /// size the output buffer passed to [`Transcoder::reset`].
301 ///
302 /// The bound may depend on immutable transcoder configuration, but it must
303 /// cover reset output from every reachable transient stream state. It must
304 /// not shrink merely because the current stream has already been reset or
305 /// finished.
306 ///
307 /// # Returns
308 ///
309 /// Returns `Ok(bound)` when the upper bound can be represented as `usize`.
310 /// Stateless transcoders default to `Ok(0)`.
311 ///
312 /// # Errors
313 ///
314 /// Implementations return [`CapacityError::OutputLengthOverflow`] when
315 /// capacity arithmetic overflows. The default never fails.
316 #[inline]
317 fn max_reset_output_len(&self) -> Result<usize, CapacityError> {
318 Ok(0)
319 }
320
321 /// Returns an upper bound for output units produced from `input_len` units
322 /// during the streaming transcode phase.
323 ///
324 /// This bound excludes stream-start output emitted by
325 /// [`Transcoder::reset`] and final output emitted by
326 /// [`Transcoder::finish`]. Callers that need a complete one-shot stream
327 /// bound should use [`Transcoder::max_total_output_len`].
328 ///
329 /// The bound may depend on immutable transcoder configuration and
330 /// `input_len`, but it must cover the streaming output reachable from every
331 /// transient stream state. In particular, it must include the maximum
332 /// retained output that may be emitted before or alongside output derived
333 /// from the supplied input, even when no output is currently retained.
334 ///
335 /// # Parameters
336 ///
337 /// - `input_len`: Number of input units the caller plans to transcode.
338 ///
339 /// # Returns
340 ///
341 /// Returns `Ok(bound)` when the upper bound can be represented as `usize`.
342 ///
343 /// # Errors
344 ///
345 /// Returns [`CapacityError::OutputLengthOverflow`] when capacity arithmetic
346 /// overflows.
347 fn max_transcode_output_len(&self, input_len: usize) -> Result<usize, CapacityError>;
348
349 /// Returns an upper bound for a complete `reset -> transcode -> finish`
350 /// stream.
351 ///
352 /// This is a convenience sum of [`Transcoder::max_reset_output_len`],
353 /// [`Transcoder::max_transcode_output_len`], and
354 /// [`Transcoder::max_finish_output_len`]. Each component is independent of
355 /// transient stream state, so the sum is valid before a full one-shot
356 /// stream regardless of how the previous logical stream ended.
357 ///
358 /// # Parameters
359 ///
360 /// - `input_len`: Number of input units in the complete stream.
361 ///
362 /// # Returns
363 ///
364 /// Returns `Ok(bound)` when the full-stream upper bound can be represented
365 /// as `usize`.
366 ///
367 /// # Errors
368 ///
369 /// Returns [`CapacityError::OutputLengthOverflow`] when a component bound
370 /// or the sum of lifecycle bounds overflows.
371 #[inline]
372 fn max_total_output_len(&self, input_len: usize) -> Result<usize, CapacityError> {
373 let reset = self.max_reset_output_len()?;
374 let transcode = self.max_transcode_output_len(input_len)?;
375 let finish = self.max_finish_output_len()?;
376 sum_output_bounds(reset, transcode, finish)
377 }
378
379 /// Returns an upper bound for output units produced by stream finalization.
380 ///
381 /// The bound may depend on immutable transcoder configuration, but it must
382 /// cover final output from every reachable transient stream state. For
383 /// example, an encoder that can emit one checksum byte must return at least
384 /// `1` before input, while accumulating the checksum, and after finishing a
385 /// previous stream. It must not shrink merely because no finish output is
386 /// currently pending.
387 ///
388 /// # Returns
389 ///
390 /// Returns `Ok(bound)` when the upper bound can be represented as `usize`.
391 /// Stateless transcoders default to `Ok(0)`.
392 ///
393 /// # Errors
394 ///
395 /// Implementations return [`CapacityError::OutputLengthOverflow`] when
396 /// capacity arithmetic overflows. The default never fails.
397 #[inline]
398 fn max_finish_output_len(&self) -> Result<usize, CapacityError> {
399 Ok(0)
400 }
401
402 /// Resets stream state and emits stream-start output into `output`.
403 ///
404 /// This starts a new logical stream while keeping configuration such as
405 /// byte order, charset policy, replacement values, and cryptographic keys.
406 /// Pending input, pending output, and completed-stream state must be
407 /// discarded by stateful implementations. The caller must provide enough
408 /// output capacity for [`Transcoder::max_reset_output_len`].
409 ///
410 /// # Parameters
411 ///
412 /// - `output`: Complete output unit slice visible to the transcoder.
413 /// - `output_index`: Absolute output unit index where writing starts.
414 ///
415 /// # Returns
416 ///
417 /// Returns the number of units written while resetting stream state.
418 /// Stateless transcoders return `0`. Implementations must not return a
419 /// count greater than [`Transcoder::max_reset_output_len`] or the output
420 /// units available from `output_index`.
421 ///
422 /// # Errors
423 ///
424 /// Returns contract errors (`invalid_output_index`, `insufficient_output`)
425 /// when capacity checks fail, or policy errors when reset itself fails.
426 fn reset(&mut self, output: &mut [Self::Output], output_index: usize) -> Result<usize, Self::Error>;
427
428 /// Converts available input units into output units.
429 ///
430 /// This method processes an input segment without closing the logical input
431 /// stream. When the current segment ends in a partial value, the transcoder
432 /// reports [`crate::TranscodeStatus::NeedInput`] without consuming that
433 /// tail. The caller owns input-buffer refill and EOF incomplete-tail
434 /// policy.
435 ///
436 /// Returning [`crate::TranscodeStatus::Complete`] means all input visible
437 /// from `input_index` was consumed. Implementations must not return
438 /// `Complete` after consuming only a prefix of the supplied input; they
439 /// must instead continue processing, report `NeedInput` for an
440 /// incomplete tail, or report `NeedOutput` if output capacity prevents
441 /// progress. This invariant is checked by
442 /// [`crate::TranscodeProgress::validate`].
443 ///
444 /// # Parameters
445 ///
446 /// - `input`: Complete input unit slice visible to the transcoder.
447 /// - `input_index`: Absolute input unit index where conversion starts.
448 /// - `output`: Complete output unit slice visible to the transcoder.
449 /// - `output_index`: Absolute output unit index where writing starts.
450 ///
451 /// # Returns
452 ///
453 /// Returns progress describing how many units were consumed and produced
454 /// and why conversion stopped. Implementations must keep the returned
455 /// counters and status fields consistent with the supplied input and
456 /// output ranges. For `Complete`, `read` must equal `input.len() -
457 /// input_index`. The default one-shot helper rejects incomplete `Complete`
458 /// progress and asserts the remaining progress contract in all builds;
459 /// streaming I/O drivers may convert validation failures before advancing
460 /// unsafe cursors.
461 ///
462 /// # Errors
463 ///
464 /// Returns framework failures for invalid indices, insufficient output,
465 /// incomplete input, and capacity overflow. Returns domain errors for
466 /// semantic conversion failures that the transcoder's policy does not
467 /// absorb.
468 fn transcode(
469 &mut self,
470 input: &[Self::Input],
471 input_index: usize,
472 output: &mut [Self::Output],
473 output_index: usize,
474 ) -> Result<TranscodeProgress, Self::Error>;
475
476 /// Converts source units after the caller has established end of input.
477 ///
478 /// The default preserves ordinary streaming behavior. Implementations that
479 /// can resolve a trailing prefix using EOF-aware format rules should
480 /// override it. If the default still reports
481 /// [`TranscodeStatus::NeedInput`], this method returns
482 /// [`TranscodeFailure::IncompleteInput`] instead. The default validates
483 /// its input and output indices before delegating, then validates returned
484 /// progress before calculating the incomplete-input context. A broken
485 /// implementation therefore returns [`TranscodeFailure::InvalidProgress`]
486 /// rather than causing arithmetic overflow or advancing invalid cursors.
487 ///
488 /// # Parameters
489 ///
490 /// - `input`: Complete input slice, including the final source segment.
491 /// - `input_index`: Absolute position where final decoding starts.
492 /// - `output`: Destination output slice.
493 /// - `output_index`: Absolute output position where writing starts.
494 ///
495 /// # Returns
496 ///
497 /// Validated complete or output-limited progress. The default never returns
498 /// a successful `NeedInput` status at EOF.
499 ///
500 /// # Errors
501 ///
502 /// Returns invalid-index errors before calling `transcode`, forwards its
503 /// errors, and rejects invalid progress or an incomplete final input tail.
504 #[inline]
505 fn transcode_eof(
506 &mut self,
507 input: &[Self::Input],
508 input_index: usize,
509 output: &mut [Self::Output],
510 output_index: usize,
511 ) -> Result<TranscodeProgress, Self::Error> {
512 TranscodeFailure::ensure_transcode_indices(input.len(), input_index, output.len(), output_index)?;
513 let available_input = input.len() - input_index;
514 let available_output = output.len() - output_index;
515 let progress = self.transcode(input, input_index, output, output_index)?;
516 progress
517 .validate(input_index, available_input, output_index, available_output)
518 .map_err(TranscodeFailure::invalid_progress)?;
519 match progress.status() {
520 TranscodeStatus::NeedInput { required } => Err(TranscodeFailure::incomplete_input(
521 input_index + progress.read(),
522 required.get(),
523 available_input - progress.read(),
524 )
525 .into()),
526 _ => Ok(progress),
527 }
528 }
529
530 /// Finishes internally retained output after all input has been supplied.
531 ///
532 /// `transcode` handles ordinary input consumption. `finish` is called once
533 /// after the caller knows no more input remains and has handled any
534 /// incomplete input tail reported by `transcode`. It emits final output
535 /// derived from internal state, such as reset bytes, checksums, digests, or
536 /// trailers. The caller must provide enough output capacity for
537 /// [`Transcoder::max_finish_output_len`].
538 ///
539 /// After `finish` succeeds, the logical stream is closed. Portable callers
540 /// should call [`Transcoder::reset`] with a buffer sized by
541 /// [`Transcoder::max_reset_output_len`] before passing input for another
542 /// logical stream to the same instance.
543 ///
544 /// # Examples
545 ///
546 /// ```rust
547 /// use core::convert::Infallible;
548 /// use core::num::NonZeroUsize;
549 ///
550 /// use qubit_codec::CapacityError;
551 /// use qubit_codec::TranscodeDecodeError;
552 /// use qubit_codec::TranscodeFailure;
553 /// use qubit_codec::TranscodeProgress;
554 /// use qubit_codec::TranscodeStatus;
555 /// use qubit_codec::Transcoder;
556 ///
557 /// #[derive(Default)]
558 /// struct ByteCopy;
559 ///
560 /// impl Transcoder for ByteCopy {
561 /// type Input = u8;
562 /// type Output = u8;
563 /// type Error = TranscodeDecodeError<Infallible>;
564 ///
565 /// fn max_transcode_output_len(&self, input_len: usize) -> Result<usize, CapacityError> {
566 /// Ok(input_len)
567 /// }
568 ///
569 /// fn reset(
570 /// &mut self,
571 /// output: &mut [u8],
572 /// output_index: usize,
573 /// ) -> Result<usize, Self::Error> {
574 /// TranscodeFailure::ensure_output_index(output.len(), output_index)?;
575 /// Ok(0)
576 /// }
577 ///
578 /// fn transcode(
579 /// &mut self,
580 /// input: &[u8],
581 /// input_index: usize,
582 /// output: &mut [u8],
583 /// output_index: usize,
584 /// ) -> Result<TranscodeProgress, Self::Error> {
585 /// let mut read = 0;
586 /// let mut written = 0;
587 /// while input_index + read < input.len() && output_index + written < output.len() {
588 /// output[output_index + written] = input[input_index + read];
589 /// read += 1;
590 /// written += 1;
591 /// }
592 /// if input_index + read == input.len() {
593 /// Ok(TranscodeProgress::complete(read, written))
594 /// } else {
595 /// let status = TranscodeStatus::NeedOutput {
596 /// required: NonZeroUsize::MIN,
597 /// };
598 /// Ok(TranscodeProgress::new(
599 /// status,
600 /// read,
601 /// written,
602 /// ))
603 /// }
604 /// }
605 ///
606 /// fn finish(
607 /// &mut self,
608 /// output: &mut [u8],
609 /// output_index: usize,
610 /// ) -> Result<usize, Self::Error> {
611 /// TranscodeFailure::ensure_output_index(output.len(), output_index)?;
612 /// Ok(0)
613 /// }
614 /// }
615 ///
616 /// let mut transcoder = ByteCopy::default();
617 /// let mut reset_output = [];
618 /// transcoder
619 /// .reset(&mut reset_output, 0)
620 /// .expect("stateless transcoder reset cannot fail");
621 /// let mut output = [1_u8; 1];
622 /// let progress = transcoder
623 /// .transcode(&[7], 0, &mut output, 0)
624 /// .expect("writer consumes one unit");
625 /// assert_eq!(TranscodeStatus::Complete, progress.status());
626 ///
627 /// let written = transcoder
628 /// .finish(&mut output, 1)
629 /// .expect("finish does not emit final state for no-op transcoders");
630 /// assert_eq!(0, written);
631 /// ```
632 ///
633 /// # Parameters
634 ///
635 /// - `output`: Complete output unit slice visible to the transcoder.
636 /// - `output_index`: Absolute output unit index where writing starts.
637 ///
638 /// # Returns
639 ///
640 /// Returns the number of units written during finalization. Stateless
641 /// transcoders return `0`. Implementations must not return a count greater
642 /// than [`Transcoder::max_finish_output_len`] or the output units available
643 /// from `output_index`.
644 ///
645 /// # Errors
646 ///
647 /// Returns contract errors (`invalid_output_index`, `insufficient_output`)
648 /// when capacity checks fail, or policy errors when finish itself
649 /// fails.
650 fn finish(&mut self, output: &mut [Self::Output], output_index: usize) -> Result<usize, Self::Error>;
651
652 /// Runs a complete one-shot `reset -> transcode -> finish` stream.
653 ///
654 /// The `input` slice is treated as complete input at EOF, and output is
655 /// written from the beginning of `output`. Callers that need to operate on
656 /// a range inside a larger buffer should slice the input or output
657 /// before calling this method.
658 ///
659 /// Before invoking any lifecycle method, this method queries the
660 /// state-independent reset, transcode, and finish bounds and requires
661 /// `output` to provide at least the complete upper bound returned by
662 /// [`Transcoder::max_total_output_len`] for `input.len()` units.
663 ///
664 /// # Parameters
665 ///
666 /// - `input`: Complete input unit slice.
667 /// - `output`: Complete output unit slice where the stream starts at index
668 /// `0`.
669 ///
670 /// # Returns
671 ///
672 /// Returns the number of output units written to `output`.
673 ///
674 /// # Errors
675 ///
676 /// Returns framework errors when the output buffer is too small, when
677 /// capacity arithmetic overflows, or when the complete input ends with
678 /// an incomplete value. Capacity-bound overflow and insufficient
679 /// complete-stream capacity are reported before `reset`, `transcode`, or
680 /// `finish` is called, so those preflight failures do not write to
681 /// `output` or advance transient stream state through lifecycle methods.
682 /// Once reset begins, domain errors, incomplete input, runtime
683 /// backpressure caused by an invalid bound implementation, or contract
684 /// violations may leave partial output and advanced state; this method
685 /// does not provide general transactional rollback.
686 ///
687 /// # Panics
688 ///
689 /// Panics when `reset` or `finish` reports writing beyond its declared
690 /// bound or the available output, when an overridden `transcode_eof`
691 /// returns invalid progress, or when a returned write count cannot be
692 /// added to the output cursor. The default `transcode_eof` converts
693 /// invalid `transcode` progress into [`TranscodeFailure::InvalidProgress`].
694 fn transcode_complete_into(
695 &mut self,
696 input: &[Self::Input],
697 output: &mut [Self::Output],
698 ) -> Result<usize, Self::Error> {
699 let reset_required = self.max_reset_output_len().map_err(TranscodeFailure::from)?;
700 let transcode_required = self
701 .max_transcode_output_len(input.len())
702 .map_err(TranscodeFailure::from)?;
703 let finish_required = self.max_finish_output_len().map_err(TranscodeFailure::from)?;
704 let total_required =
705 sum_output_bounds(reset_required, transcode_required, finish_required).map_err(TranscodeFailure::from)?;
706 TranscodeFailure::ensure_output_capacity(output.len(), 0, total_required)?;
707
708 let reset_written = self.reset(output, 0)?;
709 assert!(
710 reset_written <= reset_required,
711 "Transcoder::reset wrote beyond its bound",
712 );
713 assert!(
714 reset_written <= output.len(),
715 "Transcoder::reset wrote beyond available output",
716 );
717 let mut output_cursor = reset_written;
718
719 let progress = self.transcode_eof(input, 0, output, output_cursor)?;
720 let transcode_written = complete_progress_written(progress, input.len(), output_cursor, output.len())?;
721 output_cursor = output_cursor
722 .checked_add(transcode_written)
723 .expect("Transcoder::transcode write count overflowed the output cursor");
724
725 let finish_available = output.len() - output_cursor;
726 let finish_written = self.finish(output, output_cursor)?;
727 assert!(
728 finish_written <= finish_required,
729 "Transcoder::finish wrote beyond its bound",
730 );
731 assert!(
732 finish_written <= finish_available,
733 "Transcoder::finish wrote beyond available output",
734 );
735 output_cursor = output_cursor
736 .checked_add(finish_written)
737 .expect("Transcoder::finish write count overflowed the output cursor");
738 Ok(output_cursor)
739 }
740}