Skip to main content

datumesh_core/
normalisation.rs

1//! Key normalisation (16.4, `spec-0.5.0`): the closed list of rules a string key or argument may
2//! be canonical under, and the pure check of a value against one.
3
4use crate::error::{ErrorCode, Result};
5use crate::lexical;
6
7/// One rule of the closed list of 16.4. The list grows only through revisions of the
8/// specification, so the enum is `#[non_exhaustive]`.
9#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
10#[non_exhaustive]
11pub enum KeyNormalisation {
12    /// `none`: any string (3.5). Named `NoRule` so that it is not mistaken for `Option::None`.
13    NoRule,
14    /// `upper_ascii`: printable ASCII only (U+0021 to U+007E), no lowercase `a`-`z`.
15    UpperAscii,
16    /// `nfc_strict`: no format character (Cf), no White_Space character (Unicode 15.1) other than
17    /// U+0020, and no leading, trailing or repeated U+0020. The White_Space characters that 3.5
18    /// does not already refuse are U+00A0, U+1680, U+2002-U+200A, U+2028, U+2029, U+202F, U+205F
19    /// and U+3000 (U+0009-U+000D and U+0085 are controls; U+2000 and U+2001 are not NFC).
20    NfcStrict,
21    /// `arabic_skeleton`: no Arabic mark (U+0610-U+061A, U+064B-U+065F, U+0670, U+06D6-U+06DC,
22    /// U+06DF-U+06E8, U+06EA-U+06ED) and no tatweel U+0640.
23    ArabicSkeleton,
24    /// `hebrew_consonantal`: no Hebrew point or accent U+0591-U+05C7 except maqaf U+05BE, paseq
25    /// U+05C0, sof pasuq U+05C3 and nun hafukha U+05C6.
26    HebrewConsonantal,
27    /// `greek_unaccented`: no combining mark U+0300-U+036F in the NFD form.
28    GreekUnaccented,
29    /// `label_fold` (16.4, the classes round): a value is canonical when it equals its own
30    /// [`fold_label`]: full case folding, NFC, each run of White_Space one U+0020, no leading or trailing
31    /// space, and not empty. A label is the only thing it is for: a key is never folded, and a request's
32    /// label is repaired to its folding by the mesh (16.1).
33    LabelFold,
34}
35
36impl KeyNormalisation {
37    /// Every rule, in the order of the table of 16.4.
38    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    /// The rule as written in a descriptor: `none`, `upper_ascii`, `nfc_strict`,
49    /// `arabic_skeleton`, `hebrew_consonantal`, `greek_unaccented`.
50    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    /// Looks a rule up by its text (exact, lowercase); `None` for anything not in the list.
63    pub fn from_name(text: &str) -> Option<KeyNormalisation> {
64        KeyNormalisation::ALL.iter().copied().find(|r| r.as_str() == text)
65    }
66
67    /// Checks that `text` is canonical under this rule (16.4): a pure function. The text is first
68    /// a string value by 3.5 under every rule, with 3.5's codes (`E_CANON_STRING`, `E_CANON_LIMIT`,
69    /// never `E_KEY_NORMALISATION`). Then the rule: `none` accepts what 3.5 accepts, the empty
70    /// string included; every other rule rejects the empty string, and a value the rule forbids
71    /// is `E_KEY_NORMALISATION`, never repaired.
72    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, // checked on the NFD form below
100            KeyNormalisation::LabelFold => false,       // checked by comparison with its folding below
101        };
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
122/// The folding of a label (16.4, `label_fold`, the classes round): full Unicode case folding (CaseFolding.txt,
123/// statuses C and F, Unicode 15.1, `case_fold.rs`), then NFC, then each run of White_Space (the list of
124/// `nfc_strict`) becomes one U+0020, and leading and trailing spaces are removed. Total: the caller checks
125/// the result (an empty result is a label that is not one). Pure, with no clock, locale or data outside
126/// the crate, so it is the same on every target, the WASM build included.
127pub 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
153/// The Arabic marks of 16.4 (`arabic_skeleton`): the vowel signs, the Quranic annotation signs
154/// and tatweel.
155const 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
165/// Format characters (general category Cf) of Unicode 15.1, as 16.4's `nfc_strict` names them.
166/// The ranges are those of the Unicode database, checked against Python 3.13's `unicodedata`
167/// (Unicode 15.1.0): every Cf code point, and no other.
168const 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
192/// The White_Space property of Unicode 15.1 (the list of 16.4 `nfc_strict`).
193fn 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}