Skip to main content

ContextualCodec

Trait ContextualCodec 

Source
pub trait ContextualCodec {
    // Required methods
    fn encode_with_context(
        &self,
        writer: &mut impl Write,
        context: &Context,
    ) -> Result<(), CodecError>;
    fn decode_with_context(
        reader: &mut impl Read,
        context: &Context,
    ) -> Result<Self, CodecError>
       where Self: Sized;
}
Expand description

Encodes and decodes a value whose wire representation depends on external protocol context.

Unlike TypeCodec, this trait receives a Context supplied by the enclosing packet or data structure. The context itself is not written to or read from the wire. For an optional field, the caller must determine whether the field is present from the surrounding protocol data.

§Examples

A generic helper can encode any contextual value using context supplied by its enclosing packet:

use mcproto_codec::error::CodecError;
use mcproto_types::{ContextualCodec, contextual::Context};

fn encode_contextual<T: ContextualCodec>(
    value: &T,
    context: &Context,
) -> Result<Vec<u8>, CodecError> {
    let mut encoded = Vec::new();
    value.encode_with_context(&mut encoded, context)?;
    Ok(encoded)
}

Required Methods§

Source

fn encode_with_context( &self, writer: &mut impl Write, context: &Context, ) -> Result<(), CodecError>

Encodes this value using context supplied by its enclosing structure.

Source

fn decode_with_context( reader: &mut impl Read, context: &Context, ) -> Result<Self, CodecError>
where Self: Sized,

Decodes this value using context supplied by its enclosing structure.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§

Source§

impl ContextualCodec for ByteArray

Source§

impl<T> ContextualCodec for Array<T>
where T: ContextualCodec,

Source§

impl<T> ContextualCodec for Optional<T>
where T: ContextualCodec,

Source§

impl<T> ContextualCodec for T
where T: TypeCodec,

Adapts a context-independent TypeCodec to ContextualCodec.

The supplied context is ignored because the value’s wire representation is already complete without external information. Context-sensitive types should implement ContextualCodec directly instead of TypeCodec.