diff options
| author | Armin Ronacher <armin.ronacher@active-4.com> | 2017-03-22 00:01:37 +0100 |
|---|---|---|
| committer | Armin Ronacher <armin.ronacher@active-4.com> | 2017-03-22 00:01:37 +0100 |
| commit | d7d4e670ed53883672d8c4458226d91dcc731569 (patch) | |
| tree | 93ae0fa2f32fe9df813c5fe7d929296c0af44ebe | |
| parent | 134c4a0f08a3d1f55ea8968fbe728fa935c71698 (diff) | |
Added core::cmp::Reverse for sort_by_key reverse sorting
| -rw-r--r-- | src/libcore/cmp.rs | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index cb39796eecd..d87615ad9a2 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -322,6 +322,40 @@ 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: +/// +/// ``` +/// 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)] +#[stable(feature = "rust1", since = "1.8.0")] +pub struct Reverse<T: Ord + PartialOrd + Eq + PartialEq>(pub T); + +#[stable(feature = "rust1", since = "1.8.0")] +impl<T: Ord + PartialOrd + Eq + PartialEq> PartialOrd for Reverse<T> { + #[inline] + fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> { + other.0.partial_cmp(&self.0) + } +} + +#[stable(feature = "rust1", since = "1.8.0")] +impl<T: Ord + PartialOrd + Eq + PartialEq> 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`): |
