Skip to content

Commit 7df2771

Browse files
committed
core: add a reverse method to Ordering.
This flips the comparison and is designed to be used when sorting etc.
1 parent 75a39e0 commit 7df2771

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/libcore/cmp.rs

+34
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,40 @@ pub enum Ordering {
100100
Greater = 1i,
101101
}
102102

103+
impl Ordering {
104+
/// Reverse the `Ordering`, so that `Less` becomes `Greater` and
105+
/// vice versa.
106+
///
107+
/// # Example
108+
///
109+
/// ```rust
110+
/// assert_eq!(Less.reverse(), Greater);
111+
/// assert_eq!(Equal.reverse(), Equal);
112+
/// assert_eq!(Greater.reverse(), Less);
113+
///
114+
///
115+
/// let mut data = &mut [2u, 10, 5, 8];
116+
///
117+
/// // sort the array from largest to smallest.
118+
/// data.sort_by(|a, b| a.cmp(b).reverse());
119+
///
120+
/// assert_eq!(data, &mut [10u, 8, 5, 2]);
121+
/// ```
122+
#[inline]
123+
#[experimental]
124+
pub fn reverse(self) -> Ordering {
125+
unsafe {
126+
// this compiles really nicely (to a single instruction);
127+
// an explicit match has a pile of branches and
128+
// comparisons.
129+
//
130+
// NB. it is safe because of the explicit discriminants
131+
// given above.
132+
::mem::transmute::<_, Ordering>(-(self as i8))
133+
}
134+
}
135+
}
136+
103137
/// Trait for types that form a [total order](
104138
/// https://en.wikipedia.org/wiki/Total_order).
105139
///

src/libcoretest/cmp.rs

+7
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,13 @@ fn test_mut_int_totalord() {
2828
assert_eq!((&mut 12i).cmp(&&mut -5), Greater);
2929
}
3030

31+
#[test]
32+
fn test_ordering_reverse() {
33+
assert_eq!(Less.reverse(), Greater);
34+
assert_eq!(Equal.reverse(), Equal);
35+
assert_eq!(Greater.reverse(), Less);
36+
}
37+
3138
#[test]
3239
fn test_ordering_order() {
3340
assert!(Less < Equal);

0 commit comments

Comments
 (0)