asynchronous_codec/codec/
lines.rs
1use crate::{Decoder, Encoder};
2use bytes::{BufMut, BytesMut};
3use memchr::memchr;
4use std::io::{Error, ErrorKind};
5
6pub struct LinesCodec;
22
23impl Encoder for LinesCodec {
24 type Item = String;
25 type Error = Error;
26
27 fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
28 dst.reserve(item.len());
29 dst.put(item.as_bytes());
30 Ok(())
31 }
32}
33
34impl Decoder for LinesCodec {
35 type Item = String;
36 type Error = Error;
37
38 fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
39 match memchr(b'\n', src) {
40 Some(pos) => {
41 let buf = src.split_to(pos + 1);
42 String::from_utf8(buf.to_vec())
43 .map(Some)
44 .map_err(|e| Error::new(ErrorKind::InvalidData, e))
45 }
46 _ => Ok(None),
47 }
48 }
49}