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