nu_utils/casing.rs
1use std::cmp::Ordering;
2use unicase::UniCase;
3
4pub trait IgnoreCaseExt {
5 /// Returns a [case folded] equivalent of this string, as a new String.
6 ///
7 /// Case folding is primarily based on lowercase mapping, but includes
8 /// additional changes to the source text to help make case folding
9 /// language-invariant and consistent. Case folded text should be used
10 /// solely for processing and generally should not be stored or displayed.
11 ///
12 /// [case folded]: <https://unicode.org/faq/casemap_charprop.html#2>
13 fn to_folded_case(&self) -> String;
14
15 /// Checks that two strings are a case-insensitive match.
16 ///
17 /// Essentially `to_folded_case(a) == to_folded_case(b)`, but without
18 /// allocating and copying string temporaries. Because case folding involves
19 /// Unicode table lookups, it can sometimes be more efficient to use
20 /// `to_folded_case` to case fold once and then compare those strings.
21 fn eq_ignore_case(&self, other: &str) -> bool;
22
23 /// Compares two strings case-insensitively.
24 ///
25 /// Essentially `to_folded_case(a) == to_folded_case(b)`, but without
26 /// allocating and copying string temporaries. Because case folding involves
27 /// Unicode table lookups, it can sometimes be more efficient to use
28 /// `to_folded_case` to case fold once and then compare those strings.
29 ///
30 /// Note that this *only* ignores case, comparing the folded strings without
31 /// any other collation data or locale, so the sort order may be surprising
32 /// outside of ASCII characters.
33 fn cmp_ignore_case(&self, other: &str) -> Ordering;
34}
35
36impl IgnoreCaseExt for str {
37 fn to_folded_case(&self) -> String {
38 UniCase::new(self).to_folded_case()
39 }
40
41 fn eq_ignore_case(&self, other: &str) -> bool {
42 UniCase::new(self) == UniCase::new(other)
43 }
44
45 fn cmp_ignore_case(&self, other: &str) -> Ordering {
46 UniCase::new(self).cmp(&UniCase::new(other))
47 }
48}