2019-12-05 08:11:56 +01:00
|
|
|
use bytes::{BufMut, Bytes, BytesMut};
|
2018-10-24 19:43:30 +02:00
|
|
|
use std::io;
|
|
|
|
|
2019-12-05 08:11:56 +01:00
|
|
|
use super::{Decoder, Encoder};
|
2018-10-24 19:43:30 +02:00
|
|
|
|
|
|
|
/// 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> {
|
2019-12-05 08:11:56 +01:00
|
|
|
dst.reserve(item.len());
|
|
|
|
dst.put(item);
|
2018-10-24 19:43:30 +02:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Decoder for BytesCodec {
|
|
|
|
type Item = BytesMut;
|
|
|
|
type Error = io::Error;
|
|
|
|
|
|
|
|
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
|
|
|
|
if src.is_empty() {
|
|
|
|
Ok(None)
|
|
|
|
} else {
|
2019-12-05 08:11:56 +01:00
|
|
|
let len = src.len();
|
|
|
|
Ok(Some(src.split_to(len)))
|
2018-10-24 19:43:30 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|