#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PushResult {
NeedMore,
Character(char),
Invalid,
InvalidAndReprocess,
}
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct Utf8Decoder {
bytes: [u8; 4],
len: u8,
expected: u8,
}
impl Utf8Decoder {
pub(crate) const fn new() -> Self {
Self {
bytes: [0; 4],
len: 0,
expected: 0,
}
}
pub(crate) const fn is_pending(self) -> bool {
self.expected != 0
}
pub(crate) fn reset(&mut self) {
self.len = 0;
self.expected = 0;
}
pub(crate) fn push(&mut self, byte: u8) -> PushResult {
if self.expected == 0 {
let expected = match byte {
0xC2..=0xDF => 2,
0xE0..=0xEF => 3,
0xF0..=0xF4 => 4,
_ => return PushResult::Invalid,
};
self.bytes[0] = byte;
self.len = 1;
self.expected = expected;
return PushResult::NeedMore;
}
if !(0x80..=0xBF).contains(&byte) {
self.reset();
return PushResult::InvalidAndReprocess;
}
self.bytes[usize::from(self.len)] = byte;
self.len += 1;
if self.len < self.expected {
return PushResult::NeedMore;
}
let result = core::str::from_utf8(&self.bytes[..usize::from(self.len)])
.ok()
.and_then(|text| text.chars().next());
self.reset();
result.map_or(PushResult::Invalid, PushResult::Character)
}
pub(crate) fn finish(&mut self) -> bool {
let incomplete = self.is_pending();
self.reset();
incomplete
}
}