Skip to main content

TranscodeEncodeOutput

Struct TranscodeEncodeOutput 

Source
pub struct TranscodeEncodeOutput<O>
where O: Output, O::Item: Copy + Default,
{ /* private fields */ }
Expand description

Encodes an Output value stream into an Output unit stream.

This type owns only the unit-level qubit_io::BufferedOutput. Callers pass a crate::Codec and error mapper to each encode operation, which lets one buffered output drive different encoders without nesting buffers or storing codec-specific state in the buffer owner.

Self::flush only drains already buffered units. State-aware streaming encoders can use Self::reset, Self::transcode, and Self::finish explicitly.

§Type Parameters

  • O - Wrapped unit output.

§Examples

use std::io::Cursor;

use qubit_codec::TranscodeEncodeOutput;

let output = TranscodeEncodeOutput::with_capacity(Cursor::new(Vec::<u8>::new()), 8);
assert!(output.spare_capacity() >= 8);

Implementations§

Source§

impl<O> TranscodeEncodeOutput<O>
where O: Output, O::Item: Copy + Default,

Source

pub fn new(inner: O) -> Self

Creates an encoder output with the default unit buffer capacity.

§Parameters
  • inner - Unit output written by this adapter.
§Returns

A new buffered encoder output.

Source

pub fn with_capacity(inner: O, capacity: usize) -> Self

Creates an encoder output with a unit buffer of at least capacity.

§Parameters
  • inner - Unit output written by this adapter.
  • capacity - Requested internal unit buffer capacity.
§Returns

A new buffered encoder output.

Source

pub fn try_with_capacity( inner: O, capacity: usize, ) -> CoreResult<Self, TryReserveError>

Creates an encoder output with a unit buffer of at least capacity.

§Parameters
  • inner - Unit output written by this adapter.
  • capacity - Requested internal unit buffer capacity.
§Errors

Returns an allocation error when the requested buffer cannot be allocated.

§Returns

A buffered adapter owning inner on success.

Source

pub const fn inner(&self) -> &O

Returns a shared reference to the wrapped unit output.

Pending units remain in this adapter’s internal buffer and are not visible through the returned output until Self::flush succeeds.

§Returns

A shared reference to the wrapped unit output.

Source

pub fn spare_capacity(&self) -> usize

Returns the available capacity of the spare output buffer.

§Returns

The number of output units that can still be appended without flushing.

Source

pub fn spare_raw_parts_mut(&mut self) -> (&mut [O::Item], usize, usize)

Returns raw spare-buffer parts for the internal output buffer.

§Returns

The full backing storage, the spare start index, and the spare unit count.

Source

pub unsafe fn advance(&mut self, count: usize)

Marks count units from Self::spare_raw_parts_mut as written.

§Parameters
  • count - Initialized units to commit from the spare window.
§Safety

The caller must guarantee that count <= Self::spare_capacity() and that the corresponding units in the returned spare slice have been initialized.

Source

pub fn ensure_spare_capacity(&mut self, count: usize) -> Result<()>

Ensures that at least count spare units are available.

§Parameters
  • count - Number of spare units required.
§Errors

Returns allocation errors mapped to ErrorKind::OutOfMemory, or I/O errors from the wrapped output while delivering pending units.

Source

pub fn into_parts(self) -> (O, BufferedOutputRecovery<O::Item>)

Consumes this adapter without flushing the wrapped output.

This method does not call Self::flush and performs no I/O. Pending units were not reported as written and may be retried. Indeterminate means an inner write panicked and may have produced an external prefix; do not replay it automatically.

§Returns

The wrapped output and pending or indeterminate units.

Source

pub fn flush(&mut self) -> Result<()>

Flushes buffered units without finishing any encoder stream.

§Errors

Returns errors from the wrapped output while flushing pending units.

Source

pub fn write_encoded_with<C, M>( &mut self, codec: &mut C, value: &C::Value, map_error: M, ) -> Result<()>
where C: Codec<Unit = O::Item>, M: FnMut(C::EncodeError) -> Error,

Encodes one codec value into this buffered unit output.

The method grows the persistent internal buffer when necessary, then writes the complete encoded value into its spare window.

