Skip to content

Commit

Permalink
core: add a reverse method to Ordering.
Browse files Browse the repository at this point in the history
This flips the comparison and is designed to be used when sorting etc.
  • Loading branch information
huonw committed Aug 3, 2014
1 parent 75a39e0 commit 7df2771
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/libcore/cmp.rs
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
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

5 comments on commit 7df2771

@bors
Copy link
Contributor

@bors bors commented on 7df2771 Aug 3, 2014

Choose a reason for hiding this comment

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

saw approval from alexcrichton
at huonw@7df2771

@bors
Copy link
Contributor

@bors bors commented on 7df2771 Aug 3, 2014

Choose a reason for hiding this comment

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

merging huonw/rust/Ordering-reverse = 7df2771 into auto

@bors
Copy link
Contributor

@bors bors commented on 7df2771 Aug 3, 2014

Choose a reason for hiding this comment

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

huonw/rust/Ordering-reverse = 7df2771 merged ok, testing candidate = ce01b4b

@bors
Copy link
Contributor

@bors bors commented on 7df2771 Aug 3, 2014

Choose a reason for hiding this comment

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

fast-forwarding master to auto = ce01b4b

Please sign in to comment.