git clone https://garage44.eu/jeroen/pinnacle.git.. /text/src/arabic.rs
//! Joining: which form each letter of Arabic (and Syriac, N'Ko, …) takes —
//! alone, at the start of a word, in its middle or at its end — from
//! whether its neighbours join it. The forms themselves are the font's
//! (its `isol`, `init`, `medi` and `fina` features); this says which a
//! letter asks for.
use alloc::vec::Vec;
use crate::tables;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(u8)]
pub enum Joining {
/// Joins neither side (most characters).
U,
/// Joins the letter before it only (alef, dal, reh, waw).
R,
/// Joins the letter after it only.
L,
/// Joins both sides (beh, seen, lam, …).
D,
/// Makes its neighbours join, itself drawn by none (tatweel's kin, ZWJ).
C,
/// Passed over: marks between letters do not break their joining.
T,
}
const JOININGS: [Joining; 6] = [
Joining::U,
Joining::R,
Joining::L,
Joining::D,
Joining::C,
Joining::T,
];
pub fn joining(c: char) -> Joining {
crate::find(&tables::JOINING, c as u32).map_or(Joining::U, |i| JOININGS[usize::from(i)])
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Form {
/// Not a joining letter: no form feature applies.
None,
Isolated,
Initial,
Medial,
Final,
}
/// The form of each character of `text`, in logical order.
pub fn forms(text: &[char]) -> Vec<Form> {
use Joining::*;
let types: Vec<Joining> = text.iter().map(|&c| joining(c)).collect();
let mut out = alloc::vec![Form::None; text.len()];
for i in 0..text.len() {
let t = types[i];
if !matches!(t, R | L | D) {
continue;
}
let prev = (0..i).rev().find(|&k| types[k] != T).map(|k| types[k]);
let next = (i + 1..text.len()).find(|&k| types[k] != T).map(|k| types[k]);
let joins_prev = matches!(t, R | D) && matches!(prev, Some(L | D | C));
let joins_next = matches!(t, L | D) && matches!(next, Some(R | D | C));
out[i] = match (joins_prev, joins_next) {
(true, true) => Form::Medial,
(true, false) => Form::Final,
(false, true) => Form::Initial,
(false, false) => Form::Isolated,
};
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn of(s: &str) -> Vec<Form> {
forms(&s.chars().collect::<Vec<_>>())
}
#[test]
fn a_word_joins() {
use Form::*;
// سلام: seen joins on, lam both sides, alef only back, meem alone.
assert_eq!(of("سلام"), [Initial, Medial, Final, Isolated]);
// بيت: beh, yeh, teh.
assert_eq!(of("بيت"), [Initial, Medial, Final]);
// A space breaks the joining.
assert_eq!(of("ب ب"), [Isolated, None, Isolated]);
// A mark between two letters does not.
assert_eq!(of("بَب"), [Initial, None, Final]);
// ZWJ makes a letter join what is not there.
assert_eq!(of("ب\u{200d}"), [Initial, None]);
}
}