§Type Parameters
  • C - Codec producing the wrapped output unit type.
  • M - Mapper from codec errors into I/O errors.
§Parameters
  • codec - Codec used for this single-value encode.
  • value - Value to encode.
  • map_error - Mapper for codec-domain encode errors.
§Errors

Returns I/O errors from the wrapped output, InvalidInput when the codec output bound overflows or the value is outside the codec domain, or the error returned by map_error for codec encode, reset, and finish failures.

§Panics

Panics when the codec violates its declared reset, value-width, or finish bounds, or when encode writes a length different from encode_len in the same reset state.

Source

pub fn reset<E, M, Value>( &mut self, encoder: &mut E, map_error: &mut M, ) -> Result<()>
where E: Transcoder<Input = Value, Output = O::Item>, M: FnMut(E::Error) -> Error,

Runs encoder reset and buffers any stream-prefix units.

This method reserves enough persistent buffer capacity for all reset output before calling encoder. Preparing that space may deliver previously buffered units to the wrapped output and can return an I/O error before encoder.reset runs. This delivery does not call the wrapped output’s flush method.

§Type Parameters
  • E - Transcoder producing the wrapped output unit type.
  • M - Mapper from transcoder errors into I/O errors.
  • Value - Source value type accepted by the transcoder.
§Parameters
  • encoder - Transcoder whose stream prefix is being collected.
  • map_error - Mapper for reset failures.
§Errors

Returns capacity errors, allocation errors, or reset errors mapped by map_error.

§Panics

Panics when encoder writes more than its declared reset bound.

Source

pub fn transcode_step<E, M, Value>( &mut self, encoder: &mut E, map_error: &mut M, input: &[Value], input_index: usize, count: usize, ) -> Result<TranscodeProgress>
where E: TranscodeEncoder<Input = Value, Output = O::Item>, M: FnMut(E::Error) -> Error,

Encodes at most one step of the selected input range.

Unlike Self::transcode, this method does not reserve output space for the entire range and calls the encoder exactly once. The returned progress is relative to this call’s input and output windows. Advance the input index by TranscodeProgress::read; if the status is NeedOutput, provide the requested spare capacity before retrying. Written units have already been committed to this adapter’s pending buffer and must not be advanced again. A zero count validates the range and returns complete progress without delivering pending units or calling the encoder.

§Parameters
  • encoder - Encoder that processes one progress step.
  • map_error - Maps encoder errors to I/O errors.
  • input - Source values.
  • input_index - Start index inside input.
  • count - Number of values available from input_index.
§Returns

Progress for the single encoder call, including consumed input, committed output, and whether more output capacity is needed.

§Errors

Returns invalid input ranges, capacity, encoder, or output errors. An invalid encoder progress report is returned as ErrorKind::InvalidData. An error does not provide general transactional rollback or complete progress. The encoder may already have advanced, but units written by its failing call are not committed to this adapter’s pending output. Do not replay the original input range without an encoder-specific recovery protocol. Earlier pending units retain the wrapped output’s recovery contract; reset starts a new logical stream and does not undo output already delivered.

§Examples
use std::io::Cursor;

use qubit_codec::TranscodeEncodeOutput;
use qubit_codec::TranscodeEncoder;
use qubit_codec::TranscodeStatus;

fn encode<E>(encoder: &mut E, values: &[E::Input]) -> std::io::Result<Vec<u8>>
where
    E: TranscodeEncoder<Output = u8>,
{
    let mut output = TranscodeEncodeOutput::with_capacity(Cursor::new(Vec::new()), 8);
    let mut map_error = |_| std::io::Error::other("encode error");
    output.reset(encoder, &mut map_error)?;
    let mut offset = 0;
    while offset < values.len() {
        let progress = output.transcode_step(
            encoder,
            &mut map_error,
            values,
            offset,
            values.len() - offset,
        )?;
        offset += progress.read();
        if let TranscodeStatus::NeedOutput { required, .. } = progress.status() {
            output.ensure_spare_capacity(required.get())?;
        }
    }
    output.finish(encoder, &mut map_error)?;
    let (cursor, _) = output.into_parts();
    Ok(cursor.into_inner())
}

