From 5944ef5e0d502420347cc6d9824e34dbf7c27969 Mon Sep 17 00:00:00 2001 From: Corey Farwell Date: Fri, 4 Dec 2015 19:09:15 -0500 Subject: [PATCH] Implement Ord and PartialOrd for UniCase> --- src/lib.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 4530753..9d864ce 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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}; @@ -41,6 +42,20 @@ impl DerefMut for UniCase { } } +impl> PartialOrd for UniCase { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl> Ord for UniCase { + 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> AsRef for UniCase { #[inline] fn as_ref(&self) -> &str { @@ -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")); + } }