use memchr::memchr;
use thiserror::Error;
use crate::parse::{CarriageReturns, RS, Scan, ScanStep, StreamConfig, StreamSplit};
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum Refused {
#[error("an empty record")]
Empty,
#[error("a record holding its delimiter")]
Delimiter,
#[error("an LF line ending in a carriage return")]
CarriageReturn,
#[error("an octet-counted record that doesn't start with `<`")]
NotCounted,
#[error("a record that isn't one JSON value")]
NotOneValue,
#[error("a first record starting with a byte order mark")]
ByteOrderMark,
#[error("a record of {len} bytes is over max_bytes {max}")]
TooLong {
len: usize,
max: usize,
},
}
#[derive(Debug, Clone)]
pub struct Writer {
split: StreamSplit,
max: usize,
strip: bool,
bom: bool,
started: bool,
}
pub(super) struct Around {
head: [u8; 24],
head_len: usize,
pub(super) tail: &'static [u8],
}
impl Around {
pub(super) fn head(&self) -> &[u8] {
&self.head[..self.head_len]
}
}
impl Writer {
#[must_use]
pub fn new(config: &StreamConfig) -> Self {
Self {
split: config.split,
max: config.max_bytes,
strip: config.carriage_returns == CarriageReturns::Strip,
bom: config.strip_bom,
started: false,
}
}
pub fn frame(&mut self, record: &[u8], out: &mut Vec<u8>) -> Result<(), Refused> {
let around = self.around(record)?;
out.reserve(around.head_len + record.len() + around.tail.len());
out.extend_from_slice(around.head());
out.extend_from_slice(record);
out.extend_from_slice(around.tail);
Ok(())
}
pub fn finish(&mut self, out: &mut Vec<u8>) {
out.extend_from_slice(self.closing());
}
pub(super) const fn closing(&mut self) -> &'static [u8] {
let opened = self.started;
self.started = false;
if !matches!(self.split, StreamSplit::JsonArray) {
return b"";
}
if opened { b"]" } else { b"[]" }
}
pub(super) fn around(&mut self, record: &[u8]) -> Result<Around, Refused> {
if record.is_empty() {
return Err(Refused::Empty);
}
if record.len() > self.max {
return Err(Refused::TooLong {
len: record.len(),
max: self.max,
});
}
if self.bom && !self.started && record.starts_with(b"\xef\xbb\xbf") {
return Err(Refused::ByteOrderMark);
}
let mut around = Around {
head: [0; 24],
head_len: 0,
tail: b"",
};
match self.split {
StreamSplit::Lf => {
if memchr(b'\n', record).is_some() {
return Err(Refused::Delimiter);
}
if self.strip && record.last() == Some(&b'\r') {
return Err(Refused::CarriageReturn);
}
around.tail = b"\n";
}
StreamSplit::Nul => {
if memchr(0, record).is_some() {
return Err(Refused::Delimiter);
}
around.tail = b"\0";
}
StreamSplit::OctetCounted => {
if record[0] != b'<' {
return Err(Refused::NotCounted);
}
let mut n = record.len();
let mut digits = [0_u8; 20];
let mut at = digits.len();
loop {
at -= 1;
digits[at] = b"0123456789"[n % 10];
n /= 10;
if n == 0 {
break;
}
}
let count = &digits[at..];
around.head[..count.len()].copy_from_slice(count);
around.head[count.len()] = b' ';
around.head_len = count.len() + 1;
}
StreamSplit::JsonConcat => {
one_value(record, false)?;
around.tail = b"\n";
}
StreamSplit::JsonSeq => {
one_value(record, true)?;
around.head[0] = RS;
around.head_len = 1;
around.tail = b"\n";
}
StreamSplit::JsonArray => {
one_value(record, false)?;
around.head[0] = if self.started { b',' } else { b'[' };
around.head_len = 1;
}
}
self.started = true;
Ok(around)
}
}
fn one_value(record: &[u8], seq: bool) -> Result<(), Refused> {
let mut scan = record
.first()
.and_then(|&b| Scan::open(b))
.ok_or(Refused::NotOneValue)?;
let scalar = scan.scalar();
match scan.run(record, 1, seq) {
ScanStep::End(end) if end == record.len() => Ok(()),
ScanStep::More if scalar => Ok(()),
_ => Err(Refused::NotOneValue),
}
}