Skip to main content

TranscodeEncodeEngine

Struct TranscodeEncodeEngine 

Source
pub struct TranscodeEncodeEngine<C, H> { /* private fields */ }
Expand description

Reusable buffered encoding engine for codec-backed encoders.

The engine owns the low-level codec and hook object. It keeps the common buffered encoding loop private: input-index validation, output-capacity checks, input consumption, output progress, and crate::TranscodeStatus reporting.

Use this type to build a streaming encoder over a one-value Codec. The engine does not allocate output. It repeatedly asks hooks to process one input value at the current output cursor. If the hook reports insufficient output, the engine returns crate::TranscodeStatus::NeedOutput without consuming that value; the caller can provide a larger or fresh output buffer and resume with the returned input index.

For the common strict policy that simply wraps codec errors, use crate::CodecTranscodeEncoder. Use TranscodeEncodeEngine directly when the encode policy needs custom planning, replacement, skipped values, or finish-time output.

§Example

use core::{
    convert::Infallible,
    num::NonZeroUsize,
};
use qubit_codec::{
    TranscodeEncodeEngine,
    TranscodeEncodeHooks,
    Codec,
    DecodeFailure,
    CodecEncodeError,
    EncodeContext,
    EncodeOutcome,
    TranscodeStatus,
};

#[derive(Clone, Copy)]
struct ByteCodec;

impl Codec for ByteCodec {
    type Value = u8;
    type Unit = u8;
    type DecodeError = Infallible;
    type EncodeError = Infallible;

    const MIN_UNITS_PER_VALUE: NonZeroUsize = NonZeroUsize::MIN;
    const MAX_UNITS_PER_VALUE: NonZeroUsize = NonZeroUsize::MIN;

    unsafe fn decode(
        &mut self,
        input: &[u8],
        index: usize,
    ) -> Result<(u8, NonZeroUsize), DecodeFailure<Self::DecodeError>> {
        Ok((input[index], NonZeroUsize::MIN))
    }

    unsafe fn encode(
        &mut self,
        value: &u8,
        output: &mut [u8],
        index: usize,
    ) -> Result<NonZeroUsize, Self::EncodeError> {
        output[index] = *value;
        Ok(NonZeroUsize::MIN)
    }
}

struct StrictHooks;

impl TranscodeEncodeHooks<ByteCodec> for StrictHooks {
    type Error = CodecEncodeError<Infallible>;

    fn encode_value(
        &mut self,
        codec: &mut ByteCodec,
        context: EncodeContext<'_, u8, u8>,
    ) -> Result<EncodeOutcome, Self::Error> {
        let required = ByteCodec::MAX_UNITS_PER_VALUE;
        if context.available_output() < required.get() {
            return Ok(EncodeOutcome::need_output(required));
        }
        let (value, input_index, output, output_index) = context.into_parts();
        let written = unsafe { codec.encode(value, output, output_index) }
            .map(NonZeroUsize::get)
            .map_err(|error| CodecEncodeError::encode(error, input_index))?;
        Ok(EncodeOutcome::consumed(written))
    }
}

let mut engine = TranscodeEncodeEngine::new(ByteCodec, StrictHooks);
let input = [1_u8, 2, 3];
let mut output = [0_u8; 2];

let progress = engine.transcode(&input, 0, &mut output, 0)?;
match progress.status() {
    TranscodeStatus::Complete => unreachable!("output is intentionally short"),
    TranscodeStatus::NeedOutput { output_index, .. } => {
        assert_eq!(2, output_index);
        assert_eq!([1, 2], output);
        // Write out `output[..output_index]`, then resume at
        // `progress.read()` with fresh output capacity.
    }
    TranscodeStatus::NeedInput { .. } => unreachable!("encoders do not read encoded input"),
}

§Type Parameters

  • C: Low-level codec used by the engine.
  • H: Policy hook object used by the engine.

Implementations§

Source§

impl<C, H> TranscodeEncodeEngine<C, H>
where C: Codec, H: TranscodeEncodeHooks<C>,

Source

pub fn new(codec: C, hooks: H) -> Self

Creates a buffered encoder engine.

§Parameters
  • codec: Low-level codec used for one-value encoding.
  • hooks: Policy hooks used for planning and writing values.
§Returns

Returns a buffered encoder engine.

§Panics

In debug builds, panics when the supplied codec violates the Codec::MIN_UNITS_PER_VALUE / Codec::MAX_UNITS_PER_VALUE ordering invariant. Release builds skip this check because the invariant is the responsibility of the Codec implementation.

Source

pub fn max_output_len(&self, input_len: usize) -> Result<usize, CapacityError>

Gets a conservative upper bound for output units needed for input_len values.

§Parameters
  • input_len: Number of input values the caller plans to encode.
§Returns

a conservative upper bound for output units, or a capacity error on arithmetic overflow.

Source

pub fn max_reset_output_len(&self) -> Result<usize, CapacityError>

Gets the maximum output units emitted by stream reset.

§Returns

the codec’s reset-output upper bound.

Source

pub fn max_finish_output_len(&self) -> Result<usize, CapacityError>

Gets the maximum output units emitted by finishing codec and hook state.

Returns the sum of Codec::MAX_ENCODE_FLUSH_UNITS and the hook-provided final-output bound. The codec flush portion covers units written by Codec::encode_flush; hook implementations must not include that portion in TranscodeEncodeHooks::max_finish_output_len.

