pub struct Codec<D: StreamDeserializer, S: StreamSerializer, T> { /* private fields */ }codec only.Expand description
Implements the codec traits of tokio-util.
The codec decodes values of type T with a StreamDeserializer and
encodes values with a StreamSerializer (for instance
deser_json::StreamDeserializer and deser_json::Serializer). This
makes it usable with FramedRead, FramedWrite and Framed:
use futures_util::{SinkExt, StreamExt};
use deser_json::{DeserializerConfig, Serializer, SerializerConfig, StreamDeserializer, Trailing};
use deser_tokio::Codec;
use tokio_util::codec::Framed;
const READ_LINES: DeserializerConfig =
DeserializerConfig::builder().trailing(Trailing::Newline).build();
const WRITE_LINES: SerializerConfig =
SerializerConfig::builder().trailing(Trailing::Newline).build();
let (client, server) = tokio::io::duplex(1024);
let codec = || {
Codec::<_, _, Vec<u32>>::new(
StreamDeserializer::with_config(READ_LINES),
Serializer::with_config(WRITE_LINES),
)
};
let mut client = Framed::new(client, codec());
let mut server = Framed::new(server, codec());
client.send(vec![1, 2]).await.unwrap();
assert_eq!(server.next().await.unwrap().unwrap(), [1, 2]);The data read by the framed reader is moved into the codec’s buffer, so
errors refer to positions in the stream. If the format supports it
(see StreamDeserializer::supports_partial), values are deserialized
while their input arrives.
Implementations§
Source§impl<D: StreamDeserializer, S: StreamSerializer, T> Codec<D, S, T>
impl<D: StreamDeserializer, S: StreamSerializer, T> Codec<D, S, T>
Sourcepub fn deserializer(&self) -> &D
pub fn deserializer(&self) -> &D
Returns the stream deserializer.
Sourcepub fn serializer(&self) -> &S
pub fn serializer(&self) -> &S
Returns the stream serializer.
Sourcepub fn set_context(&mut self, context: Context)
pub fn set_context(&mut self, context: Context)
Sets the context the values are deserialized and serialized in.
This replaces the context of the stream deserializer (see
StreamDeserializer::context).
The values of the context are the defaults of the extension values
of the state (see Context).