diff options
| author | bors <bors@rust-lang.org> | 2013-03-02 05:15:39 -0800 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2013-03-02 05:15:39 -0800 |
| commit | 2304fe6208404ce952aaa37e7634db570ff71f6c (patch) | |
| tree | ff90158dc320e3c59e5572a41adbbd148bf82cf7 /src/libcore/str.rs | |
| parent | 5aca7d6aef2f5e18b640d918b243a71fc893a65b (diff) | |
| parent | 035233a25907af8206d254878e7e04048fcac95e (diff) | |
| download | rust-2304fe6208404ce952aaa37e7634db570ff71f6c.tar.gz rust-2304fe6208404ce952aaa37e7634db570ff71f6c.zip | |
auto merge of #5196 : thestinger/rust/ord, r=catamorphism
This allows `TreeMap`/`TreeSet` to fully express their requirements and reduces the comparisons from ~1.5 per level to 1 which really helps for string keys. I also added `ReverseIter` to the prelude exports because I forgot when I originally added it.
Diffstat (limited to 'src/libcore/str.rs')
| -rw-r--r-- | src/libcore/str.rs | 40 |
1 files changed, 39 insertions, 1 deletions
diff --git a/src/libcore/str.rs b/src/libcore/str.rs index 7dfc52c458a..f1e23f01e7b 100644 --- a/src/libcore/str.rs +++ b/src/libcore/str.rs @@ -20,7 +20,7 @@ use at_vec; use cast; use char; -use cmp::{Eq, Ord}; +use cmp::{Eq, Ord, TotalOrd, Ordering, Less, Equal, Greater}; use libc; use libc::size_t; use io::WriterUtil; @@ -773,6 +773,35 @@ pub pure fn eq(a: &~str, b: &~str) -> bool { eq_slice(*a, *b) } +pure fn cmp(a: &str, b: &str) -> Ordering { + let low = uint::min(a.len(), b.len()); + + for uint::range(0, low) |idx| { + match a[idx].cmp(&b[idx]) { + Greater => return Greater, + Less => return Less, + Equal => () + } + } + + a.len().cmp(&b.len()) +} + +#[cfg(notest)] +impl TotalOrd for &str { + pure fn cmp(&self, other: & &self/str) -> Ordering { cmp(*self, *other) } +} + +#[cfg(notest)] +impl TotalOrd for ~str { + pure fn cmp(&self, other: &~str) -> Ordering { cmp(*self, *other) } +} + +#[cfg(notest)] +impl TotalOrd for @str { + pure fn cmp(&self, other: &@str) -> Ordering { cmp(*self, *other) } +} + /// Bytewise slice less than pure fn lt(a: &str, b: &str) -> bool { let (a_len, b_len) = (a.len(), b.len()); @@ -2389,6 +2418,7 @@ mod tests { use ptr; use str::*; use vec; + use cmp::{TotalOrd, Less, Equal, Greater}; #[test] fn test_eq() { @@ -3395,4 +3425,12 @@ mod tests { assert view("abcdef", 1, 5).to_managed() == @"bcde"; } + #[test] + fn test_total_ord() { + "1234".cmp(& &"123") == Greater; + "123".cmp(& &"1234") == Less; + "1234".cmp(& &"1234") == Equal; + "12345555".cmp(& &"123456") == Less; + "22".cmp(& &"1234") == Greater; + } } |
