asynchronous_codec/codec/
lines.rs

1use crate::{Decoder, Encoder};
2use bytes::{BufMut, BytesMut};
3use memchr::memchr;
4use std::io::{Error, ErrorKind};
5
6/// A simple `Codec` implementation that splits up data into lines.
7///
8/// ```rust
9/// # futures::executor::block_on(async move {
10/// use futures::stream::TryStreamExt; // for lines.try_next()
11/// use asynchronous_codec::{FramedRead, LinesCodec};
12///
13/// let input = "hello\nworld\nthis\nis\ndog\n".as_bytes();
14/// let mut lines = FramedRead::new(input, LinesCodec);
15/// while let Some(line) = lines.try_next().await? {
16///     println!("{}", line);
17/// }
18/// # Ok::<_, std::io::Error>(())
19/// # }).unwrap();
20/// ```
21pub 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}