Skip to content

Commit f4a0b74

Browse files
committed
Implement Ord and PartialOrd for UniCase<AsRef<str>>
1 parent 8529d00 commit f4a0b74

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/lib.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
//! ```
1818
1919
use std::ascii::AsciiExt;
20+
use std::cmp::Ordering;
2021
use std::fmt;
2122
use std::hash::{Hash, Hasher};
2223
use std::ops::{Deref, DerefMut};
@@ -41,6 +42,20 @@ impl<S> DerefMut for UniCase<S> {
4142
}
4243
}
4344

45+
impl<T: AsRef<str>> PartialOrd for UniCase<T> {
46+
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
47+
Some(self.cmp(other))
48+
}
49+
}
50+
51+
impl<T: AsRef<str>> Ord for UniCase<T> {
52+
fn cmp(&self, other: &Self) -> Ordering {
53+
let self_chars = self.as_ref().chars().map(|c| c.to_ascii_lowercase());
54+
let other_chars = other.as_ref().chars().map(|c| c.to_ascii_lowercase());
55+
self_chars.cmp(other_chars)
56+
}
57+
}
58+
4459
impl<S: AsRef<str>> AsRef<str> for UniCase<S> {
4560
#[inline]
4661
fn as_ref(&self) -> &str {
@@ -108,4 +123,16 @@ mod test {
108123
assert_eq!(a, b);
109124
assert_eq!(hash(&a), hash(&b));
110125
}
126+
127+
#[test]
128+
fn test_case_cmp() {
129+
assert!(UniCase("foobar") == UniCase("FOOBAR"));
130+
assert!(UniCase("a") < UniCase("B"));
131+
132+
assert!(UniCase("A") < UniCase("b"));
133+
assert!(UniCase("aa") > UniCase("a"));
134+
135+
assert!(UniCase("a") < UniCase("aa"));
136+
assert!(UniCase("a") < UniCase("AA"));
137+
}
111138
}

0 commit comments

Comments
 (0)