dencode/codec/
lines.rs

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