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§
Sourcefn encode_with_context(
&self,
writer: &mut impl Write,
context: &Context,
) -> Result<(), CodecError>
fn encode_with_context( &self, writer: &mut impl Write, context: &Context, ) -> Result<(), CodecError>
Encodes this value using context supplied by its enclosing structure.
Sourcefn decode_with_context(
reader: &mut impl Read,
context: &Context,
) -> Result<Self, CodecError>where
Self: Sized,
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§
impl ContextualCodec for ByteArray
impl<T> ContextualCodec for Array<T>where
T: ContextualCodec,
impl<T> ContextualCodec for Optional<T>where
T: ContextualCodec,
impl<T> ContextualCodec for Twhere
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.