1
Fork 0

add a TotalOrd trait

This commit is contained in:
Daniel Micay 2013-03-01 22:07:12 -05:00
parent a660bb362c
commit ca1ceb15b1
4 changed files with 166 additions and 11 deletions

View file

@ -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());
@ -2382,6 +2411,7 @@ mod tests {
use ptr;
use str::*;
use vec;
use cmp::{TotalOrd, Less, Equal, Greater};
#[test]
fn test_eq() {
@ -3388,4 +3418,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;
}
}