use crate::error::{ErrorCode, Result};
use crate::lexical;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum KeyNormalisation {
NoRule,
UpperAscii,
NfcStrict,
ArabicSkeleton,
HebrewConsonantal,
GreekUnaccented,
LabelFold,
}
impl KeyNormalisation {
pub const ALL: &'static [KeyNormalisation] = &[
KeyNormalisation::NoRule,
KeyNormalisation::UpperAscii,
KeyNormalisation::NfcStrict,
KeyNormalisation::ArabicSkeleton,
KeyNormalisation::HebrewConsonantal,
KeyNormalisation::GreekUnaccented,
KeyNormalisation::LabelFold,
];
pub const fn as_str(self) -> &'static str {
match self {
KeyNormalisation::NoRule => "none",
KeyNormalisation::UpperAscii => "upper_ascii",
KeyNormalisation::NfcStrict => "nfc_strict",
KeyNormalisation::ArabicSkeleton => "arabic_skeleton",
KeyNormalisation::HebrewConsonantal => "hebrew_consonantal",
KeyNormalisation::GreekUnaccented => "greek_unaccented",
KeyNormalisation::LabelFold => "label_fold",
}
}
pub fn from_name(text: &str) -> Option<KeyNormalisation> {
KeyNormalisation::ALL.iter().copied().find(|r| r.as_str() == text)
}
pub fn check(self, text: &str) -> Result<()> {
lexical::check_string(text, "$")?;
if self == KeyNormalisation::NoRule {
return Ok(());
}
let fail = |why: &str| {
Err(crate::error::Error::new(
ErrorCode::KeyNormalisation,
"$",
format!("not canonical under {}: {why}", self.as_str()),
))
};
if text.is_empty() {
return fail("the empty string");
}
if !unicode_normalization::is_nfc(text) {
return fail("not in Normalization Form C");
}
let forbidden = |c: char| match self {
KeyNormalisation::NoRule => false,
KeyNormalisation::UpperAscii => !(('!'..='~').contains(&c) && !c.is_ascii_lowercase()),
KeyNormalisation::NfcStrict => is_format_character(c) || (is_white_space(c) && c != ' '),
KeyNormalisation::ArabicSkeleton => ARABIC_MARKS.iter().any(|r| r.contains(&(c as u32))),
KeyNormalisation::HebrewConsonantal => {
let cp = c as u32;
(0x0591..=0x05C7).contains(&cp) && !matches!(cp, 0x05BE | 0x05C0 | 0x05C3 | 0x05C6)
}
KeyNormalisation::GreekUnaccented => false, KeyNormalisation::LabelFold => false, };
if let Some(c) = text.chars().find(|&c| forbidden(c)) {
return fail(&format!("forbidden character U+{:04X}", c as u32));
}
if self == KeyNormalisation::NfcStrict && (text.starts_with(' ') || text.ends_with(' ') || text.contains(" "))
{
return fail("a leading, trailing or repeated space");
}
if self == KeyNormalisation::GreekUnaccented {
use unicode_normalization::UnicodeNormalization;
if text.nfd().any(|c| ('\u{0300}'..='\u{036F}').contains(&c)) {
return fail("a combining mark in its decomposed form");
}
}
if self == KeyNormalisation::LabelFold && fold_label(text) != text {
return fail("not its own folding (fold_label)");
}
Ok(())
}
}
pub fn fold_label(text: &str) -> String {
use unicode_normalization::UnicodeNormalization;
let mut cased = String::with_capacity(text.len());
for c in text.chars() {
match crate::case_fold::CASE_FOLDING.binary_search_by_key(&(c as u32), |&(cp, _)| cp) {
Ok(i) => cased.push_str(crate::case_fold::CASE_FOLDING[i].1),
Err(_) => cased.push(c),
}
}
let nfc: String = cased.nfc().collect();
let mut out = String::with_capacity(nfc.len());
for word in nfc.split(is_white_space).filter(|w| !w.is_empty()) {
if !out.is_empty() {
out.push(' ');
}
out.push_str(word);
}
out
}
impl core::fmt::Display for KeyNormalisation {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.as_str())
}
}
const ARABIC_MARKS: &[core::ops::RangeInclusive<u32>] = &[
0x0610..=0x061A,
0x064B..=0x065F,
0x0670..=0x0670,
0x06D6..=0x06DC,
0x06DF..=0x06E8,
0x06EA..=0x06ED,
0x0640..=0x0640,
];
const FORMAT_CHARACTERS: &[(u32, u32)] = &[
(0x00AD, 0x00AD),
(0x0600, 0x0605),
(0x061C, 0x061C),
(0x06DD, 0x06DD),
(0x070F, 0x070F),
(0x0890, 0x0891),
(0x08E2, 0x08E2),
(0x180E, 0x180E),
(0x200B, 0x200F),
(0x202A, 0x202E),
(0x2060, 0x2064),
(0x2066, 0x206F),
(0xFEFF, 0xFEFF),
(0xFFF9, 0xFFFB),
(0x110BD, 0x110BD),
(0x110CD, 0x110CD),
(0x13430, 0x1343F),
(0x1BCA0, 0x1BCA3),
(0x1D173, 0x1D17A),
(0xE0001, 0xE0001),
(0xE0020, 0xE007F),
];
fn is_white_space(c: char) -> bool {
matches!(
c as u32,
0x0009..=0x000D
| 0x0020
| 0x0085
| 0x00A0
| 0x1680
| 0x2000..=0x200A
| 0x2028
| 0x2029
| 0x202F
| 0x205F
| 0x3000
)
}
fn is_format_character(c: char) -> bool {
let cp = c as u32;
FORMAT_CHARACTERS.iter().any(|&(lo, hi)| (lo..=hi).contains(&cp))
}