2018-10-24 10:43:30 -07:00
|
|
|
use std::io;
|
|
|
|
|
2021-11-05 00:12:02 +00:00
|
|
|
use bytes::{Buf, Bytes, BytesMut};
|
|
|
|
|
2019-12-05 13:11:56 +06:00
|
|
|
use super::{Decoder, Encoder};
|
2018-10-24 10:43:30 -07:00
|
|
|
|
2021-11-05 00:12:02 +00:00
|
|
|
/// Bytes codec. Reads/writes chunks of bytes from a stream.
|
2018-10-24 10:43:30 -07:00
|
|
|
#[derive(Debug, Copy, Clone)]
|
|
|
|
pub struct BytesCodec;
|
|
|
|
|
2020-07-19 21:44:26 +01:00
|
|
|
impl Encoder<Bytes> for BytesCodec {
|
2018-10-24 10:43:30 -07:00
|
|
|
type Error = io::Error;
|
|
|
|
|
2020-07-19 21:36:51 +00:00
|
|
|
#[inline]
|
2018-10-24 10:43:30 -07:00
|
|
|
fn encode(&mut self, item: Bytes, dst: &mut BytesMut) -> Result<(), Self::Error> {
|
2020-12-28 11:16:37 +08:00
|
|
|
dst.extend_from_slice(item.chunk());
|
2018-10-24 10:43:30 -07: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 {
|
2020-07-20 14:09:24 +00:00
|
|
|
Ok(Some(src.split()))
|
2018-10-24 10:43:30 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|