ewts 1.0.0

Converter between EWTS (Extended Wylie Transliteration Scheme) and Tibetan Unicode symbols (lib)
Documentation
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
    );
}

// Built on the first conversion: programs that only convert EWTS to Unicode never need it.
static MAPS: LazyLock<UnicodeToEwtsMaps> = LazyLock::new(UnicodeToEwtsMaps::create);

#[inline]
pub(crate) fn convert(src: &str) -> UnicodeToEwts {
    convert_with(&MAPS, src)
}

// Warnings are collected by index into the decomposed chars: (kind, index).
type RawWarnings = Vec<(UnicodeWarningKind, usize)>;

fn convert_with(maps: &UnicodeToEwtsMaps, src: &str) -> UnicodeToEwts {
    let mut warnings = RawWarnings::new();
    // Precomposed chars: (index of the first part, number of parts).
    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;
            }
            // A typographic apostrophe would read as "'", so it goes in the brackets too.
            _ if c.is_ascii() || is_apostrophe(c) => {
                // Spaces between words stay inside the brackets: "[New York]", not "[New]_[York]".
                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;
            }
            // Other Tibetan chars, including vowel signs etc. with no letter to attach to.
            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 }
}

// Turns indexes into the decomposed chars into byte offsets in `src`.
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();
    // Parts beyond the first of the precomposed chars before the current one.
    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,
        };
        // Parts of one precomposed char can give the same warning.
        if warnings.last() != Some(&warning) {
            warnings.push(warning);
        }
    }
    warnings
}

/// The kind of a [`UnicodeWarning`] from [`unicode_to_ewts`](crate::unicode_to_ewts).
///
/// New kinds may be added in minor versions.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnicodeWarningKind {
    /// Signs of a stack are not in canonical order (a vowel sign before a subjoined letter, a final before a vowel
    /// sign) or a tsa-phru is repeated: the EWTS converts back to the signs in canonical order.
    SignOrder,
    /// A char is written as chars that are not canonically equivalent to it: "ༀ" is "oM", which converts back to
    /// "ཨོཾ".
    NotEquivalent,
    /// A vowel sign, subjoined letter or final with no letter to attach to; written as an escape.
    NoLetter,
    /// A Tibetan char with no EWTS; written as an escape.
    NoEwts,
}

impl UnicodeWarningKind {
    /// Whether the EWTS converts back to a different string: [`SignOrder`](Self::SignOrder) and
    /// [`NotEquivalent`](Self::NotEquivalent). The escapes of the other kinds convert back exactly.
    #[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",
        })
    }
}

/// The result of [`unicode_to_ewts`](crate::unicode_to_ewts).
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnicodeToEwts {
    /// The converted text.
    pub ewts: String,
    /// Problems in the source, sorted by position.
    pub warnings: Vec<UnicodeWarning>,
}

/// A problem in the input of [`unicode_to_ewts`](crate::unicode_to_ewts).
///
/// A warning is always about one char, so unlike [`EwtsWarning`](crate::EwtsWarning) it has no `len`:
/// the fragment is `&src[pos..pos + ch.len_utf8()]`.
///
/// ```
/// use ewts::UnicodeWarningKind;
///
/// let src = "ཀ་ༀ";
/// let result = ewts::unicode_to_ewts(src);
///
/// assert_eq!(result.ewts, "ka oM");
/// let warning = result.warnings[0];
/// assert_eq!(warning.kind, UnicodeWarningKind::NotEquivalent);
/// assert_eq!(warning.pos, 6);
/// assert_eq!(&src[warning.pos..warning.pos + warning.ch.len_utf8()], "ༀ");
/// assert_eq!(warning.to_string(), "not canonically equivalent at byte 6: 'ༀ'");
///
/// // A vowel sign with no letter.
/// let warning = ewts::unicode_to_ewts("\u{f72}").warnings[0];
/// assert_eq!(warning.to_string(), "no letter to attach to at byte 0: '\\u{f72}'");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UnicodeWarning {
    /// What is wrong.
    pub kind: UnicodeWarningKind,
    /// Byte offset of the char in the source string.
    pub pos: usize,
    /// The char at `pos`; a precomposed char rather than its part.
    pub ch: char,
}

/// "not canonically equivalent at byte 6: 'ༀ'"; a combining char is escaped: "no letter to attach to at byte 0:
/// '\u{f72}'".
impl fmt::Display for UnicodeWarning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} at byte {}: {:?}", self.kind, self.pos, self.ch)
    }
}