§Returns

the combined codec-flush and hook-finish output bound.

Source

pub fn reset( &mut self, output: &mut [C::Unit], output_index: usize, ) -> Result<usize, TranscodeError<TranscodeEncodeEngineError<<C as Codec>::EncodeError, <H as TranscodeEncodeHooks<C>>::Error>>>

Resets codec encode state, hook-owned state, and stream-start output.

§Parameters
  • output: Complete output unit slice visible to the encoder.
  • output_index: Absolute output unit index where writing starts.
§Returns

Returns the number of reset units written.

§Errors

Returns framework errors when the caller provides invalid or insufficient output capacity. Returns domain errors when codec reset or hook reset handling fails.

Source

pub fn transcode( &mut self, input: &[C::Value], input_index: usize, output: &mut [C::Unit], output_index: usize, ) -> Result<TranscodeProgress, TranscodeError<TranscodeEncodeEngineError<<C as Codec>::EncodeError, <H as TranscodeEncodeHooks<C>>::Error>>>

Encodes values into a caller-provided output buffer.

The engine stops before consuming the next input value when the current output buffer does not satisfy that value’s planned capacity bound.

§Parameters
  • input: Complete input value slice visible to the encoder.
  • input_index: Absolute input value index where encoding starts.
  • output: Complete output unit slice visible to the encoder.
  • output_index: Absolute output unit index where writing starts.
§Returns

Returns progress describing input values consumed, output units written, and why encoding stopped.

§Errors

Returns hook errors when input_index is outside input, when output_index is outside output, or when hook planning or writing rejects a value.

Source

pub fn finish( &mut self, output: &mut [C::Unit], output_index: usize, ) -> Result<usize, TranscodeError<TranscodeEncodeEngineError<<C as Codec>::EncodeError, <H as TranscodeEncodeHooks<C>>::Error>>>

Finishes codec and hook-owned output after EOF.

Finalization first flushes encode-side codec state through Codec::encode_flush, then lets hook implementations finish their own retained state. The caller must provide enough output capacity for TranscodeEncodeEngine::max_finish_output_len, which includes both the codec flush bound and the hook-owned finish bound.

§Parameters
  • output: Complete output unit slice visible to the encoder.
  • output_index: Absolute output unit index where writing starts.
§Returns

Returns the number of units written by finalization.

§Errors

Returns framework errors when the caller provides invalid or insufficient output capacity. Returns domain errors when codec flush or hook finalization fails.

§Panics

Panics when the codec flush writes beyond Codec::MAX_ENCODE_FLUSH_UNITS or when the combined codec and hook finalization writes beyond TranscodeEncodeEngine::max_finish_output_len.

Trait Implementations§

Source§

impl<C: Debug, H: Debug> Debug for TranscodeEncodeEngine<C, H>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<C, H> Default for TranscodeEncodeEngine<C, H>

Source§

fn default() -> Self

Creates a default buffered encoder engine.

§Returns

Returns an engine with default codec and hooks.

Source§

impl<C, H> Transcoder<<C as Codec>::Value, <C as Codec>::Unit> for TranscodeEncodeEngine<C, H>
where C: Codec, H: TranscodeEncodeHooks<C>,

Source§

fn max_output_len(&self, input_len: usize) -> Result<usize, CapacityError>

Returns an upper bound for units produced from input_len values.

Source§

fn max_reset_output_len(&self) -> Result<usize, CapacityError>

Returns the maximum units emitted when resetting stream state.

Source§

fn max_finish_output_len(&self) -> Result<usize, CapacityError>

Returns the maximum units emitted by finishing internal state.

Source§

fn reset( &mut self, output: &mut [C::Unit], output_index: usize, ) -> Result<usize, TranscodeError<Self::Error>>

Resets codec encode state, hook-owned state, and stream-start output.

Source§

fn transcode( &mut self, input: &[C::Value], input_index: usize, output: &mut [C::Unit], output_index: usize, ) -> Result<TranscodeProgress, TranscodeError<Self::Error>>

Encodes input values into caller-provided output units.

Source§

fn finish( &mut self, output: &mut [C::Unit], output_index: usize, ) -> Result<usize, TranscodeError<Self::Error>>

Finishes hook-owned encoder state.

Source§

type Error = TranscodeEncodeEngineError<<C as Codec>::EncodeError, <H as TranscodeEncodeHooks<C>>::Error>

Domain error reported by semantic conversion failures.

Auto Trait Implementations§

§

impl<C, H> Freeze for TranscodeEncodeEngine<C, H>
where C: Freeze, H: Freeze,

§

impl<C, H> RefUnwindSafe for TranscodeEncodeEngine<C, H>

§

impl<C, H> Send for TranscodeEncodeEngine<C, H>
where C: Send, H: Send,

§

impl<C, H> Sync for TranscodeEncodeEngine<C, H>
where C: Sync, H: Sync,

§

impl<C, H> Unpin for TranscodeEncodeEngine<C, H>
where C: Unpin, H: Unpin,

§

impl<C, H> UnsafeUnpin for TranscodeEncodeEngine<C, H>
where C: UnsafeUnpin, H: UnsafeUnpin,

§

impl<C, H> UnwindSafe for TranscodeEncodeEngine<C, H>
where C: UnwindSafe, H: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.