about summary refs log tree commit diff
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2014-08-03 06:31:09 +0000
committerbors <bors@rust-lang.org>2014-08-03 06:31:09 +0000
commitce01b4b1b7a9df49ab6bc7c5eaf0b2f95a799a1b (patch)
tree4e2b33ca8d5d5598f0b3b471540643730d1211ba
parent055e25acbe9fd48e0791c6a97db27a19b4f36b45 (diff)
parent7df277115ac009a671e0a68a27d4c9896bd81a7b (diff)
downloadrust-ce01b4b1b7a9df49ab6bc7c5eaf0b2f95a799a1b.tar.gz
rust-ce01b4b1b7a9df49ab6bc7c5eaf0b2f95a799a1b.zip
auto merge of #16155 : huonw/rust/Ordering-reverse, r=alexcrichton
This flips the comparison and is designed to be used when sorting etc.
-rw-r--r--src/libcore/cmp.rs34
-rw-r--r--src/libcoretest/cmp.rs7
2 files changed, 41 insertions, 0 deletions
diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs
index 3f739b86a1b..a2537a1281e 100644
--- a/src/libcore/cmp.rs
+++ b/src/libcore/cmp.rs
@@ -100,6 +100,40 @@ pub enum Ordering {
    Greater = 1i,
 }
 
+impl Ordering {
+    /// Reverse the `Ordering`, so that `Less` becomes `Greater` and
+    /// vice versa.
+    ///
+    /// # Example
+    ///
+    /// ```rust
+    /// assert_eq!(Less.reverse(), Greater);
+    /// assert_eq!(Equal.reverse(), Equal);
+    /// assert_eq!(Greater.reverse(), Less);
+    ///
+    ///
+    /// let mut data = &mut [2u, 10, 5, 8];
+    ///
+    /// // sort the array from largest to smallest.
+    /// data.sort_by(|a, b| a.cmp(b).reverse());
+    ///
+    /// assert_eq!(data, &mut [10u, 8, 5, 2]);
+    /// ```
+    #[inline]
+    #[experimental]
+    pub fn reverse(self) -> Ordering {
+        unsafe {
+            // this compiles really nicely (to a single instruction);
+            // an explicit match has a pile of branches and
+            // comparisons.
+            //
+            // NB. it is safe because of the explicit discriminants
+            // given above.
+            ::mem::transmute::<_, Ordering>(-(self as i8))
+        }
+    }
+}
+
 /// Trait for types that form a [total order](
 /// https://en.wikipedia.org/wiki/Total_order).
 ///
diff --git a/src/libcoretest/cmp.rs b/src/libcoretest/cmp.rs
index 88e944be3e8..4a38bb33d33 100644
--- a/src/libcoretest/cmp.rs
+++ b/src/libcoretest/cmp.rs
@@ -29,6 +29,13 @@ fn test_mut_int_totalord() {
 }
 
 #[test]
+fn test_ordering_reverse() {
+    assert_eq!(Less.reverse(), Greater);
+    assert_eq!(Equal.reverse(), Equal);
+    assert_eq!(Greater.reverse(), Less);
+}
+
+#[test]
 fn test_ordering_order() {
     assert!(Less < Equal);
     assert_eq!(Greater.cmp(&Less), Greater);