1use crate::error::{ErrorCode, Result};
5use crate::lexical;
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
10#[non_exhaustive]
11pub enum KeyNormalisation {
12 NoRule,
14 UpperAscii,
16 NfcStrict,
21 ArabicSkeleton,
24 HebrewConsonantal,
27 GreekUnaccented,
29 LabelFold,
34}
35
36impl KeyNormalisation {
37 pub const ALL: &'static [KeyNormalisation] = &[
39 KeyNormalisation::NoRule,
40 KeyNormalisation::UpperAscii,
41 KeyNormalisation::NfcStrict,
42 KeyNormalisation::ArabicSkeleton,
43 KeyNormalisation::HebrewConsonantal,
44 KeyNormalisation::GreekUnaccented,
45 KeyNormalisation::LabelFold,
46 ];
47
48 pub const fn as_str(self) -> &'static str {
51 match self {
52 KeyNormalisation::NoRule => "none",
53 KeyNormalisation::UpperAscii => "upper_ascii",
54 KeyNormalisation::NfcStrict => "nfc_strict",
55 KeyNormalisation::ArabicSkeleton => "arabic_skeleton",
56 KeyNormalisation::HebrewConsonantal => "hebrew_consonantal",
57 KeyNormalisation::GreekUnaccented => "greek_unaccented",
58 KeyNormalisation::LabelFold => "label_fold",
59 }
60 }
61
62 pub fn from_name(text: &str) -> Option<KeyNormalisation> {
64 KeyNormalisation::ALL.iter().copied().find(|r| r.as_str() == text)
65 }
66
67 pub fn check(self, text: &str) -> Result<()> {
73 lexical::check_string(text, "$")?;
74 if self == KeyNormalisation::NoRule {
75 return Ok(());
76 }
77 let fail = |why: &str| {
78 Err(crate::error::Error::new(
79 ErrorCode::KeyNormalisation,
80 "$",
81 format!("not canonical under {}: {why}", self.as_str()),
82 ))
83 };
84 if text.is_empty() {
85 return fail("the empty string");
86 }
87 if !unicode_normalization::is_nfc(text) {
88 return fail("not in Normalization Form C");
89 }
90 let forbidden = |c: char| match self {
91 KeyNormalisation::NoRule => false,
92 KeyNormalisation::UpperAscii => !(('!'..='~').contains(&c) && !c.is_ascii_lowercase()),
93 KeyNormalisation::NfcStrict => is_format_character(c) || (is_white_space(c) && c != ' '),
94 KeyNormalisation::ArabicSkeleton => ARABIC_MARKS.iter().any(|r| r.contains(&(c as u32))),
95 KeyNormalisation::HebrewConsonantal => {
96 let cp = c as u32;
97 (0x0591..=0x05C7).contains(&cp) && !matches!(cp, 0x05BE | 0x05C0 | 0x05C3 | 0x05C6)
98 }
99 KeyNormalisation::GreekUnaccented => false, KeyNormalisation::LabelFold => false, };
102 if let Some(c) = text.chars().find(|&c| forbidden(c)) {
103 return fail(&format!("forbidden character U+{:04X}", c as u32));
104 }
105 if self == KeyNormalisation::NfcStrict && (text.starts_with(' ') || text.ends_with(' ') || text.contains(" "))
106 {
107 return fail("a leading, trailing or repeated space");
108 }
109 if self == KeyNormalisation::GreekUnaccented {
110 use unicode_normalization::UnicodeNormalization;
111 if text.nfd().any(|c| ('\u{0300}'..='\u{036F}').contains(&c)) {
112 return fail("a combining mark in its decomposed form");
113 }
114 }
115 if self == KeyNormalisation::LabelFold && fold_label(text) != text {
116 return fail("not its own folding (fold_label)");
117 }
118 Ok(())
119 }
120}
121
122pub fn fold_label(text: &str) -> String {
128 use unicode_normalization::UnicodeNormalization;
129 let mut cased = String::with_capacity(text.len());
130 for c in text.chars() {
131 match crate::case_fold::CASE_FOLDING.binary_search_by_key(&(c as u32), |&(cp, _)| cp) {
132 Ok(i) => cased.push_str(crate::case_fold::CASE_FOLDING[i].1),
133 Err(_) => cased.push(c),
134 }
135 }
136 let nfc: String = cased.nfc().collect();
137 let mut out = String::with_capacity(nfc.len());
138 for word in nfc.split(is_white_space).filter(|w| !w.is_empty()) {
139 if !out.is_empty() {
140 out.push(' ');
141 }
142 out.push_str(word);
143 }
144 out
145}
146
147impl core::fmt::Display for KeyNormalisation {
148 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
149 f.write_str(self.as_str())
150 }
151}
152
153const ARABIC_MARKS: &[core::ops::RangeInclusive<u32>] = &[
156 0x0610..=0x061A,
157 0x064B..=0x065F,
158 0x0670..=0x0670,
159 0x06D6..=0x06DC,
160 0x06DF..=0x06E8,
161 0x06EA..=0x06ED,
162 0x0640..=0x0640,
163];
164
165const FORMAT_CHARACTERS: &[(u32, u32)] = &[
169 (0x00AD, 0x00AD),
170 (0x0600, 0x0605),
171 (0x061C, 0x061C),
172 (0x06DD, 0x06DD),
173 (0x070F, 0x070F),
174 (0x0890, 0x0891),
175 (0x08E2, 0x08E2),
176 (0x180E, 0x180E),
177 (0x200B, 0x200F),
178 (0x202A, 0x202E),
179 (0x2060, 0x2064),
180 (0x2066, 0x206F),
181 (0xFEFF, 0xFEFF),
182 (0xFFF9, 0xFFFB),
183 (0x110BD, 0x110BD),
184 (0x110CD, 0x110CD),
185 (0x13430, 0x1343F),
186 (0x1BCA0, 0x1BCA3),
187 (0x1D173, 0x1D17A),
188 (0xE0001, 0xE0001),
189 (0xE0020, 0xE007F),
190];
191
192fn is_white_space(c: char) -> bool {
194 matches!(
195 c as u32,
196 0x0009..=0x000D
197 | 0x0020
198 | 0x0085
199 | 0x00A0
200 | 0x1680
201 | 0x2000..=0x200A
202 | 0x2028
203 | 0x2029
204 | 0x202F
205 | 0x205F
206 | 0x3000
207 )
208}
209
210fn is_format_character(c: char) -> bool {
211 let cp = c as u32;
212 FORMAT_CHARACTERS.iter().any(|&(lo, hi)| (lo..=hi).contains(&cp))
213}