| 1 | use crate::{Decoder, Encoder}; |
| 2 | use bytes::{Bytes, BytesMut}; |
| 3 | use std::io::Error; |
| 4 | |
| 5 | /// A simple codec that ships bytes around |
| 6 | /// |
| 7 | /// # Example |
| 8 | /// |
| 9 | /// ``` |
| 10 | /// # futures::executor::block_on(async move { |
| 11 | /// use bytes::Bytes; |
| 12 | /// use futures::{SinkExt, TryStreamExt}; |
| 13 | /// use futures::io::Cursor; |
| 14 | /// use futures_codec::{BytesCodec, Framed}; |
| 15 | /// |
| 16 | /// let mut buf = vec![]; |
| 17 | /// // Cursor implements AsyncRead and AsyncWrite |
| 18 | /// let cur = Cursor::new(&mut buf); |
| 19 | /// let mut framed = Framed::new(cur, BytesCodec); |
| 20 | /// |
| 21 | /// framed.send(Bytes::from("Hello World!")).await?; |
| 22 | /// |
| 23 | /// while let Some(bytes) = framed.try_next().await? { |
| 24 | /// dbg!(bytes); |
| 25 | /// } |
| 26 | /// # Ok::<_, std::io::Error>(()) |
| 27 | /// # }).unwrap(); |
| 28 | /// ``` |
| 29 | pub struct BytesCodec; |
| 30 | |
| 31 | impl Encoder for BytesCodec { |
| 32 | type Item = Bytes; |
| 33 | type Error = Error; |
| 34 | |
| 35 | fn encode(&mut self, src: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> { |
| 36 | dst.extend_from_slice(&src); |
| 37 | Ok(()) |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | impl Decoder for BytesCodec { |
| 42 | type Item = Bytes; |
| 43 | type Error = Error; |
| 44 | |
| 45 | fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { |
| 46 | let len = src.len(); |
| 47 | if len > 0 { |
| 48 | Ok(Some(src.split_to(len).freeze())) |
| 49 | } else { |
| 50 | Ok(None) |
| 51 | } |
| 52 | } |
| 53 | } |