pub trait Codec: Send + Sync {
// Required methods
fn encode<T: Serialize>(&self, value: &T) -> Result<BytesMut, CodecError>;
fn decode<T: DeserializeOwned>(&self, bytes: &[u8]) -> Result<T, CodecError>;
}Expand description
A serializer that converts Rust values to and from bytes.
Implementations are stateless and cheap to clone. The trait uses generic methods rather
than associated types so a single codec instance can handle any Serialize /
DeserializeOwned value. This means dyn Codec is not object-safe; use generics or
boxed concrete codecs at the call site.
§Examples
use ruststream::codec::{Codec, JsonCodec};
#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Order { id: u32, total: f64 }
let codec = JsonCodec;
let bytes = codec.encode(&Order { id: 1, total: 9.99 })?;
let back: Order = codec.decode(&bytes)?;
assert_eq!(back, Order { id: 1, total: 9.99 });Required Methods§
Sourcefn encode<T: Serialize>(&self, value: &T) -> Result<BytesMut, CodecError>
fn encode<T: Serialize>(&self, value: &T) -> Result<BytesMut, CodecError>
Encodes value into a mutable byte buffer.
Returning BytesMut lets the encoded buffer move into the publish pipeline (an
Outgoing payload) without a copy, while still allowing
publish middleware to mutate it in place.
§Errors
Returns CodecError::Encode when the underlying serializer fails.
Sourcefn decode<T: DeserializeOwned>(&self, bytes: &[u8]) -> Result<T, CodecError>
fn decode<T: DeserializeOwned>(&self, bytes: &[u8]) -> Result<T, CodecError>
Decodes bytes into a Rust value of type T.
§Errors
Returns CodecError::Decode when the underlying deserializer fails.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".