let mut encoder = CodecTranscodeEncoder::new(ByteCodec);
assert_eq!(encode(&mut encoder, &[1, 2, 3]).unwrap(), vec![1, 2, 3]);
let mut empty_encoder = CodecTranscodeEncoder::new(ByteCodec);
assert_eq!(encode(&mut empty_encoder, &[]).unwrap(), Vec::<u8>::new());
Source

pub fn transcode<E, M, Value>( &mut self, encoder: &mut E, map_error: &mut M, input: &[Value], input_index: usize, count: usize, ) -> Result<usize>
where E: TranscodeEncoder<Input = Value, Output = O::Item>, M: FnMut(E::Error) -> Error,

Encodes values from an indexed input range using a streaming Transcoder.

This streaming path reserves the encoder’s conservative output bound for the whole batch before calling it. Preparing that space may deliver previously buffered units to the wrapped output and can return an I/O error before consuming source values. Split large batches into smaller calls when you need to limit the memory required for one operation.

§Type Parameters
  • E - Encoder producing the wrapped output unit type.
  • M - Mapper from encoder errors into I/O errors.
  • Value - Source value type accepted by the encoder.
§Parameters
  • encoder - Streaming encoder used for this operation.
  • map_error - Function mapping transcode errors into I/O errors.
  • input - Source values.
  • input_index - Start index inside input.
  • count - Maximum number of values to encode.
§Returns

The number of source values consumed.

§Errors

Returns invalid input ranges, capacity, transcode, or output errors. An output-bound contract violation is reported as ErrorKind::InvalidData. An error does not provide general transactional rollback or complete progress. The encoder may already have advanced, while units written by its failing call are not committed to this adapter’s pending output. Do not replay the original input range unless the concrete encoder provides an explicit recovery protocol. Previously committed pending output remains subject to the wrapped output’s recovery contract, and reset starts a new logical stream without undoing output already delivered.

§Examples

A value that only implements Transcoder is not an encoder and cannot be passed to this method.

ⓘ
use std::io::Error;
use std::io::sink;

use qubit_codec::CapacityError;
use qubit_codec::TranscodeEncodeError;
use qubit_codec::TranscodeEncodeOutput;
use qubit_codec::TranscodeProgress;
use qubit_codec::Transcoder;

struct GenericTranscoder;

impl Transcoder for GenericTranscoder {
    type Input = u8;
    type Output = u8;
    type Error = TranscodeEncodeError<(), u8>;

    fn max_transcode_output_len(
        &self,
        input_len: usize,
    ) -> Result<usize, CapacityError> {
        Ok(input_len)
    }

    fn reset(
        &mut self,
        _output: &mut [u8],
        _output_index: usize,
    ) -> Result<usize, Self::Error> {
        Ok(0)
    }

    fn transcode(
        &mut self,
        input: &[u8],
        input_index: usize,
        _output: &mut [u8],
        _output_index: usize,
    ) -> Result<TranscodeProgress, Self::Error> {
        Ok(TranscodeProgress::complete(input.len() - input_index, 0))
    }

    fn finish(
        &mut self,
        _output: &mut [u8],
        _output_index: usize,
    ) -> Result<usize, Self::Error> {
        Ok(0)
    }
}

let mut output = TranscodeEncodeOutput::with_capacity(sink(), 1);
let mut transcoder = GenericTranscoder;
let mut map_error = |_| Error::other("transcode error");
let _ = output.transcode(
    &mut transcoder,
    &mut map_error,
    &[0_u8],
    0,
    1,
);
Source

pub fn finish<E, M, Value>( &mut self, encoder: &mut E, map_error: &mut M, ) -> Result<()>
where E: Transcoder<Input = Value, Output = O::Item>, M: FnMut(E::Error) -> Error,

Finishes the encoder and flushes the wrapped unit output.

This method writes final units directly into the internal spare buffer, growing it when Transcoder::max_finish_output_len exceeds the current capacity.

§Type Parameters
  • E - Transcoder producing the wrapped output unit type.
  • M - Mapper from transcoder errors into I/O errors.
  • Value - Source value type accepted by the transcoder.
§Parameters
  • encoder - Encoder whose final units are being collected.
  • map_error - Function mapping transcode errors into I/O errors.
§Errors

Returns capacity, transcode finalization, or wrapped output flush errors.

