unicode_normalization_alignments/
normalize.rsuse std::char;
use std::ops::FnMut;
use lookups::{canonical_fully_decomposed, composition_table, compatibility_fully_decomposed};
#[inline]
pub fn decompose_canonical<F>(c: char, emit_char: F) where F: FnMut(char) {
decompose(c, canonical_fully_decomposed, emit_char)
}
#[inline]
pub fn decompose_compatible<F: FnMut(char)>(c: char, emit_char: F) {
let decompose_char = |c| compatibility_fully_decomposed(c)
.or_else(|| canonical_fully_decomposed(c));
decompose(c, decompose_char, emit_char)
}
#[inline]
fn decompose<D, F>(c: char, decompose_char: D, mut emit_char: F)
where D: Fn(char) -> Option<&'static [char]>, F: FnMut(char)
{
if c <= '\x7f' {
emit_char(c);
return;
}
if is_hangul_syllable(c) {
decompose_hangul(c, emit_char);
return;
}
if let Some(decomposed) = decompose_char(c) {
for &d in decomposed {
emit_char(d);
}
return;
}
emit_char(c);
}
pub fn compose(a: char, b: char) -> Option<char> {
compose_hangul(a, b).or_else(|| composition_table(a, b))
}
const S_BASE: u32 = 0xAC00;
const L_BASE: u32 = 0x1100;
const V_BASE: u32 = 0x1161;
const T_BASE: u32 = 0x11A7;
const L_COUNT: u32 = 19;
const V_COUNT: u32 = 21;
const T_COUNT: u32 = 28;
const N_COUNT: u32 = (V_COUNT * T_COUNT);
const S_COUNT: u32 = (L_COUNT * N_COUNT);
const S_LAST: u32 = S_BASE + S_COUNT - 1;
const L_LAST: u32 = L_BASE + L_COUNT - 1;
const V_LAST: u32 = V_BASE + V_COUNT - 1;
const T_LAST: u32 = T_BASE + T_COUNT - 1;
const T_FIRST: u32 = T_BASE + 1;
pub(crate) fn is_hangul_syllable(c: char) -> bool {
(c as u32) >= S_BASE && (c as u32) < (S_BASE + S_COUNT)
}
#[allow(unsafe_code)]
#[inline(always)]
fn decompose_hangul<F>(s: char, mut emit_char: F) where F: FnMut(char) {
let s_index = s as u32 - S_BASE;
let l_index = s_index / N_COUNT;
unsafe {
emit_char(char::from_u32_unchecked(L_BASE + l_index));
let v_index = (s_index % N_COUNT) / T_COUNT;
emit_char(char::from_u32_unchecked(V_BASE + v_index));
let t_index = s_index % T_COUNT;
if t_index > 0 {
emit_char(char::from_u32_unchecked(T_BASE + t_index));
}
}
}
#[inline]
pub(crate) fn hangul_decomposition_length(s: char) -> usize {
let si = s as u32 - S_BASE;
let ti = si % T_COUNT;
if ti > 0 { 3 } else { 2 }
}
#[allow(unsafe_code)]
#[inline(always)]
#[allow(ellipsis_inclusive_range_patterns)]
fn compose_hangul(a: char, b: char) -> Option<char> {
let (a, b) = (a as u32, b as u32);
match (a, b) {
(L_BASE ... L_LAST, V_BASE ... V_LAST) => {
let l_index = a - L_BASE;
let v_index = b - V_BASE;
let lv_index = l_index * N_COUNT + v_index * T_COUNT;
let s = S_BASE + lv_index;
Some(unsafe {char::from_u32_unchecked(s)})
},
(S_BASE ... S_LAST, T_FIRST ... T_LAST) if (a - S_BASE) % T_COUNT == 0 => {
Some(unsafe {char::from_u32_unchecked(a + (b - T_BASE))})
},
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::compose_hangul;
#[test]
fn test_hangul_composition() {
assert_eq!(compose_hangul('\u{c8e0}', '\u{11a7}'), None);
}
}