From d7d4e670ed53883672d8c4458226d91dcc731569 Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Wed, 22 Mar 2017 00:01:37 +0100 Subject: [PATCH] Added core::cmp::Reverse for sort_by_key reverse sorting --- src/libcore/cmp.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index cb39796eecd7..d87615ad9a2c 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(pub T); + +#[stable(feature = "rust1", since = "1.8.0")] +impl PartialOrd for Reverse { + #[inline] + fn partial_cmp(&self, other: &Reverse) -> Option { + other.0.partial_cmp(&self.0) + } +} + +#[stable(feature = "rust1", since = "1.8.0")] +impl Ord for Reverse { + #[inline] + fn cmp(&self, other: &Reverse) -> 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`):