ewts 1.0.0

Converter between EWTS (Extended Wylie Transliteration Scheme) and Tibetan Unicode symbols (lib)
Documentation
use super::*;
use std::fmt::Write;

pub(crate) static TST_DATA: &[(&str, &str)] = &[
    // Standart Tibetan Stacks
    (
        r"
rka rga rnga rja rnya rta rda rna rba rma rtsa rdza 
lka lga lnga lca lja lta lda lpa lba lha 
ska sga snga snya sta sda sna spa sba sma stsa 
kwa khwa gwa cwa nywa twa dwa tswa tshwa zhwa zwa 
rwa shwa swa hwa 
kya khya gya pya phya bya mya 
kra khra gra tra thra dra pra phra bra mra shra sra hra 
kla gla bla zla rla sla 
rkya rgya rmya rgwa rtswa 
skya sgya spya sbya smya 
skra sgra snra spra sbra smra 
grwa drwa phywa 
",
        r"
རྐ་རྒ་རྔ་རྗ་རྙ་རྟ་རྡ་རྣ་རྦ་རྨ་རྩ་རྫ་
ལྐ་ལྒ་ལྔ་ལྕ་ལྗ་ལྟ་ལྡ་ལྤ་ལྦ་ལྷ་
སྐ་སྒ་སྔ་སྙ་སྟ་སྡ་སྣ་སྤ་སྦ་སྨ་སྩ་
ཀྭ་ཁྭ་གྭ་ཅྭ་ཉྭ་ཏྭ་དྭ་ཙྭ་ཚྭ་ཞྭ་ཟྭ་
རྭ་ཤྭ་སྭ་ཧྭ་
ཀྱ་ཁྱ་གྱ་པྱ་ཕྱ་བྱ་མྱ་
ཀྲ་ཁྲ་གྲ་ཏྲ་ཐྲ་དྲ་པྲ་ཕྲ་བྲ་མྲ་ཤྲ་སྲ་ཧྲ་
ཀླ་གླ་བླ་ཟླ་རླ་སླ་
རྐྱ་རྒྱ་རྨྱ་རྒྭ་རྩྭ་
སྐྱ་སྒྱ་སྤྱ་སྦྱ་སྨྱ་
སྐྲ་སྒྲ་སྣྲ་སྤྲ་སྦྲ་སྨྲ་
གྲྭ་དྲྭ་ཕྱྭ་
",
    ),
    //
    ("", ""),
    ("rkw rk+w ", "རཀྭ་རྐྭ་"),
    ("rgyi", "རྒྱི"),
    (
        "oM aHhU~M` badz+ra gu ru pad+ma sid+d+hi hU~M`:",
        "ཨོཾ་ཨཿཧཱུྂ་བཛྲ་གུ་རུ་པདྨ་སིདྡྷི་ཧཱུྂ༔",
    ),
    ("va fi &ung", "བ༹་ཕི༹་྅ུང"),
    ("sha ai gaang angs ", "ཤ་ཨཻ་གཨང་ཨངས་"),
    (
        "@#/_/sangs rgyas chos dang tshogs kyi mchog rnams la/_/byang chub bar du bdag ni skyabs su mchi/_/bdag gyis spyin sogs bgyis pa'i bsod nams kyis/_/'gro la phan phyir sangs rgyas 'grub par shog_!",
        "༄༅། །སངས་རྒྱས་ཆོས་དང་ཚོགས་ཀྱི་མཆོག་རྣམས་ལ། །བྱང་ཆུབ་བར་དུ་བདག་ནི་སྐྱབས་སུ་མཆི། །བདག་གྱིས་སྤྱིན་སོགས་བགྱིས་པའི་བསོད་ནམས་ཀྱིས། །འགྲོ་ལ་ཕན་ཕྱིར་སངས་རྒྱས་འགྲུབ་པར་ཤོག ༈",
    ),
];

#[test]
fn ewts_to_unicode_converting_test() {
    for td in TST_DATA {
        assert_eq!(ewts_to_unicode(td.0).unicode, td.1);
    }
}

#[test]
fn etu_prefixes() {
    let data = [
        ("brgyad brjod ", "བརྒྱད་བརྗོད་"),
        ("g.yon l+ha g.yon ", "གཡོན་ལྷ་གཡོན་"),
        ("g.yeng gyeng g.yul ", "གཡེང་གྱེང་གཡུལ་"),
        (
            "bdag gis ang ga'i rgyal po dang lhan cig g.yul ngor g.yul sprad par bgyi'o/",
            "བདག་གིས་ཨང་གའི་རྒྱལ་པོ་དང་ལྷན་ཅིག་གཡུལ་ངོར་གཡུལ་སྤྲད་པར་བགྱིའོ།",
        ),
    ];

    for td in &data {
        assert_eq!(ewts_to_unicode(td.0).unicode, td.1);
    }
}

