about summary refs log tree commit diff
diff options
context:
space:
mode:
authorCorey Farwell <coreyf@rwell.org>2017-03-29 08:57:03 -0400
committerGitHub <noreply@github.com>2017-03-29 08:57:03 -0400
commit978c90654b7a01ca38d78ed379c284f0ba9bba72 (patch)
tree3cebcd9006644f0475e26e001b64f6d57d47b461
parentabf5592510156e08b4de3830afaabbc0b65ce054 (diff)
parent5d3695362f795a45947e92c77f910dcacba575ea (diff)
downloadrust-978c90654b7a01ca38d78ed379c284f0ba9bba72.tar.gz
rust-978c90654b7a01ca38d78ed379c284f0ba9bba72.zip
Rollup merge of #40720 - mitsuhiko:feature/rev-key, r=BurntSushi
Added core::cmp::Reverse for sort_by_key reverse sorting

I'm not sure if this is the best way to go about proposing this feature but it's pretty useful. It allows you to use `sort_by_key` and return tuples where a single item is then reversed to how it normally sorts.

I quite miss something like this in Rust currently though I'm not sure if this is the best way to implement it.
-rw-r--r--src/libcore/cmp.rs35
1 files changed, 35 insertions, 0 deletions
diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs
index 7db35359a1f..dc2398b22ac 100644
--- a/src/libcore/cmp.rs
+++ b/src/libcore/cmp.rs
@@ -322,6 +322,41 @@ impl Ordering {
     }
 }
 
+/// A helper struct for reverse ordering.
+///
+/// This struct is a helper to be used with functions like `Vec::sort_by_key` and
+/// can be used to reverse order a part of a key.
+///
+/// Example usage:
+///
+/// ```
+/// #![feature(reverse_cmp_key)]
+/// use std::cmp::Reverse;
+///
+/// let mut v = vec![1, 2, 3, 4, 5, 6];
+/// v.sort_by_key(|&num| (num > 3, Reverse(num)));
+/// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
+/// ```
+#[derive(PartialEq, Eq, Debug)]
+#[unstable(feature = "reverse_cmp_key", issue = "40893")]
+pub struct Reverse<T>(pub T);
+
+#[unstable(feature = "reverse_cmp_key", issue = "40893")]
+impl<T: PartialOrd> PartialOrd for Reverse<T> {
+    #[inline]
+    fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
+        other.0.partial_cmp(&self.0)
+    }
+}
+
+#[unstable(feature = "reverse_cmp_key", issue = "40893")]
+impl<T: Ord> Ord for Reverse<T> {
+    #[inline]
+    fn cmp(&self, other: &Reverse<T>) -> Ordering {
+        other.0.cmp(&self.0)
+    }
+}
+
 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
 ///
 /// An order is a total order if it is (for all `a`, `b` and `c`):