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.
This commit is contained in:
commit
2304fe6208
5 changed files with 253 additions and 93 deletions
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue