use crate::normalize_tables::{
CANONICAL_DECOMPOSITION, COMBINING_CLASS, COMPATIBILITY_DECOMPOSITION, COMPOSITION,
HANGUL_SBASE, HANGUL_SCOUNT,
};
use crate::value::Wtf8;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Form {
Nfc,
Nfd,
Nfkc,
Nfkd,
}
impl Form {
pub fn parse(name: &str) -> Option<Form> {
match name {
"NFC" => Some(Form::Nfc),
"NFD" => Some(Form::Nfd),
"NFKC" => Some(Form::Nfkc),
"NFKD" => Some(Form::Nfkd),
_ => None,
}
}
fn compatibility(self) -> bool {
matches!(self, Form::Nfkc | Form::Nfkd)
}
fn composes(self) -> bool {
matches!(self, Form::Nfc | Form::Nfkc)
}
}
pub fn normalize(text: &Wtf8, form: Form) -> Wtf8 {
if text.as_bytes().is_ascii() {
return text.clone();
}
let mut points = text.code_point_values();
decompose(&mut points, form.compatibility());
canonical_order(&mut points);
if form.composes() {
compose(&mut points);
}
encode(&points)
}
fn decompose(points: &mut Vec<u32>, compatibility: bool) {
let mut out = Vec::with_capacity(points.len());
for &point in points.iter() {
expand(point, compatibility, &mut out, 0);
}
*points = out;
}
fn expand(point: u32, compatibility: bool, out: &mut Vec<u32>, depth: u32) {
debug_assert!(depth < 8, "decomposition must be acyclic");
if let Some((lead, vowel, tail)) = hangul_decompose(point) {
out.push(lead);
out.push(vowel);
if let Some(tail) = tail {
out.push(tail);
}
return;
}
let mapping = if compatibility {
lookup(COMPATIBILITY_DECOMPOSITION, point)
.or_else(|| lookup(CANONICAL_DECOMPOSITION, point))
} else {
lookup(CANONICAL_DECOMPOSITION, point)
};
match mapping {
Some(members) => {
for &member in members {
expand(member, compatibility, out, depth + 1);
}
}
None => out.push(point),
}
}
fn lookup(table: &'static [(u32, &'static [u32])], point: u32) -> Option<&'static [u32]> {
table
.binary_search_by_key(&point, |&(key, _)| key)
.ok()
.map(|index| table[index].1)
}
fn canonical_order(points: &mut [u32]) {
let mut start = 0;
while start < points.len() {
if combining_class(points[start]) == 0 {
start += 1;
continue;
}
let mut end = start;
while end < points.len() && combining_class(points[end]) != 0 {
end += 1;
}
sort_run(&mut points[start..end]);
start = end;
}
}
fn sort_run(run: &mut [u32]) {
for index in 1..run.len() {
let point = run[index];
let class = combining_class(point);
let mut position = index;
while position > 0 && combining_class(run[position - 1]) > class {
run[position] = run[position - 1];
position -= 1;
}
run[position] = point;
}
}
fn compose(points: &mut Vec<u32>) {
let mut out: Vec<u32> = Vec::with_capacity(points.len());
let mut starter: Option<usize> = None;
let mut last_class: u8 = 0;
for &point in points.iter() {
let class = combining_class(point);
if let Some(at) = starter
&& (last_class == 0 || last_class < class)
&& let Some(composite) = compose_pair(out[at], point)
{
out[at] = composite;
last_class = combining_class(composite);
continue;
}
if class == 0 {
starter = Some(out.len());
}
last_class = class;
out.push(point);
}
*points = out;
}
fn compose_pair(first: u32, second: u32) -> Option<u32> {
if let Some(composite) = hangul_compose(first, second) {
return Some(composite);
}
let key = u64::from(first) << 21 | u64::from(second);
COMPOSITION
.binary_search_by_key(&key, |&(candidate, _)| candidate)
.ok()
.map(|index| COMPOSITION[index].1)
}
const HANGUL_LBASE: u32 = 0x1100;
const HANGUL_VBASE: u32 = 0x1161;
const HANGUL_TBASE: u32 = 0x11a7;
const HANGUL_LCOUNT: u32 = 19;
const HANGUL_VCOUNT: u32 = 21;
const HANGUL_TCOUNT: u32 = 28;
const HANGUL_NCOUNT: u32 = HANGUL_VCOUNT * HANGUL_TCOUNT;
fn hangul_decompose(point: u32) -> Option<(u32, u32, Option<u32>)> {
if !(HANGUL_SBASE..HANGUL_SBASE + HANGUL_SCOUNT).contains(&point) {
return None;
}
let index = point - HANGUL_SBASE;
let lead = HANGUL_LBASE + index / HANGUL_NCOUNT;
let vowel = HANGUL_VBASE + (index % HANGUL_NCOUNT) / HANGUL_TCOUNT;
let tail = index % HANGUL_TCOUNT;
Some((lead, vowel, (tail != 0).then(|| HANGUL_TBASE + tail)))
}
fn hangul_compose(first: u32, second: u32) -> Option<u32> {
if (HANGUL_LBASE..HANGUL_LBASE + HANGUL_LCOUNT).contains(&first)
&& (HANGUL_VBASE..HANGUL_VBASE + HANGUL_VCOUNT).contains(&second)
{
let lead = first - HANGUL_LBASE;
let vowel = second - HANGUL_VBASE;
return Some(HANGUL_SBASE + (lead * HANGUL_VCOUNT + vowel) * HANGUL_TCOUNT);
}
if (HANGUL_SBASE..HANGUL_SBASE + HANGUL_SCOUNT).contains(&first)
&& (first - HANGUL_SBASE) % HANGUL_TCOUNT == 0
&& (HANGUL_TBASE + 1..HANGUL_TBASE + HANGUL_TCOUNT).contains(&second)
{
return Some(first + (second - HANGUL_TBASE));
}
None
}
fn combining_class(point: u32) -> u8 {
let found = COMBINING_CLASS.binary_search_by(|&(lo, hi, _)| {
if hi < point {
std::cmp::Ordering::Less
} else if lo > point {
std::cmp::Ordering::Greater
} else {
std::cmp::Ordering::Equal
}
});
match found {
Ok(index) => COMBINING_CLASS[index].2,
Err(_) => 0,
}
}
fn encode(points: &[u32]) -> Wtf8 {
Wtf8::from_code_points(points)
}
#[cfg(test)]
mod tests {
use super::*;
fn nfc(text: &str) -> String {
normalize(&Wtf8::new(text), Form::Nfc)
.to_string_lossy()
.into_owned()
}
fn nfd(text: &str) -> String {
normalize(&Wtf8::new(text), Form::Nfd)
.to_string_lossy()
.into_owned()
}
fn nfkc(text: &str) -> String {
normalize(&Wtf8::new(text), Form::Nfkc)
.to_string_lossy()
.into_owned()
}
fn nfkd(text: &str) -> String {
normalize(&Wtf8::new(text), Form::Nfkd)
.to_string_lossy()
.into_owned()
}
#[test]
fn the_four_forms_differ_as_the_annex_says() {
let text = "\u{1E9B}\u{0323}";
assert_eq!(nfc(text), "\u{1E9B}\u{0323}");
assert_eq!(nfd(text), "\u{017F}\u{0323}\u{0307}");
assert_eq!(nfkc(text), "\u{1E69}");
assert_eq!(nfkd(text), "s\u{0323}\u{0307}");
}
#[test]
fn a_starter_and_a_mark_compose() {
assert_eq!(nfc("e\u{0301}"), "\u{00E9}");
assert_eq!(nfd("\u{00E9}"), "e\u{0301}");
}
#[test]
fn marks_are_reordered_by_combining_class() {
assert_eq!(nfc("a\u{0301}\u{0323}"), "\u{1EA1}\u{0301}");
assert_eq!(nfd("\u{1EA1}\u{0301}"), "a\u{0323}\u{0301}");
assert_eq!(nfd("\u{1EAD}"), "a\u{0323}\u{0302}");
}
#[test]
fn equal_classes_stay_in_order() {
assert_eq!(nfd("a\u{0301}\u{0300}"), "a\u{0301}\u{0300}");
}
#[test]
fn a_mark_of_the_same_class_blocks_the_next() {
assert_eq!(nfc("a\u{0301}\u{0301}"), "\u{00E1}\u{0301}");
assert_eq!(nfc("a\u{0334}\u{0301}"), "\u{00E1}\u{0334}");
assert_eq!(nfc("a\u{0301}b"), "\u{00E1}b");
}
#[test]
fn hangul_composes_and_decomposes_arithmetically() {
assert_eq!(nfc("\u{1100}\u{1161}"), "\u{AC00}");
assert_eq!(nfc("\u{1100}\u{1161}\u{11A8}"), "\u{AC01}");
assert_eq!(nfc("\u{AC01}\u{11A8}"), "\u{AC01}\u{11A8}");
assert_eq!(nfd("\u{AC01}"), "\u{1100}\u{1161}\u{11A8}");
assert_eq!(nfd("\u{AC00}"), "\u{1100}\u{1161}");
}
#[test]
fn decomposition_and_composition_agree() {
for text in [
"\u{1E9B}\u{0323}",
"\u{00C5}",
"\u{AC01}",
"\u{212B}", "\u{FB01}", "plain text",
"",
] {
assert_eq!(nfc(&nfd(text)), nfc(text));
assert_eq!(nfkc(&nfkd(text)), nfkc(text));
}
}
#[test]
fn normalization_is_idempotent() {
for text in [
"\u{1E9B}\u{0323}",
"\u{0041}\u{030A}",
"\u{AC01}",
"\u{212B}",
"ascii",
] {
for form in [Form::Nfc, Form::Nfd, Form::Nfkc, Form::Nfkd] {
let once = normalize(&Wtf8::new(text), form);
let twice = normalize(&once, form);
assert_eq!(once, twice);
}
}
}
#[test]
fn a_lone_surrogate_passes_through() {
let text = Wtf8::from_units(&[0xD800, b'e' as u16, 0x0301]);
for form in [Form::Nfc, Form::Nfd, Form::Nfkc, Form::Nfkd] {
let units = normalize(&text, form).to_units();
assert_eq!(units[0], 0xD800);
let expected: &[u16] = if form.composes() {
&[0xD800, 0x00E9]
} else {
&[0xD800, b'e' as u16, 0x0301]
};
assert_eq!(units, expected, "{form:?}");
}
}
#[test]
fn only_the_four_names_parse() {
assert_eq!(Form::parse("NFC"), Some(Form::Nfc));
assert_eq!(Form::parse("NFD"), Some(Form::Nfd));
assert_eq!(Form::parse("NFKC"), Some(Form::Nfkc));
assert_eq!(Form::parse("NFKD"), Some(Form::Nfkd));
assert_eq!(Form::parse("nfc"), None);
assert_eq!(Form::parse("NFCC"), None);
assert_eq!(Form::parse(""), None);
}
}