§Panics

Panics when the encoder exceeds its declared finish-output bound.

Source

pub fn finish_to_buffer<E, M, Value>( &mut self, encoder: &mut E, map_error: &mut M, ) -> Result<()>
where E: Transcoder<Input = Value, Output = O::Item>, M: FnMut(E::Error) -> Error,

Finishes the encoder while retaining final units in the output buffer.

This method separates encoder finalization from output delivery. It is useful when a caller must record successful finalization before a later flush can fail. Call Self::flush to deliver the retained units.

§Type Parameters
  • E - Transcoder producing the wrapped output unit type.
  • M - Mapper from transcoder errors into I/O errors.
  • Value - Source value type accepted by the transcoder.
§Parameters
  • encoder - Encoder whose final units are being collected.
  • map_error - Function mapping transcode errors into I/O errors.
§Errors

Returns capacity planning, allocation, or transcoder finalization errors. It does not perform output I/O; use Self::finish to deliver the buffered final units and flush the wrapped output.

§Panics

Panics when encoder writes more units than its declared finish bound.

Source§

impl<O> TranscodeEncodeOutput<O>

Source

pub fn seek(&mut self, position: SeekFrom) -> Result<u64>

Flushes pending bytes, then seeks the wrapped byte output.

§Parameters
  • position - Target seek position.
§Returns

The new stream position reported by the wrapped output.

§Errors

Returns flush or seek errors from the wrapped output.

Trait Implementations§

Source§

impl<O> Debug for TranscodeEncodeOutput<O>
where O: Output, O::Item: Copy + Default, BufferedOutput<O>: Debug,

Source§

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

Formats the owned buffer and underlying output for diagnostics.

§Parameters
  • formatter - Destination and formatting options.
§Errors

Returns a formatting error if the destination rejects output.

Source§

impl<O> Seek for TranscodeEncodeOutput<O>

Source§

fn seek(&mut self, position: SeekFrom) -> Result<u64>

Flushes pending bytes, then seeks the wrapped byte output.

§Parameters
  • position - Target position relative to the selected seek origin.
§Returns

The new absolute byte position.

§Errors

Propagates flush or seek errors from the wrapped output.

1.55.0 · Source§

fn rewind(&mut self) -> Result<(), Error>

Rewind to the beginning of a stream. Read more
Source§

fn stream_len(&mut self) -> Result<u64, Error>

🔬This is a nightly-only experimental API. (seek_stream_len)
Returns the length of this stream (in bytes). Read more
1.51.0 · Source§

fn stream_position(&mut self) -> Result<u64, Error>

Returns the current seek position from the start of the stream. Read more
1.80.0 · Source§

fn seek_relative(&mut self, offset: i64) -> Result<(), Error>

Seeks relative to the current position. Read more
Source§

impl<O> Write for TranscodeEncodeOutput<O>
where O: ByteOutput,

Source§

fn write(&mut self, input: &[u8]) -> Result<usize>

Writes raw bytes through the internal buffer without encoding them.

§Parameters
  • input - Bytes to append to the buffered unit output.
§Returns

The number of bytes accepted, which may be shorter than input.

§Errors

Propagates wrapped-output errors when buffer delivery is needed.

Source§

fn write_all(&mut self, input: &[u8]) -> Result<()>

Writes all raw bytes through the internal buffer without encoding them.

§Parameters
  • input - Bytes that must all be accepted before success.
§Errors

Propagates output errors and returns WriteZero if output stops progressing.

§Panics

Panics when the wrapped output reports more bytes than supplied.

Source§

fn flush(&mut self) -> Result<()>

Flushes buffered bytes to the wrapped output without finishing an encoder.

§Errors

Propagates wrapped-output flush errors.

1.36.0 · Source§

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, Error>

Like write, except that it writes from a slice of buffers. Read more
Source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored implementation. Read more
Source§

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

🔬This is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 · Source§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Writes a formatted string into this writer, returning any error encountered. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Write. Read more

Auto Trait Implementations§

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> ByteOutput for T
where T: Output<Item = u8> + ?Sized,

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<W> Output for W
where W: Write + ?Sized,

Source§

type Item = u8

Bytes written by the standard Write implementation.

Source§

