Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Ord and PartialOrd for UniCase<AsRef<str>> #7

Merged
merged 1 commit into from
Dec 11, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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_lowercase());
let other_chars = other.as_ref().chars().map(|c| c.to_ascii_lowercase());
self_chars.cmp(other_chars)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems this is using an unstable feature, so the tests don't pass on stable.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or I could wait until Thursday :)

rust-lang/rust#29254

}
}

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"));
}
}