Skip to content

Commit

Permalink
Implement Ord and PartialOrd for UniCase<AsRef<str>>
Browse files Browse the repository at this point in the history
  • Loading branch information
frewsxcv committed Dec 5, 2015
1 parent 8529d00 commit 5944ef5
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
//! ```
use std::ascii::AsciiExt;
use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::ops::{Deref, DerefMut};
Expand All @@ -41,6 +42,20 @@ impl<S> DerefMut for UniCase<S> {
}
}

impl<T: AsRef<str>> PartialOrd for UniCase<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}

impl<T: AsRef<str>> Ord for UniCase<T> {
fn cmp(&self, other: &Self) -> Ordering {
let self_chars = self.as_ref().chars().map(|c| c.to_ascii_uppercase());
let other_chars = other.as_ref().chars().map(|c| c.to_ascii_uppercase());
self_chars.cmp(other_chars)
}
}

impl<S: AsRef<str>> AsRef<str> for UniCase<S> {
#[inline]
fn as_ref(&self) -> &str {
Expand Down Expand Up @@ -108,4 +123,16 @@ mod test {
assert_eq!(a, b);
assert_eq!(hash(&a), hash(&b));
}

#[test]
fn test_case_cmp() {
assert!(UniCase("foobar") == UniCase("FOOBAR"));
assert!(UniCase("a") < UniCase("B"));

assert!(UniCase("A") < UniCase("b"));
assert!(UniCase("aa") > UniCase("a"));

assert!(UniCase("a") < UniCase("aa"));
assert!(UniCase("a") < UniCase("AA"));
}
}

0 comments on commit 5944ef5

Please sign in to comment.