use super::Flow;
pub(crate) struct Gen<'a> {
text: String,
pending: Vec<u8>,
emitted: usize,
stops: &'a [String],
hold: usize,
}
impl<'a> Gen<'a> {
pub(crate) fn new(stops: &'a [String]) -> Self {
let hold = stops
.iter()
.map(String::len)
.max()
.unwrap_or(0)
.saturating_sub(1);
Self {
text: String::new(),
pending: Vec::new(),
emitted: 0,
stops,
hold,
}
}
pub(crate) fn push(&mut self, bytes: &[u8], on_token: &mut dyn FnMut(&str) -> Flow) -> Flow {
self.pending.extend_from_slice(bytes);
self.decode_pending();
let mut search_from = self.emitted.saturating_sub(self.hold);
while !self.text.is_char_boundary(search_from) {
search_from -= 1;
}
let hit = self
.stops
.iter()
.filter(|s| !s.is_empty())
.filter_map(|s| {
self.text[search_from..]
.find(s.as_str())
.map(|i| search_from + i)
})
.min();
if let Some(at) = hit {
self.text.truncate(at);
self.pending.clear();
self.emit_to(at, on_token);
return Flow::Stop;
}
let mut safe = self.text.len().saturating_sub(self.hold);
while !self.text.is_char_boundary(safe) {
safe -= 1;
}
let flow = self.emit_to(safe, on_token);
if flow == Flow::Stop {
self.text.truncate(self.emitted);
self.pending.clear();
}
flow
}
pub(crate) fn finish(&mut self, on_token: &mut dyn FnMut(&str) -> Flow) -> Flow {
if !self.pending.is_empty() {
self.text.push_str(&String::from_utf8_lossy(&self.pending));
self.pending.clear();
}
let end = self.text.len();
self.emit_to(end, on_token)
}
pub(crate) fn into_text(self) -> String {
self.text
}
fn decode_pending(&mut self) {
loop {
match std::str::from_utf8(&self.pending) {
Ok(s) => {
self.text.push_str(s);
self.pending.clear();
return;
}
Err(e) => {
let valid = e.valid_up_to();
let s = std::str::from_utf8(&self.pending[..valid]).expect("prefix is valid");
self.text.push_str(s);
let Some(bad) = e.error_len() else {
self.pending.drain(..valid);
assert!(
self.pending.len() < 4,
"an incomplete sequence is under 4 bytes"
);
return;
};
self.text.push(char::REPLACEMENT_CHARACTER);
self.pending.drain(..valid + bad);
}
}
}
}
fn emit_to(&mut self, end: usize, on_token: &mut dyn FnMut(&str) -> Flow) -> Flow {
if end <= self.emitted {
return Flow::Continue;
}
let flow = on_token(&self.text[self.emitted..end]);
self.emitted = end;
flow
}
}