#[test]
fn etu_non_tibetan_test() {
    let data = [
        ("k [alphabet]_h ", "ཀ་alphabet ཧ་"),
        ("[u]", "u"),
        ("_[u]rjes[U]_[\\\\]_", " uརྗེསU \\ "),
        ("\\u0f40", "ཀ"),
        ("\\U00000f40", "ཀ"),
        ("phyogs \\1\\0 bcu ", "ཕྱོགས་10་བཅུ་"),
        ("\\u0f", "\\ཨུ༠ཕ༹"),
    ];

    for td in &data {
        assert_eq!(ewts_to_unicode(td.0).unicode, td.1);
    }
}

#[test]
fn etu_tsa_phru_after_vowel() {
    let data = [
        ("fi", "\u{f55}\u{f72}\u{f39}"),
        ("vu", "\u{f56}\u{f74}\u{f39}"),
        ("fA", "\u{f55}\u{f71}\u{f39}"),
        ("fe fo ", "\u{f55}\u{f7a}\u{f39}\u{f0b}\u{f55}\u{f7c}\u{f39}\u{f0b}"),
        ("fiM", "\u{f55}\u{f72}\u{f39}\u{f7e}"),
        ("fa f+ya", "\u{f55}\u{f39}\u{f0b}\u{f55}\u{f39}\u{fb1}"),
        ("ka^ bi", "\u{f40}\u{f39}\u{f0b}\u{f56}\u{f72}"),
    ];

    for td in &data {
        assert_eq!(ewts_to_unicode(td.0).unicode, td.1, "input: {:?}", td.0);
    }
}

#[test]
fn etu_non_ascii_passthrough() {
    let data = [
        ("ka привет", "ཀ་привет"),
        ("ka ཀ་ཁ kha", "ཀ་ཀ་ཁ་ཁ"),
        ("kaж", "ཀж"),
        ("жka", "жཀ"),
        ("ж ka", "ж་ཀ"),
        ("ka \\ж", "ཀ་ж"),
        ("\\😀ka", "😀ཀ"),
        ("[привет] ka", "привет་ཀ"),
        ("ka é", "ཀ་é"),
    ];

    for td in &data {
        assert_eq!(ewts_to_unicode(td.0).unicode, td.1, "input: {:?}", td.0);
    }
}

// EWTS rule 9: brackets nest, and escapes work inside them. A "+" not between letters or vowels is kept as is.
#[test]
fn etu_brackets_and_plus() {
    let data = [
        ("[a [b] c]d", "a [b] cད"),
        ("[a [b [c]] d]e", "a [b [c]] dཨེ"),
        ("[x]y]z", "xཡ]ཟ"),
        ("[\\u0f40]", "ཀ"),
        ("[a\\u0f40b]", "aཀb"),
        ("[\\]]", "]"),
        ("[\\[]", "["),
        ("[\\\\]", "\\"),
        ("[\\u0fzz]", "\\u0fzz"),
        ("[\\u+f40]", "\\u+f40"),
        ("+a", "+ཨ"),
        ("ka +ta", "ཀ་+ཏ"),
        ("kM+ta", "ཀཾ+ཏ"),
        ("+", "+"),
        ("k++ta", "ཀ++ཏ"),
        ("k+", "ཀ+"),
        ("ka+", "ཀ+"),
        ("k+ ka", "ཀ+་ཀ"),
        ("k+.ta", "ཀ+ཏ"),
        ("ka+ta", "ཀྟ"),
        ("ke+e", "ཀ\u{0f7a}\u{0f7a}"),
        ("c+a+i", "ཅ\u{0fb8}\u{0f72}"),
    ];
    for (src, expected) in data {
        assert_eq!(ewts_to_unicode(src).unicode, expected, "input: {src:?}");
    }
    // "+" is not a hex digit.
    assert_ne!(ewts_to_unicode("\\u+f40").unicode, "ཀ");
}

#[test]
fn etu_many_non_tibetan_inserts() {
    let count = 600;

    let mut brackets = String::new();
    let mut expected = String::new();
    for i in 0..count {
        let _ = write!(brackets, "[{i}] ");
        let _ = write!(expected, "{i}་");
    }
    assert_eq!(ewts_to_unicode(&brackets).unicode, expected);

    let digits: Vec<char> = (0..count).filter_map(|i| char::from_digit(i % 10, 10)).collect();
    let escapes: String = digits.iter().flat_map(|&d| ['\\', d]).collect();
    let expected: String = digits.iter().collect();
    assert_eq!(ewts_to_unicode(&escapes).unicode, expected);
}

