mod generated;
use generated::{CANONICAL, CCC, COMPATIBILITY, COMPOSITION, DECOMPOSED};
pub use generated::UNICODE_VERSION;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NormalForm {
Nfc,
Nfd,
Nfkc,
Nfkd,
}
impl NormalForm {
pub fn name(self) -> &'static str {
match self {
NormalForm::Nfc => "NFC",
NormalForm::Nfd => "NFD",
NormalForm::Nfkc => "NFKC",
NormalForm::Nfkd => "NFKD",
}
}
pub fn from_name(word: &str) -> Option<NormalForm> {
match word.to_ascii_uppercase().as_str() {
"NFC" => Some(NormalForm::Nfc),
"NFD" => Some(NormalForm::Nfd),
"NFKC" => Some(NormalForm::Nfkc),
"NFKD" => Some(NormalForm::Nfkd),
_ => None,
}
}
fn composes(self) -> bool {
matches!(self, NormalForm::Nfc | NormalForm::Nfkc)
}
fn compatibility(self) -> bool {
matches!(self, NormalForm::Nfkc | NormalForm::Nfkd)
}
}
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;
fn ccc(c: char) -> u8 {
match CCC.binary_search_by_key(&c, |&(k, _)| k) {
Ok(i) => CCC[i].1,
Err(_) => 0,
}
}
fn decomposition(c: char, compatibility: bool) -> Option<&'static [char]> {
let table = if compatibility {
COMPATIBILITY
} else {
CANONICAL
};
let i = table.binary_search_by_key(&c, |&(k, _, _)| k).ok()?;
let (_, at, len) = table[i];
Some(&DECOMPOSED[at as usize..at as usize + len as usize])
}
fn compose_pair(first: char, second: char) -> Option<char> {
let (a, b) = (first as u32, second as u32);
if (L_BASE..L_BASE + L_COUNT).contains(&a) && (V_BASE..V_BASE + V_COUNT).contains(&b) {
let syllable = S_BASE + ((a - L_BASE) * V_COUNT + (b - V_BASE)) * T_COUNT;
return char::from_u32(syllable);
}
if (S_BASE..S_BASE + S_COUNT).contains(&a)
&& (a - S_BASE).is_multiple_of(T_COUNT)
&& (T_BASE + 1..T_BASE + T_COUNT).contains(&b)
{
return char::from_u32(a + (b - T_BASE));
}
COMPOSITION
.binary_search_by_key(&(first, second), |&(x, y, _)| (x, y))
.ok()
.map(|i| COMPOSITION[i].2)
}
fn decompose_char(out: &mut Vec<char>, c: char, compatibility: bool) {
let u = c as u32;
if (S_BASE..S_BASE + S_COUNT).contains(&u) {
let index = u - S_BASE;
let (l, v, t) = (
L_BASE + index / N_COUNT,
V_BASE + (index % N_COUNT) / T_COUNT,
index % T_COUNT,
);
out.extend(char::from_u32(l));
out.extend(char::from_u32(v));
if t != 0 {
out.extend(char::from_u32(T_BASE + t));
}
return;
}
match decomposition(c, compatibility) {
Some(chars) => out.extend_from_slice(chars),
None => out.push(c),
}
}
fn canonical_order(chars: &mut [char]) {
for i in 1..chars.len() {
let class = ccc(chars[i]);
if class == 0 {
continue;
}
let mut j = i;
while j > 0 && ccc(chars[j - 1]) > class {
chars.swap(j - 1, j);
j -= 1;
}
}
}
fn compose(chars: Vec<char>) -> Vec<char> {
let mut out: Vec<char> = Vec::with_capacity(chars.len());
let mut starter: Option<usize> = None;
let mut previous = 0u8;
let mut anything_since_starter = false;
for c in chars {
let class = ccc(c);
if let Some(at) = starter
&& !(anything_since_starter && previous >= class)
&& let Some(composed) = compose_pair(out[at], c)
{
out[at] = composed;
continue;
}
if class == 0 {
starter = Some(out.len());
anything_since_starter = false;
} else {
anything_since_starter = true;
}
previous = class;
out.push(c);
}
out
}
pub fn normalize(s: &str, form: NormalForm) -> String {
if s.is_ascii() {
return s.to_string();
}
let mut chars = Vec::with_capacity(s.len());
for c in s.chars() {
decompose_char(&mut chars, c, form.compatibility());
}
canonical_order(&mut chars);
if form.composes() {
chars = compose(chars);
}
chars.into_iter().collect()
}
pub fn is_normalized(s: &str, form: NormalForm) -> bool {
if s.is_ascii() {
return true;
}
normalize(s, form) == s
}
pub fn is_ident_start(c: char) -> bool {
if c.is_ascii() {
return c.is_ascii_alphabetic() || c == '_';
}
in_ranges(generated::IDENT_START, c)
}
pub fn is_ident_extend(c: char) -> bool {
if c.is_ascii() {
return c.is_ascii_alphanumeric() || c == '_';
}
in_ranges(generated::IDENT_EXTEND, c)
}
fn in_ranges(ranges: &[(char, char)], c: char) -> bool {
match ranges.binary_search_by(|(from, _)| from.cmp(&c)) {
Ok(_) => true,
Err(0) => false,
Err(at) => ranges[at - 1].1 >= c,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ascii_is_already_in_every_form() {
for form in [
NormalForm::Nfc,
NormalForm::Nfd,
NormalForm::Nfkc,
NormalForm::Nfkd,
] {
assert_eq!(normalize("ab", form), "ab");
assert!(is_normalized("ab", form));
}
}
#[test]
fn a_letter_and_its_accent_are_one_character_composed_and_two_decomposed() {
assert_eq!(normalize("e\u{301}", NormalForm::Nfc), "\u{e9}");
assert_eq!(normalize("\u{e9}", NormalForm::Nfd), "e\u{301}");
assert!(is_normalized("\u{e9}", NormalForm::Nfc));
assert!(!is_normalized("\u{e9}", NormalForm::Nfd));
}
#[test]
fn compatibility_is_the_only_form_that_loses_the_formatting() {
assert_eq!(normalize("\u{fb01}", NormalForm::Nfc), "\u{fb01}");
assert_eq!(normalize("\u{fb01}", NormalForm::Nfkc), "fi");
assert_eq!(normalize("\u{bd}", NormalForm::Nfkd), "1\u{2044}2");
}
#[test]
fn marks_sort_by_combining_class_and_keep_their_order_inside_a_class() {
assert_eq!(
normalize("a\u{301}\u{328}", NormalForm::Nfd),
"a\u{328}\u{301}"
);
assert_eq!(
normalize("a\u{301}\u{328}", NormalForm::Nfc),
normalize("a\u{328}\u{301}", NormalForm::Nfc)
);
}
#[test]
fn a_hangul_syllable_is_arithmetic_in_both_directions() {
assert_eq!(normalize("\u{ac00}", NormalForm::Nfd), "\u{1100}\u{1161}");
assert_eq!(normalize("\u{1100}\u{1161}", NormalForm::Nfc), "\u{ac00}");
assert_eq!(
normalize("\u{d4db}", NormalForm::Nfd),
"\u{1111}\u{1171}\u{11b6}"
);
assert_eq!(
normalize("\u{1111}\u{1171}\u{11b6}", NormalForm::Nfc),
"\u{d4db}"
);
}
#[test]
fn an_excluded_composition_stays_apart() {
assert_eq!(normalize("\u{958}", NormalForm::Nfc), "\u{915}\u{93c}");
assert_eq!(
normalize("\u{915}\u{93c}", NormalForm::Nfc),
"\u{915}\u{93c}"
);
}
#[test]
fn a_blocked_mark_does_not_reach_the_starter() {
assert_eq!(
normalize("a\u{308}\u{301}", NormalForm::Nfc),
"\u{e4}\u{301}"
);
assert_eq!(
normalize("a\u{328}\u{301}", NormalForm::Nfc),
"\u{105}\u{301}"
);
}
#[test]
fn every_form_has_a_name_and_answers_to_it() {
for form in [
NormalForm::Nfc,
NormalForm::Nfd,
NormalForm::Nfkc,
NormalForm::Nfkd,
] {
assert_eq!(NormalForm::from_name(form.name()), Some(form));
assert_eq!(
NormalForm::from_name(&form.name().to_ascii_lowercase()),
Some(form)
);
}
assert_eq!(NormalForm::from_name("NFX"), None);
}
}