Debian Codegraph @

src/codec/lines.rs

raw symbols SCIP
1 use crate::{Decoder, Encoder};
2 use bytes::{BufMut, BytesMut};
3 use memchr::memchr;
4 use 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 futures_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 /// ```
21 pub struct LinesCodec;
22
23 impl 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
34 impl 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 }