Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added core::cmp::Reverse for sort_by_key reverse sorting #40720

Merged
merged 5 commits into from
Mar 29, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/libcore/cmp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we derive PartialEq and Eq here, when we are specifying custom implementations below?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no custom implementation for PartialEq, only for Ord and PartialOrd.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, of course. I don't know where my brain was. Sorry about that.

#[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`):
Expand Down