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

Add min and max methods to Ord and PartialOrd #16067

Closed
wants to merge 1 commit into from
Closed
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
52 changes: 51 additions & 1 deletion src/libcore/cmp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@

#![stable]

use option::{Option, Some};
use option::{None, Option, Some};

/// Trait for values that can be compared for equality and inequality.
///
Expand Down Expand Up @@ -122,6 +122,30 @@ pub trait Ord: Eq + PartialOrd {
/// assert_eq!( 5u.cmp(&5), Equal); // because 5 == 5
/// ```
fn cmp(&self, other: &Self) -> Ordering;

/// This method returns the greater of two values.
///
/// If the values are equal, the value which this method was called on
/// (self) is returned.
#[inline]
fn max<'a>(&'a self, other: &'a Self) -> &'a Self {
match self.cmp(other) {
Less => other,
_ => self,
}
}

/// This method returns the lesser of two values.
///
/// If the values are equal, the value which this method was called on
/// (self) is returned.
#[inline]
fn min<'a>(&'a self, other: &'a Self) -> &'a Self {
match self.cmp(other) {
Greater => other,
_ => self,
}
}
}

#[unstable = "Trait is unstable."]
Expand Down Expand Up @@ -207,6 +231,32 @@ pub trait PartialOrd: PartialEq {
_ => false,
}
}

/// This method returns the greater of two values, if they can be compared.
///
/// If the values are equal, the value which this method was called on
/// (self) is returned.
#[inline]
fn partial_max<'a>(&'a self, other: &'a Self) -> Option<&'a Self> {
match self.partial_cmp(other) {
Some(Less) => Some(other),
Some(_) => Some(self),
_ => None,
}
}

/// This method returns the lesser of two values, if they can be compared.
///
/// If the values are equal, the value which this method was called on
/// (self) is returned.
#[inline]
fn partial_min<'a>(&'a self, other: &'a Self) -> Option<&'a Self> {
match self.partial_cmp(other) {
Some(Greater) => Some(other),
Some(_) => Some(self),
_ => None,
}
}
}

/// The equivalence relation. Two values may be equivalent even if they are
Expand Down