use std::borrow::Cow;
use std::iter::FusedIterator;
use std::str::Chars;
const MAPPING: &str = include_str!("mapping.txt");
#[repr(C)]
#[derive(Copy, Clone)]
struct Ptr {
chr: [u8; 2],
len: u8,
}
const POINTERS: &[u8] = include_bytes!("pointers.bin");
#[inline(always)]
pub fn deunicode(s: &str) -> String {
deunicode_with_tofu(s, "[?]")
}
#[inline]
pub fn deunicode_with_tofu(s: &str, custom_placeholder: &str) -> String {
deunicode_with_tofu_cow(s, custom_placeholder).into_owned()
}
pub fn deunicode_with_tofu_cow<'input>(s: &'input str, custom_placeholder: &str) -> Cow<'input, str> {
let ascii_len = s.as_bytes().iter().take_while(|&&c| c < 0x7F).count();
if ascii_len >= s.len() { return Cow::Borrowed(s);
}
let mut out = String::with_capacity(s.len() | 15);
let (ascii, rest) = s.as_bytes().split_at(ascii_len);
out.push_str(unsafe { std::str::from_utf8_unchecked(ascii) });
debug_assert!(std::str::from_utf8(rest).is_ok());
let s = unsafe { std::str::from_utf8_unchecked(rest) };
out.extend(s.ascii_chars().map(|ch| ch.unwrap_or(custom_placeholder)));
Cow::Owned(out)
}
#[inline]
pub fn deunicode_char(ch: char) -> Option<&'static str> {
let pointers: &'static [Ptr] = unsafe {
std::slice::from_raw_parts(POINTERS.as_ptr().cast::<Ptr>(), POINTERS.len()/std::mem::size_of::<Ptr>())
};
if let Some(p) = pointers.get(ch as usize) {
if p.len <= 2 {
let chars = &p.chr[..p.len as usize];
debug_assert!(std::str::from_utf8(chars).is_ok());
unsafe {
Some(std::str::from_utf8_unchecked(chars))
}
} else {
let map_pos = (p.chr[0] as u16 | (p.chr[1] as u16) << 8) as usize;
MAPPING.get(map_pos..map_pos + p.len as usize)
}
} else {
None
}
}
pub trait AsciiChars {
fn ascii_chars(&self) -> AsciiCharsIter<'_>;
fn to_ascii_lossy(&self) -> String;
}
impl AsciiChars for String {
#[inline(always)]
fn ascii_chars(&self) -> AsciiCharsIter<'_> {
AsciiCharsIter::new(self)
}
#[inline(always)]
fn to_ascii_lossy(&self) -> String {
deunicode(self)
}
}
impl AsciiChars for str {
#[inline(always)]
fn ascii_chars(&self) -> AsciiCharsIter<'_> {
AsciiCharsIter::new(self)
}
#[inline(always)]
fn to_ascii_lossy(&self) -> String {
deunicode(self)
}
}
pub struct AsciiCharsIter<'a> {
next_char: Option<Option<&'static str>>,
chars: Chars<'a>,
}
impl<'a> AsciiCharsIter<'a> {
#[inline]
pub fn new(unicode_string: &'a str) -> Self {
let mut chars = unicode_string.chars();
Self {
next_char: chars.next().map(deunicode_char),
chars,
}
}
}
impl<'a> FusedIterator for AsciiCharsIter<'a> {}
impl<'a> Iterator for AsciiCharsIter<'a> {
type Item = Option<&'static str>;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.next_char.map(|dch| {
self.next_char = self.chars.next().map(deunicode_char);
dch.map(|dch| {
let bytes = dch.as_bytes();
let ends_with_space = bytes.len() > 1 && bytes.last().cloned() == Some(b' ');
if !ends_with_space {
return dch;
}
let space_or_end_next = self.next_char.map_or(true, |ch| { ch.map_or(false, |ch| ch.as_bytes().get(0).cloned() == Some(b' ')) });
if !space_or_end_next {
dch
} else {
&dch[..dch.len()-1]
}
})
})
}
#[inline]
fn count(self) -> usize {
self.chars.count() + if self.next_char.is_some() {1} else {0}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(self.chars.size_hint().0 + if self.next_char.is_some() {1} else {0}, None)
}
}
#[test]
fn iter_test() {
let chars: Vec<_> = AsciiCharsIter::new("中国").filter_map(|ch| ch).collect();
assert_eq!(&chars, &["Zhong ", "Guo"]);
let chars: Vec<_> = "中国x".ascii_chars().filter_map(|ch| ch).collect();
assert_eq!(&chars, &["Zhong ", "Guo ", "x"]);
let chars: Vec<_> = "中 国".ascii_chars().filter_map(|ch| ch).collect();
assert_eq!(&chars, &["Zhong", " ", "Guo"]);
}