#[derive(Debug, Default)]
pub struct LineDecoder {
buf: Vec<u8>,
}
impl LineDecoder {
pub fn new() -> Self {
Self::default()
}
pub fn push(&mut self, bytes: &[u8]) -> Vec<Vec<u8>> {
self.buf.extend_from_slice(bytes);
let mut lines = Vec::new();
while let Some(index) = self.buf.iter().position(|byte| *byte == b'\n') {
let mut line = self.buf.drain(..=index).collect::<Vec<u8>>();
line.pop(); if line.last() == Some(&b'\r') {
line.pop();
}
lines.push(line);
}
lines
}
pub fn flush(&mut self) -> Option<Vec<u8>> {
if self.buf.is_empty() {
return None;
}
let mut line = std::mem::take(&mut self.buf);
if line.last() == Some(&b'\r') {
line.pop();
}
Some(line)
}
pub fn buffered_len(&self) -> usize {
self.buf.len()
}
pub fn buffered(&self) -> &[u8] {
&self.buf
}
pub fn has_buffered(&self) -> bool {
!self.buf.is_empty()
}
}