Skip to content

Commit ed17ce1

Browse files
committed
Implement Ord trait for Timespec
1 parent 8bde2c1 commit ed17ce1

File tree

1 file changed

+46
-2
lines changed

1 file changed

+46
-2
lines changed

src/libstd/time.rs

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
#[forbid(deprecated_mode)];
1212

13-
use core::cmp::Eq;
13+
use core::cmp::{Eq, Ord};
1414
use core::int;
1515
use core::libc::{c_char, c_int, c_long, size_t, time_t};
1616
use core::i32;
@@ -41,7 +41,7 @@ extern mod rustrt {
4141
pub struct Timespec { sec: i64, nsec: i32 }
4242

4343
impl Timespec {
44-
static fn new(sec: i64, nsec: i32) -> Timespec {
44+
static pure fn new(sec: i64, nsec: i32) -> Timespec {
4545
Timespec { sec: sec, nsec: nsec }
4646
}
4747
}
@@ -53,6 +53,16 @@ impl Timespec : Eq {
5353
pure fn ne(&self, other: &Timespec) -> bool { !self.eq(other) }
5454
}
5555

56+
impl Timespec : Ord {
57+
pure fn lt(&self, other: &Timespec) -> bool {
58+
self.sec < other.sec ||
59+
(self.sec == other.sec && self.nsec < other.nsec)
60+
}
61+
pure fn le(&self, other: &Timespec) -> bool { !other.lt(self) }
62+
pure fn ge(&self, other: &Timespec) -> bool { !self.lt(other) }
63+
pure fn gt(&self, other: &Timespec) -> bool { !self.le(other) }
64+
}
65+
5666
/**
5767
* Returns the current time as a `timespec` containing the seconds and
5868
* nanoseconds since 1970-01-01T00:00:00Z.
@@ -1247,4 +1257,38 @@ mod tests {
12471257
assert utc.rfc822z() == ~"Fri, 13 Feb 2009 23:31:30 -0000";
12481258
assert utc.rfc3339() == ~"2009-02-13T23:31:30Z";
12491259
}
1260+
1261+
#[test]
1262+
fn test_timespec_eq_ord() {
1263+
use core::cmp::{eq, ge, gt, le, lt, ne};
1264+
1265+
let a = &Timespec::new(-2, 1);
1266+
let b = &Timespec::new(-1, 2);
1267+
let c = &Timespec::new(1, 2);
1268+
let d = &Timespec::new(2, 1);
1269+
let e = &Timespec::new(2, 1);
1270+
1271+
assert eq(d, e);
1272+
assert ne(c, e);
1273+
1274+
assert lt(a, b);
1275+
assert lt(b, c);
1276+
assert lt(c, d);
1277+
1278+
assert le(a, b);
1279+
assert le(b, c);
1280+
assert le(c, d);
1281+
assert le(d, e);
1282+
assert le(e, d);
1283+
1284+
assert ge(b, a);
1285+
assert ge(c, b);
1286+
assert ge(d, c);
1287+
assert ge(e, d);
1288+
assert ge(d, e);
1289+
1290+
assert gt(b, a);
1291+
assert gt(c, b);
1292+
assert gt(d, c);
1293+
}
12501294
}

0 commit comments

Comments
 (0)