use encoding_rs::{Encoding, UTF_8, UTF_16BE, UTF_16LE};
use crate::parse::StreamEncoding;
#[derive(Debug, Clone)]
pub struct Text {
encoding: Option<&'static Encoding>,
start: bool,
held: Vec<u8>,
}
impl Text {
pub fn new(encoding: StreamEncoding) -> Option<Self> {
let encoding = match encoding {
StreamEncoding::Utf16Le => Some(UTF_16LE),
StreamEncoding::Utf16Be => Some(UTF_16BE),
StreamEncoding::Bom => None,
_ => return None,
};
Some(Self {
encoding,
start: true,
held: Vec::new(),
})
}
pub fn push(&mut self, input: &[u8], eof: bool, mut out: impl FnMut(&[u8])) {
self.held.extend_from_slice(input);
if self.start {
let marks: [&[u8]; 3] = [b"\xef\xbb\xbf", b"\xff\xfe", b"\xfe\xff"];
if !eof && self.held.len() < 3 && marks.iter().any(|m| m.starts_with(&self.held)) {
return;
}
self.start = false;
let named = Encoding::for_bom(&self.held);
let encoding = *self
.encoding
.get_or_insert_with(|| named.map_or(UTF_8, |(e, _)| e));
if let Some((mark, len)) = named
&& mark == encoding
{
self.held.drain(..len);
}
}
let Some(encoding) = self.encoding.filter(|&e| e != UTF_8) else {
out(&self.held);
self.held.clear();
return;
};
let cut = if eof {
self.held.len()
} else {
whole_units(&self.held, encoding == UTF_16BE)
};
let (text, _) = encoding.decode_without_bom_handling(&self.held[..cut]);
out(text.as_bytes());
self.held.drain(..cut);
}
}
fn whole_units(bytes: &[u8], big_endian: bool) -> usize {
let mut cut = bytes.len() & !1;
if let Some(&[a, b]) = bytes.get(cut.saturating_sub(2)..cut) {
let unit = if big_endian {
u16::from_be_bytes([a, b])
} else {
u16::from_le_bytes([a, b])
};
if (0xd800..0xdc00).contains(&unit) {
cut -= 2;
}
}
cut
}