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

core: add a reverse method to Ordering. #16155

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
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
34 changes: 34 additions & 0 deletions src/libcore/cmp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,40 @@ pub enum Ordering {
Greater = 1i,
}

impl Ordering {
/// Reverse the `Ordering`, so that `Less` becomes `Greater` and
/// vice versa.
///
/// # Example
///
/// ```rust
/// assert_eq!(Less.reverse(), Greater);
/// assert_eq!(Equal.reverse(), Equal);
/// assert_eq!(Greater.reverse(), Less);
///
///
/// let mut data = &mut [2u, 10, 5, 8];
///
/// // sort the array from largest to smallest.
/// data.sort_by(|a, b| a.cmp(b).reverse());
///
/// assert_eq!(data, &mut [10u, 8, 5, 2]);
/// ```
#[inline]
#[experimental]
pub fn reverse(self) -> Ordering {
unsafe {
// this compiles really nicely (to a single instruction);
// an explicit match has a pile of branches and
// comparisons.
//
// NB. it is safe because of the explicit discriminants
// given above.
::mem::transmute::<_, Ordering>(-(self as i8))
}
}
}

/// Trait for types that form a [total order](
/// https://en.wikipedia.org/wiki/Total_order).
///
Expand Down
7 changes: 7 additions & 0 deletions src/libcoretest/cmp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ fn test_mut_int_totalord() {
assert_eq!((&mut 12i).cmp(&&mut -5), Greater);
}

#[test]
fn test_ordering_reverse() {
assert_eq!(Less.reverse(), Greater);
assert_eq!(Equal.reverse(), Equal);
assert_eq!(Greater.reverse(), Less);
}

#[test]
fn test_ordering_order() {
assert!(Less < Equal);
Expand Down