Skip to content

Commit d7d4e67

Browse files
committed
Added core::cmp::Reverse for sort_by_key reverse sorting
1 parent 134c4a0 commit d7d4e67

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/libcore/cmp.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,40 @@ 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+
/// use std::cmp::Reverse;
334+
///
335+
/// let mut v = vec![1, 2, 3, 4, 5, 6];
336+
/// v.sort_by_key(|&num| (num >= 3, Reverse(num)));
337+
/// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
338+
/// ```
339+
#[derive(PartialEq, Eq, Debug)]
340+
#[stable(feature = "rust1", since = "1.8.0")]
341+
pub struct Reverse<T: Ord + PartialOrd + Eq + PartialEq>(pub T);
342+
343+
#[stable(feature = "rust1", since = "1.8.0")]
344+
impl<T: Ord + PartialOrd + Eq + PartialEq> PartialOrd for Reverse<T> {
345+
#[inline]
346+
fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
347+
other.0.partial_cmp(&self.0)
348+
}
349+
}
350+
351+
#[stable(feature = "rust1", since = "1.8.0")]
352+
impl<T: Ord + PartialOrd + Eq + PartialEq> Ord for Reverse<T> {
353+
#[inline]
354+
fn cmp(&self, other: &Reverse<T>) -> Ordering {
355+
other.0.cmp(&self.0)
356+
}
357+
}
358+
325359
/// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
326360
///
327361
/// An order is a total order if it is (for all `a`, `b` and `c`):

0 commit comments

Comments
 (0)