async_codec_lite/codec/
lines.rs

1use super::{Decoder, Encoder};
2use bytes::{BufMut, BytesMut};
3use memchr::memchr;
4use std::convert::Infallible;
5
6#[derive(Clone, Debug, Default, PartialEq)]
7pub struct LinesCodec;
8
9impl Encoder for LinesCodec {
10    type Error = Infallible;
11    type Item = String;
12
13    fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
14        dst.reserve(item.len());
15        dst.put(item.as_bytes());
16        Ok(())
17    }
18}
19
20impl Decoder for LinesCodec {
21    type Error = std::string::FromUtf8Error;
22    type Item = String;
23
24    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
25        match memchr(b'\n', src) {
26            Some(pos) => {
27                let buf = src.split_to(pos + 1);
28                String::from_utf8(buf.to_vec()).map(Some)
29            },
30            _ => Ok(None),
31        }
32    }
33}