mod scan;
#[cfg(test)]
mod tests;
mod text;
#[cfg(feature = "tokio")]
pub mod tokio;
mod write;
use std::borrow::Cow;
use std::collections::VecDeque;
use std::io::{self, BufRead, Write};
use std::marker::PhantomData;
use crate::parse::StreamConfig;
use text::Text;
pub use scan::{Scanner, Step};
pub use write::{Refused, Writer};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Frame<B> {
Record(B),
Oversize {
len: u64,
head: B,
},
Malformed {
offset: u64,
reason: &'static str,
},
Cut {
len: u64,
},
}
impl<B> Frame<B> {
pub(crate) fn map<C>(self, mut f: impl FnMut(B) -> C) -> Frame<C> {
match self {
Self::Record(bytes) => Frame::Record(f(bytes)),
Self::Oversize { len, head } => Frame::Oversize { len, head: f(head) },
Self::Malformed { offset, reason } => Frame::Malformed { offset, reason },
Self::Cut { len } => Frame::Cut { len },
}
}
}
pub(crate) fn frame_of<'b, B>(
step: &Step,
buf: &'b [u8],
wrap: impl Fn(&'b [u8]) -> B,
) -> Option<Frame<B>> {
match step {
Step::Record { record, .. } => Some(Frame::Record(wrap(&buf[record.clone()]))),
Step::Oversize { len, head, .. } => Some(Frame::Oversize {
len: *len,
head: wrap(&buf[head.clone()]),
}),
Step::Malformed { offset, reason, .. } => Some(Frame::Malformed {
offset: *offset,
reason,
}),
Step::Cut { len } => Some(Frame::Cut { len: *len }),
Step::Skip { .. } | Step::Need => None,
}
}
pub(crate) trait Emit<'a> {
fn borrowed(&mut self, record: &'a [u8]);
fn frame(&mut self, frame: Frame<Cow<'a, [u8]>>);
}
impl<'a, F: FnMut(Frame<Cow<'a, [u8]>>)> Emit<'a> for F {
fn borrowed(&mut self, record: &'a [u8]) {
self(Frame::Record(Cow::Borrowed(record)));
}
fn frame(&mut self, frame: Frame<Cow<'a, [u8]>>) {
self(frame);
}
}
#[derive(Debug, Clone)]
pub(crate) struct Feed {
scanner: Scanner,
held: Vec<u8>,
text: Option<Text>,
decoded: Vec<u8>,
}
struct Owned<'e, 'a, E>(&'e mut E, PhantomData<&'a ()>);
impl<'t, 'a, E: Emit<'a>> Emit<'t> for Owned<'_, 'a, E> {
fn borrowed(&mut self, record: &'t [u8]) {
self.0.frame(Frame::Record(Cow::Owned(record.to_vec())));
}
fn frame(&mut self, frame: Frame<Cow<'t, [u8]>>) {
self.0
.frame(frame.map(|bytes| Cow::Owned(bytes.into_owned())));
}
}
const JOIN_STEP: usize = 256;
impl Feed {
pub(crate) fn new(config: &StreamConfig) -> Self {
Self {
scanner: Scanner::new(config),
held: Vec::new(),
text: Text::new(config.encoding),
decoded: Vec::new(),
}
}
#[cfg(test)]
pub(crate) const fn held(&self) -> usize {
self.held.len()
}
pub(crate) fn fed(&self) -> u64 {
self.scanner.consumed() + u64::try_from(self.held.len()).unwrap_or(u64::MAX)
}
#[inline]
pub(crate) fn push<'a>(&mut self, input: &'a [u8], eof: bool, emit: &mut impl Emit<'a>) {
if self.text.is_some() {
self.push_decoded(input, eof, emit);
} else {
self.push_utf8(input, eof, emit);
}
}
#[inline(never)]
fn push_decoded<'a>(&mut self, input: &[u8], eof: bool, emit: &mut impl Emit<'a>) {
let mut decoded = std::mem::take(&mut self.decoded);
decoded.clear();
if let Some(text) = &mut self.text {
text.push(input, eof, |bytes| decoded.extend_from_slice(bytes));
}
self.push_utf8(&decoded, eof, &mut Owned(emit, PhantomData));
self.decoded = decoded;
}
#[allow(
clippy::inline_always,
reason = "with #[inline] alone the plan driver's UTF-8 path took 1% more instructions"
)]
#[inline(always)]
fn push_utf8<'a>(&mut self, input: &'a [u8], eof: bool, emit: &mut impl Emit<'a>) {
let mut at = 0;
if !self.held.is_empty() {
match self.join(input, eof, emit) {
Some(next) => at = next,
None => return,
}
}
at += self.scanner.each(&input[at..], eof, |frame| match frame {
Frame::Record(record) => emit.borrowed(record),
other => emit.frame(other.map(Cow::Borrowed)),
});
self.held.extend_from_slice(&input[at..]);
}
#[cold]
#[inline(never)]
fn join<'a>(&mut self, input: &'a [u8], eof: bool, emit: &mut impl Emit<'a>) -> Option<usize> {
let base = self.held.len();
let mut front = 0;
let mut taken = 0;
loop {
let last = eof && taken == input.len();
let buf = &self.held[front..];
let step = self.scanner.next(buf, last);
match step {
Step::Need => {
if taken == input.len() {
self.held.drain(..front);
return None;
}
let n = buf.len().max(JOIN_STEP).min(input.len() - taken);
self.held.extend_from_slice(&input[taken..taken + n]);
taken += n;
continue;
}
Step::Cut { len } => {
self.held.clear();
emit.frame(Frame::Cut { len });
return None;
}
_ => {}
}
if let Some(frame) = frame_of(&step, buf, |b| Cow::Owned(b.to_vec())) {
emit.frame(frame);
}
front += step.consume(buf);
if front >= base {
self.held.clear();
return Some(front - base);
}
}
}
}
pub fn frames<R: BufRead>(reader: R, config: &StreamConfig) -> Frames<R> {
Frames {
reader,
feed: Feed::new(config),
ready: VecDeque::new(),
done: false,
}
}
#[derive(Debug)]
pub struct Frames<R> {
reader: R,
feed: Feed,
ready: VecDeque<Frame<Vec<u8>>>,
done: bool,
}
impl<R> Frames<R> {
#[must_use]
pub const fn scanner(&self) -> &Scanner {
&self.feed.scanner
}
pub fn into_inner(self) -> R {
self.reader
}
}
impl<R: BufRead> Iterator for Frames<R> {
type Item = io::Result<Frame<Vec<u8>>>;
fn next(&mut self) -> Option<Self::Item> {
loop {
if let Some(frame) = self.ready.pop_front() {
return Some(Ok(frame));
}
if self.done {
return None;
}
let input = match self.reader.fill_buf() {
Ok(input) => input,
Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
Err(e) => return Some(Err(e)),
};
let n = input.len();
self.done = n == 0;
let ready = &mut self.ready;
self.feed
.push(input, self.done, &mut |frame: Frame<Cow<'_, [u8]>>| {
ready.push_back(frame.map(Cow::into_owned));
});
self.reader.consume(n);
}
}
}
pub fn write_frames<W, I>(mut writer: W, config: &StreamConfig, records: I) -> io::Result<()>
where
W: Write,
I: IntoIterator,
I::Item: AsRef<[u8]>,
{
const BATCH: usize = 64 * 1024;
let mut framer = Writer::new(config);
let mut out = Vec::with_capacity(BATCH);
for record in records {
if let Err(refused) = framer.frame(record.as_ref(), &mut out) {
writer.write_all(&out)?;
return Err(io::Error::new(io::ErrorKind::InvalidInput, refused));
}
if out.len() >= BATCH {
writer.write_all(&out)?;
out.clear();
}
}
framer.finish(&mut out);
writer.write_all(&out)?;
writer.flush()
}