use encoding_rs::{CoderResult, Decoder, DecoderResult, Encoding, REPLACEMENT};
use thiserror::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Charset(&'static Encoding);
impl Charset {
pub const UTF_8: Self = Self(encoding_rs::UTF_8);
pub const UTF_16LE: Self = Self(encoding_rs::UTF_16LE);
pub const UTF_16BE: Self = Self(encoding_rs::UTF_16BE);
#[must_use]
pub fn for_label(label: &str) -> Option<Self> {
let found = Encoding::for_label(label.as_bytes())?;
(found != REPLACEMENT).then_some(Self(found))
}
#[must_use]
pub fn for_bom(bytes: &[u8]) -> Option<(Self, usize)> {
Encoding::for_bom(bytes).map(|(found, len)| (Self(found), len))
}
#[must_use]
pub fn name(self) -> &'static str {
self.0.name()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Malformed {
#[default]
Replace,
Reject,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum TranscodeError {
#[error("bytes that don't decode as {charset}, at byte {offset}")]
Malformed {
charset: &'static str,
offset: u64,
},
#[error("a chunk too long to size its decoded output")]
TooLarge,
#[error("a chunk pushed after the last one")]
Finished,
}
#[derive(Debug)]
pub struct Transcoder {
decoder: Decoder,
malformed: Malformed,
read: u64,
finished: bool,
}
const MIN_ROOM: usize = 16;
impl Transcoder {
#[must_use]
pub fn new(charset: Charset, malformed: Malformed) -> Self {
Self::from_decoder(charset.0.new_decoder_with_bom_removal(), malformed)
}
#[must_use]
pub fn sniffing(malformed: Malformed) -> Self {
Self::from_decoder(encoding_rs::UTF_8.new_decoder(), malformed)
}
const fn from_decoder(decoder: Decoder, malformed: Malformed) -> Self {
Self {
decoder,
malformed,
read: 0,
finished: false,
}
}
#[must_use]
pub fn charset(&self) -> Charset {
Charset(self.decoder.encoding())
}
pub fn push(
&mut self,
chunk: &[u8],
last: bool,
out: &mut Vec<u8>,
) -> Result<(), TranscodeError> {
if self.finished {
return Err(TranscodeError::Finished);
}
let mut rest = chunk;
loop {
let room = match self.malformed {
Malformed::Replace => self.decoder.max_utf8_buffer_length(rest.len()),
Malformed::Reject => self
.decoder
.max_utf8_buffer_length_without_replacement(rest.len()),
}
.ok_or(TranscodeError::TooLarge)?
.max(MIN_ROOM);
let start = out.len();
out.resize(start + room, 0);
let step = self.step(rest, &mut out[start..], last);
out.truncate(start + step.written);
if let Some((bad, after)) = step.bad {
let offset = (self.read + step.read as u64)
.saturating_sub(u64::from(bad) + u64::from(after));
return Err(TranscodeError::Malformed {
charset: self.charset().name(),
offset,
});
}
self.read += step.read as u64;
rest = &rest[step.read..];
if step.done {
self.finished = last;
return Ok(());
}
}
}
fn step(&mut self, src: &[u8], dst: &mut [u8], last: bool) -> Step {
match self.malformed {
Malformed::Replace => {
let (result, read, written, _) = self.decoder.decode_to_utf8(src, dst, last);
Step {
done: result == CoderResult::InputEmpty,
read,
written,
bad: None,
}
}
Malformed::Reject => {
let (result, read, written) = self
.decoder
.decode_to_utf8_without_replacement(src, dst, last);
Step {
done: result == DecoderResult::InputEmpty,
read,
written,
bad: match result {
DecoderResult::Malformed(bad, after) => Some((bad, after)),
_ => None,
},
}
}
}
}
}
struct Step {
done: bool,
read: usize,
written: usize,
bad: Option<(u8, u8)>,
}
#[cfg(test)]
mod tests;