ewts 1.0.0

Converter between EWTS (Extended Wylie Transliteration Scheme) and Tibetan Unicode symbols (lib)
Documentation
use crate::dict::{Con, ConSpec, Final, PRECOMPOSED, Sign, Sym, Syntax, Vowel};

pub(crate) struct UnicodeToEwtsMaps {
    // Dictionary entries by their Unicode char: Tibetan ones by offset in the block, the rest (a space) in a list.
    signs: Vec<Option<Sign>>,
    other_signs: Vec<(char, Sign)>,
    // ASCII whitespace that occurs in no EWTS token, so it can be written as is. Other ASCII goes in brackets, even
    // if it is in no token: `ewts_to_unicode` would warn about it.
    pub(super) plain_ascii: [bool; 128],
    pub(super) merging_syms: Vec<(Sym, Sym)>,
    // Parts of precomposed chars, by offset in the Tibetan block; empty for other chars.
    decomposed: Vec<Vec<char>>,
}

impl UnicodeToEwtsMaps {
    pub(crate) fn create() -> Self {
        let mut signs = vec![None; TIBETAN_BLOCK_LEN];
        let mut other_signs = Vec::new();
        let mut plain_ascii: [bool; 128] =
            std::array::from_fn(|b| u8::try_from(b).is_ok_and(|b| b.is_ascii_whitespace()));

        let mut add = |unicode: &'static str, kind: Sign| {
            let mut chars = unicode.chars();
            if let (Some(c), None) = (chars.next(), chars.next()) {
                // The first entry wins: `T` over `-t`, `w` over `W` for the base form, etc.
                match tibetan_offset(c) {
                    Some(i) => {
                        signs[i].get_or_insert(kind);
                    }
                    None if other_signs.iter().all(|&(o, _)| o != c) => other_signs.push((c, kind)),
                    None => {}
                }
            }
        };

        for &c in Con::list() {
            let (_, base, sub) = c.get();
            add(base, Sign::Base(c));
            add(sub, Sign::Sub(c));
        }
        for &v in Vowel::list() {
            add(v.get().1, Sign::Vowel(v));
        }
        for &f in Final::list() {
            let unicode = f.get().1;
            add(unicode, Sign::Final(f));
        }
        for &s in Sym::list() {
            let unicode = s.get().1;
            add(unicode, Sign::Sym(s));
        }

        let all_ewts = Con::list()
            .iter()
            .map(|c| c.get().0)
            .chain(Vowel::list().iter().map(|v| v.get().0))
            .chain(Final::list().iter().map(|f| f.get().0))
            .chain(Sym::list().iter().map(|s| s.get().0))
            .chain(ConSpec::list().iter().map(|s| s.get().0));
        let all_ewts: Vec<&str> = all_ewts.collect();
        for ewts in &all_ewts {
            for b in ewts.bytes() {
                plain_ascii[b as usize] = false;
            }
        }
        plain_ascii[Syntax::Escape.get() as usize] = false;
        plain_ascii[Syntax::NonTibetanStart.get() as usize] = false;

        // Symbols that would be read back as one token when written one after another: "/" + "/" is "//".
        let mut merging_syms = Vec::new();
        for &a in Sym::list() {
            // What follows `a` in longer tokens that start with it: "/" for "/" (from "//").
            let rests: Vec<&str> = (all_ewts.iter())
                .filter_map(|t| t.strip_prefix(a.get().0).filter(|rest| !rest.is_empty()))
                .collect();
            if rests.is_empty() {
                continue;
            }
            for &b in Sym::list() {
                let b_ewts = b.get().0;
                if rests
                    .iter()
                    .any(|rest| b_ewts.starts_with(rest) || rest.starts_with(b_ewts))
                {
                    merging_syms.push((a, b));
                }
            }
        }

        let mut decomposed = vec![Vec::new(); TIBETAN_BLOCK_LEN];
        for &(c, parts) in PRECOMPOSED {
            decomposed[(c as usize) - (TIBETAN_FIRST as usize)] =
                parts.iter().flat_map(|p| p.unicode().chars()).collect();
        }

        UnicodeToEwtsMaps {
            signs,
            other_signs,
            plain_ascii,
            merging_syms,
            decomposed,
        }
    }
}

impl UnicodeToEwtsMaps {
    pub(super) fn sign(&self, c: char) -> Option<Sign> {
        match tibetan_offset(c) {
            Some(i) => self.signs[i],
            None => self.other_signs.iter().find(|&&(o, _)| o == c).map(|&(_, s)| s),
        }
    }

    // Precomposed chars are written as their parts: "ྒྷ" (U+0F43) -> "g+ha", "ཱི" (U+0F73) -> "I".
    // So these convert back to the canonically equivalent (decomposed) form, not to the same chars.
    pub(super) fn decompose(&self, c: char) -> Option<&[char]> {
        let offset = (c as usize).checked_sub(TIBETAN_FIRST as usize)?;
        self.decomposed
            .get(offset)
            .filter(|parts| !parts.is_empty())
            .map(Vec::as_slice)
    }
}

const TIBETAN_FIRST: char = '\u{0f00}';
const TIBETAN_LAST: char = '\u{0fff}';
const TIBETAN_BLOCK_LEN: usize = (TIBETAN_LAST as usize) - (TIBETAN_FIRST as usize) + 1;

fn tibetan_offset(c: char) -> Option<usize> {
    is_tibetan_block(c).then(|| (c as usize) - (TIBETAN_FIRST as usize))
}

pub(super) fn is_tibetan_block(c: char) -> bool {
    (TIBETAN_FIRST..=TIBETAN_LAST).contains(&c)
}