// `w` after a syllable-initial `b` or `y` is looked up as a possible lower form while only one consonant precedes it; this used to underflow the token index (a panic in debug builds).
#[test]
fn etu_lower_form_after_first_consonant() {
    let data = [("bw", "བཝ"), ("yw", "ཡཝ"), ("bwa", "བཝ"), ("bw ", "བཝ་")];

    for td in &data {
        assert_eq!(ewts_to_unicode(td.0).unicode, td.1);
    }
}

// Typographic apostrophes read as "'".
#[test]
fn etu_apostrophes() {
    for a in ['\u{02bc}', '\u{02b9}', '\u{2018}', '\u{2019}', '\u{02be}'] {
        assert_eq!(ewts_to_unicode(&format!("ba{a}i")).unicode, "བའི", "apostrophe: {a:?}");
        assert_eq!(
            ewts_to_unicode(&format!("абв{a}ka")).unicode,
            "абвའཀ",
            "apostrophe: {a:?}"
        );
    }
    // Inside brackets the text is kept as is.
    assert_eq!(ewts_to_unicode("[ba\u{2019}i]").unicode, "ba\u{2019}i");
}

// Each branch of `is_lower_form`.
#[test]
fn etu_stacks() {
    let data = [
        // A pair with nothing, a vowel or a letter of a triple after it.
        ("rk", "རྐ"),
        ("rka", "རྐ"),
        ("rkya", "རྐྱ"),
        // A pair followed by a bottom letter that does not make a triple: the first letter is a prefix.
        ("brlabs", "བརླབས"),
        ("rkg", "རཀག"),
        // The third letter of a triple.
        ("brgya", "བརྒྱ"),
        ("sgra", "སྒྲ"),
        // No pair.
        ("kt", "ཀཏ"),
        ("bkra", "བཀྲ"),
        // After a "+" stack only a pair is checked.
        ("k+sma", "ཀྶྨ"),
        // An "a" ends the stack.
        ("kaky", "ཀཀྱ"),
        ("aky", "ཨཀྱ"),
    ];
    for (src, expected) in data {
        assert_eq!(ewts_to_unicode(src).unicode, expected, "input: {src:?}");
    }
}

// A xorshift generator for the random tests.
pub(crate) struct Rng(pub(crate) u64);

impl Rng {
    pub(crate) fn next(&mut self) -> u64 {
        self.0 ^= self.0 << 13;
        self.0 ^= self.0 >> 7;
        self.0 ^= self.0 << 17;
        self.0
    }

    pub(crate) fn below(&mut self, n: usize) -> usize {
        usize::try_from(self.next() % n as u64).unwrap()
    }

    pub(crate) fn pick<T: Copy>(&mut self, items: &[T]) -> T {
        items[self.below(items.len())]
    }
}

// Iterations of a random test: `default`, or more with `EWTS_RANDOM_ITERATIONS=10000000 cargo test --release`.
pub(crate) fn random_iterations(default: usize) -> usize {
    std::env::var("EWTS_RANDOM_ITERATIONS")
        .ok()
        .and_then(|n| n.parse().ok())
        .unwrap_or(default)
}

// Any mix of EWTS, syntax, escapes and other text: no panics, and each warning points at a fragment of the source.
#[test]
fn etu_random_input() {
    // "BS" is a backslash.
    let mut fragments: Vec<String> = concat!(
        "k kh g ng c ny t d n p b m ts dz w zh z ' y r l sh s h a T D N Sh f v A i I u U e ai o au -i -I r-i l-I ",
        "M H ~M ~M` ~^ ^ ? & + . [ ] BSu0f40 BSU00000f40 BSu0fz BSu+f4 BSU0f BS BSBS BS[ BS] / // ; | : _ * # % = ",
        "! < > q x W Y R 0 9 ʼ ’ ж 😀 ཀ ི"
    )
    .split(' ')
    .map(|f| f.replace("BS", "\\"))
    .collect();
    fragments.extend([" ", "\n", "\t"].map(String::from));
    let mut rng = Rng(0x2545_F491_4F6C_DD1D);

    for _ in 0..random_iterations(100_000) {
        let src: String = (0..rng.below(12))
            .map(|_| fragments[rng.below(fragments.len())].as_str())
            .collect();
        let warnings = ewts_to_unicode(&src).warnings;
        for pair in warnings.windows(2) {
            assert!(pair[0].pos <= pair[1].pos, "src: {src:?}, warnings: {warnings:?}");
        }
        for w in &warnings {
            let end = w.pos + w.len;
            assert!(
                w.len > 0 && end <= src.len() && src.is_char_boundary(w.pos) && src.is_char_boundary(end),
                "src: {src:?}, warning: {w:?}"
            );
            assert_eq!(src[w.pos..].chars().next(), Some(w.ch), "src: {src:?}, warning: {w:?}");
        }
    }
}