| 1 |
use std::io; |
| 2 |
|
| 3 |
use bytes::{Buf, Bytes, BytesMut}; |
| 4 |
|
| 5 |
use super::{Decoder, Encoder}; |
| 6 |
|
| 7 |
/// Bytes codec. Reads/writes chunks of bytes from a stream. |
| 8 |
#[derive(Debug, Copy, Clone)] |
| 9 |
pub struct BytesCodec; |
| 10 |
|
| 11 |
impl Encoder<Bytes> for BytesCodec { |
| 12 |
type Error = io::Error; |
| 13 |
|
| 14 |
#[inline] |
| 15 |
fn encode(&mut self, item: Bytes, dst: &mut BytesMut) -> Result<(), Self::Error> { |
| 16 |
dst.extend_from_slice(item.chunk()); |
| 17 |
Ok(()) |
| 18 |
} |
| 19 |
} |
| 20 |
|
| 21 |
impl Decoder for BytesCodec { |
| 22 |
type Item = BytesMut; |
| 23 |
type Error = io::Error; |
| 24 |
|
| 25 |
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { |
| 26 |
if src.is_empty() { |
| 27 |
Ok(None) |
| 28 |
} else { |
| 29 |
Ok(Some(src.split())) |
| 30 |
} |
| 31 |
} |
| 32 |
} |