unsafe fn write_unchecked( &mut self, input: &[u8], index: usize, count: usize, ) -> Result<usize, Error>

Writes bytes from a caller-validated indexed input range.

§Parameters
  • input: Source byte slice.
  • index: Start offset inside input.
  • count: Maximum number of bytes to write.
§Returns

The number of bytes reported by the standard writer.

§Errors

Returns the error reported by the standard writer.

§Panics

Panics in debug builds if the requested source range does not fit.

§Safety

The caller must ensure that index through index plus count is a valid range inside input without overflowing.

Source§

fn write(&mut self, input: &[<W as Output>::Item]) -> Result<usize, Error>

Writes bytes from the complete input slice.

§Parameters
  • input: Source byte slice.
§Returns

The number of bytes written from input.

§Errors

Returns std::io::ErrorKind::InvalidData if the writer reports more bytes than input contains, or the error reported by the standard writer.

Source§

fn write_vectored(&mut self, buffers: &[&[u8]]) -> Result<usize, Error>

Writes from the buffers in order using the standard writer’s vectored method. Returns InvalidInput if their total length overflows, OutOfMemory if descriptor preparation fails before I/O, or InvalidData if the writer reports more than the total capacity. Short progress and writer errors are returned without retrying or undoing underlying side effects.

Source§

fn flush(&mut self) -> Result<(), Error>

Flushes the standard writer.

§Returns

Returns Ok(()) after the standard writer is flushed.

§Errors

Returns the error reported by the standard writer.

Source§

fn into_std_write(self) -> StdWrite<Self> ⓘ
where Self: Sized + ByteOutput,

Converts this byte output into a standard library writer. Read more
Source§

fn is_buffered(&self) -> bool

Returns whether this output already buffers items internally. Read more
Source§

unsafe fn write_fully_unchecked( &mut self, input: &[Self::Item], index: usize, count: usize, ) -> Result<(), Error>

Writes all items from an indexed input range. Read more
Source§

fn write_fully(&mut self, input: &[Self::Item]) -> Result<(), Error>

Writes all items from the full input slice. Read more
Source§

impl<T> SeekExt for T
where T: Seek + ?Sized,

Source§

fn stream_size(&mut self) -> Result<u64, Error>

Gets the stream size without changing its final position.

§Returns

The stream size in bytes.

§Errors

Returns an error when querying, changing, or restoring the stream position fails.

Source§

impl<S> Seekable for S
where S: Seek + ?Sized,

Source§

type Unit = u8

Bytes used by the standard Seek implementation.

Source§

fn seek_to(&mut self, position: SeekFrom) -> Result<u64, Error>

Seeks using the standard byte offset semantics.

§Parameters
  • position: Standard-library seek origin and byte offset.
§Returns

The resulting byte offset from the start of the stream.

§Errors

Returns the error reported by the standard seeker.

Source§

impl<T> SeekableByteOutput for T
where T: SeekableOutput<Item = u8, Unit = u8> + ?Sized,

Source§

impl<T> SeekableOutput for T
where T: Output + Seekable<Unit = <T as Output>::Item> + ?Sized,

Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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.
Source§

impl<T> WriteExt for T
where T: Write + ?Sized,

Source§

unsafe fn write_unchecked( &mut self, buffer: &[u8], start_index: usize, count: usize, ) -> Result<usize, Error>

Writes bytes from a range of buffer without checking the range bounds in release builds. Read more
Source§

unsafe fn write_all_unchecked( &mut self, buffer: &[u8], start_index: usize, count: usize, ) -> Result<(), Error>

Writes exactly count bytes from a range of buffer without checking the range bounds in release builds. Read more
Source§

impl<T> WriteSeek for T
where T: Write + Seek + ?Sized,

Source§

impl<T> WriteSeekExt for T
where T: Write + Seek + ?Sized,

Source§

fn write_all_at_preserving_position( &mut self, offset: u64, buffer: &[u8], ) -> Result<(), Error>

Writes at an absolute offset and restores the original position.

§Parameters
  • offset: Absolute byte offset to write at.
  • buffer: Bytes to write.
§Returns

Ok(()) after all bytes have been written and the position restored.

§Errors

Returns an error when querying, changing, or restoring the stream position, or when writing fails.