mod maps;
mod syllable;
#[cfg(test)]
mod tests;
use crate::dict::{NOT_EQUIVALENT, Sign, Syntax, is_apostrophe};
use maps::UnicodeToEwtsMaps;
use maps::is_tibetan_block;
use std::fmt::{self, Write};
use std::sync::LazyLock;
use syllable::push_tsekbar;
fn push_escape(out: &mut String, c: char) {
let _ = write!(
out,
"{}{}{:04x}",
Syntax::Escape.get() as char,
Syntax::EscapeU.get() as char,
c as u32
);
}
static MAPS: LazyLock<UnicodeToEwtsMaps> = LazyLock::new(UnicodeToEwtsMaps::create);
#[inline]
pub(crate) fn convert(src: &str) -> UnicodeToEwts {
convert_with(&MAPS, src)
}
type RawWarnings = Vec<(UnicodeWarningKind, usize)>;
fn convert_with(maps: &UnicodeToEwtsMaps, src: &str) -> UnicodeToEwts {
let mut warnings = RawWarnings::new();
let mut decomposed = Vec::new();
let mut chars = Vec::with_capacity(src.len());
for c in src.chars() {
match maps.decompose(c) {
Some(parts) => {
if NOT_EQUIVALENT.contains(&c) {
warnings.push((UnicodeWarningKind::NotEquivalent, chars.len()));
}
decomposed.push((chars.len(), parts.len()));
chars.extend_from_slice(parts);
}
None => chars.push(c),
}
}
let mut out = String::with_capacity(src.len() * 2);
let mut i = 0;
let mut prev_sym = None;
while i < chars.len() {
let c = chars[i];
let after_sym = prev_sym.take();
let span = |pred: &dyn Fn(char) -> bool| chars[i..].iter().take_while(|&&c| pred(c)).count();
match maps.sign(c) {
Some(Sign::Base(_)) => {
i = push_tsekbar(maps, &chars, i, &mut out, &mut warnings);
}
Some(Sign::Sym(sym)) => {
if after_sym.is_some_and(|prev| maps.merging_syms.contains(&(prev, sym))) {
push_escape(&mut out, c);
} else {
out.push_str(sym.get().0);
prev_sym = Some(sym);
}
i += 1;
}
_ if c.is_ascii() && maps.plain_ascii[c as usize] => {
out.push(c);
i += 1;
}
_ if c.is_ascii() || is_apostrophe(c) => {
let len = span(&|c| {
c == ' '
|| is_apostrophe(c)
|| (c.is_ascii() && !maps.plain_ascii[c as usize] && maps.sign(c).is_none())
});
let run = &chars[i..i + len];
let trailing_spaces = run.iter().rev().take_while(|&&c| c == ' ').count();
out.push(Syntax::NonTibetanStart.get() as char);
for &c in &run[..len - trailing_spaces] {
if Syntax::is_bracket_syntax(c) {
out.push(Syntax::Escape.get() as char);
}
out.push(c);
}
out.push(Syntax::NonTibetanEnd.get() as char);
i += len - trailing_spaces;
}
sign if is_tibetan_block(c) => {
let kind = if sign.is_some() {
UnicodeWarningKind::NoLetter
} else {
UnicodeWarningKind::NoEwts
};
warnings.push((kind, i));
push_escape(&mut out, c);
i += 1;
}
_ => {
let len = span(&|c| !c.is_ascii() && !is_tibetan_block(c) && !is_apostrophe(c));
out.extend(&chars[i..i + len]);
i += len;
}
}
}
let warnings = if warnings.is_empty() {
Vec::new()
} else {
byte_positions(src, warnings, &decomposed)
};
UnicodeToEwts { ewts: out, warnings }
}
fn byte_positions(src: &str, mut raw: RawWarnings, decomposed: &[(usize, usize)]) -> Vec<UnicodeWarning> {
raw.sort_by_key(|&(_, at)| at);
let mut src_chars = src.char_indices().enumerate();
let mut current = (usize::MAX, 0, ' ');
let mut decomposed = decomposed.iter().peekable();
let mut extra = 0;
let mut warnings = Vec::with_capacity(raw.len());
for (kind, at) in raw {
while let Some(&(_, len)) = decomposed.next_if(|&&(start, len)| start + len <= at) {
extra += len - 1;
}
let in_part = decomposed.peek().map_or(0, |&&(start, _)| at.saturating_sub(start));
let n = at - extra - in_part;
while current.0 != n {
let (index, (pos, ch)) = src_chars.next().unwrap();
current = (index, pos, ch);
}
let warning = UnicodeWarning {
kind,
pos: current.1,
ch: current.2,
};
if warnings.last() != Some(&warning) {
warnings.push(warning);
}
}
warnings
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnicodeWarningKind {
SignOrder,
NotEquivalent,
NoLetter,
NoEwts,
}
impl UnicodeWarningKind {
#[must_use]
pub fn is_lossy(self) -> bool {
matches!(self, UnicodeWarningKind::SignOrder | UnicodeWarningKind::NotEquivalent)
}
}
impl fmt::Display for UnicodeWarningKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
UnicodeWarningKind::SignOrder => "signs not in canonical order",
UnicodeWarningKind::NotEquivalent => "not canonically equivalent",
UnicodeWarningKind::NoLetter => "no letter to attach to",
UnicodeWarningKind::NoEwts => "no EWTS",
})
}
}
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnicodeToEwts {
pub ewts: String,
pub warnings: Vec<UnicodeWarning>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UnicodeWarning {
pub kind: UnicodeWarningKind,
pub pos: usize,
pub ch: char,
}
impl fmt::Display for UnicodeWarning {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} at byte {}: {:?}", self.kind, self.pos, self.ch)
}
}