Skip to content

Commit 978c906

Browse files
authored
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.
2 parents abf5592 + 5d36953 commit 978c906

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/libcore/cmp.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,41 @@ impl Ordering {
322322
}
323323
}
324324

325+
/// A helper struct for reverse ordering.
326+
///
327+
/// This struct is a helper to be used with functions like `Vec::sort_by_key` and
328+
/// can be used to reverse order a part of a key.
329+
///
330+
/// Example usage:
331+
///
332+
/// ```
333+
/// #![feature(reverse_cmp_key)]
334+
/// use std::cmp::Reverse;
335+
///
336+
/// let mut v = vec![1, 2, 3, 4, 5, 6];
337+
/// v.sort_by_key(|&num| (num > 3, Reverse(num)));
338+
/// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
339+
/// ```
340+
#[derive(PartialEq, Eq, Debug)]
341+
#[unstable(feature = "reverse_cmp_key", issue = "40893")]
342+
pub struct Reverse<T>(pub T);
343+
344+
#[unstable(feature = "reverse_cmp_key", issue = "40893")]
345+
impl<T: PartialOrd> PartialOrd for Reverse<T> {
346+
#[inline]
347+
fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
348+
other.0.partial_cmp(&self.0)
349+
}
350+
}
351+
352+
#[unstable(feature = "reverse_cmp_key", issue = "40893")]
353+
impl<T: Ord> Ord for Reverse<T> {
354+
#[inline]
355+
fn cmp(&self, other: &Reverse<T>) -> Ordering {
356+
other.0.cmp(&self.0)
357+
}
358+
}
359+
325360
/// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
326361
///
327362
/// An order is a total order if it is (for all `a`, `b` and `c`):

0 commit comments

Comments
 (0)