use crate::NetError;
use crate::line::LineDecoder;
#[derive(Debug, Default)]
pub struct NdjsonDecoder {
lines: LineDecoder,
max_line_bytes: Option<usize>,
}
impl NdjsonDecoder {
pub fn new() -> Self {
Self::default()
}
pub fn with_max_line_bytes(max_line_bytes: usize) -> Self {
Self {
lines: LineDecoder::new(),
max_line_bytes: Some(max_line_bytes),
}
}
pub fn push(&mut self, bytes: &[u8]) -> Result<Vec<String>, NetError> {
let mut records = Vec::new();
for line in self.lines.push(bytes) {
self.check_limit(line.len())?;
if line.is_empty() {
continue;
}
records.push(String::from_utf8_lossy(&line).into_owned());
}
self.check_limit(self.lines.buffered_len())?;
Ok(records)
}
pub fn flush(&mut self) -> Option<String> {
let line = self.lines.flush()?;
if line.is_empty() {
return None;
}
Some(String::from_utf8_lossy(&line).into_owned())
}
fn check_limit(&self, len: usize) -> Result<(), NetError> {
if let Some(limit) = self.max_line_bytes
&& len > limit
{
return Err(NetError::OversizeBody(limit));
}
Ok(())
}
}