use super::{
filter::{CodepointFilter, FilterAction, FilterIterator},
page_table::{decode_page_table, page_table_lookup, replace_scan},
simd::skip_ascii_simd,
utf8::decode_utf8_raw,
};
pub(crate) struct VariantNormFilter<'a> {
l1: &'a [u16],
l2: &'a [u32],
}
impl<'a> CodepointFilter<'a> for VariantNormFilter<'a> {
#[inline(always)]
fn filter_ascii(&self, _byte: u8) -> FilterAction<'a> {
FilterAction::Keep
}
#[inline(always)]
fn filter_codepoint(&self, cp: u32) -> FilterAction<'a> {
if let Some(mapped_cp) = page_table_lookup(cp, self.l1, self.l2)
&& mapped_cp != cp
{
FilterAction::ReplaceCodepoint(mapped_cp)
} else {
FilterAction::Keep
}
}
}
struct VariantNormFindIter<'a> {
l1: &'a [u16],
l2: &'a [u32],
text: &'a str,
byte_offset: usize,
}
impl<'a> Iterator for VariantNormFindIter<'a> {
type Item = (usize, usize, char);
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let bytes = self.text.as_bytes();
let len = bytes.len();
loop {
self.byte_offset = skip_ascii_simd(bytes, self.byte_offset);
if self.byte_offset >= len {
return None;
}
let start = self.byte_offset;
let (cp, char_len) = unsafe { decode_utf8_raw(bytes, start) };
self.byte_offset += char_len;
if let Some(mapped_cp) = page_table_lookup(cp, self.l1, self.l2)
&& mapped_cp != cp
{
let mapped = unsafe {
core::hint::assert_unchecked(mapped_cp <= 0x10FFFF);
char::from_u32_unchecked(mapped_cp)
};
return Some((start, self.byte_offset, mapped));
}
}
}
}
#[derive(Clone)]
pub(crate) struct VariantNormMatcher {
l1: Box<[u16]>,
l2: Box<[u32]>,
}
impl VariantNormMatcher {
#[inline(always)]
fn iter<'a>(&'a self, text: &'a str) -> VariantNormFindIter<'a> {
VariantNormFindIter {
l1: &self.l1,
l2: &self.l2,
text,
byte_offset: 0,
}
}
pub(crate) fn replace(&self, text: &str) -> Option<String> {
replace_scan(text, self.iter(text))
}
#[inline(always)]
pub(crate) fn filter_bytes<'a>(
&'a self,
text: &'a str,
) -> FilterIterator<'a, VariantNormFilter<'a>> {
FilterIterator::new(
text,
VariantNormFilter {
l1: &self.l1,
l2: &self.l2,
},
)
}
pub(crate) fn new(l1: &'static [u8], l2: &'static [u8]) -> Self {
let (l1, l2) = decode_page_table(l1, l2);
Self { l1, l2 }
}
}