about summary refs log tree commit diff
diff options
context:
space:
mode:
authorHuon Wilson <dbau.pp+github@gmail.com>2014-08-01 12:53:00 +1000
committerHuon Wilson <dbau.pp+github@gmail.com>2014-08-03 11:50:19 +1000
commit7df277115ac009a671e0a68a27d4c9896bd81a7b (patch)
treed3f6ae3185fa42723d2d7998957113f949cd1dfd
parent75a39e0fb8fef20d72f7279686ec266bb9cec127 (diff)
downloadrust-7df277115ac009a671e0a68a27d4c9896bd81a7b.tar.gz
rust-7df277115ac009a671e0a68a27d4c9896bd81a7b.zip
core: add a reverse method to Ordering.
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 8db59bd370e..398421681af 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);