| 1 |
use crate::{Decoder, Encoder}; |
| 2 |
use bytes::{BufMut, BytesMut}; |
| 3 |
use memchr::memchr; |
| 4 |
use std::io::{Error, ErrorKind}; |
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
pub struct LinesCodec; |
| 22 |
|
| 23 |
impl Encoder for LinesCodec { |
| 24 |
type Item<'a> = 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 |
} |