diff --git a/src/codec/bcodec.rs b/src/codec/bcodec.rs new file mode 100644 index 00000000..d7523bf0 --- /dev/null +++ b/src/codec/bcodec.rs @@ -0,0 +1,33 @@ +use std::io; + +use bytes::{Bytes, BytesMut}; +use tokio_codec::{Decoder, Encoder}; + +/// Bytes codec. +/// +/// Reads/Writes chunks of bytes from a stream. +#[derive(Debug, Copy, Clone)] +pub struct BytesCodec; + +impl Encoder for BytesCodec { + type Item = Bytes; + type Error = io::Error; + + fn encode(&mut self, item: Bytes, dst: &mut BytesMut) -> Result<(), Self::Error> { + dst.extend_from_slice(&item[..]); + Ok(()) + } +} + +impl Decoder for BytesCodec { + type Item = BytesMut; + type Error = io::Error; + + fn decode(&mut self, src: &mut BytesMut) -> Result, Self::Error> { + if src.is_empty() { + Ok(None) + } else { + Ok(Some(src.take())) + } + } +} diff --git a/src/codec/mod.rs b/src/codec/mod.rs index 54aa35ff..140e77bb 100644 --- a/src/codec/mod.rs +++ b/src/codec/mod.rs @@ -12,11 +12,13 @@ #![deny(missing_docs, missing_debug_implementations, warnings)] +mod bcodec; mod framed; mod framed2; mod framed_read; mod framed_write; +pub use self::bcodec::BytesCodec; pub use self::framed::{Framed, FramedParts}; pub use self::framed2::{Framed2, FramedParts2}; pub use self::framed_read::FramedRead;