Skip to content

Commit

Permalink
implement all min/max fns in terms of <=/is_le
Browse files Browse the repository at this point in the history
  • Loading branch information
WaffleLapkin committed Jan 30, 2025
1 parent 99768c8 commit f9d2512
Showing 1 changed file with 7 additions and 13 deletions.
20 changes: 7 additions & 13 deletions library/core/src/cmp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -981,7 +981,7 @@ pub trait Ord: Eq + PartialOrd<Self> {
where
Self: Sized,
{
max_by(self, other, Ord::cmp)
if self <= other { other } else { self }
}

/// Compares and returns the minimum of two values.
Expand All @@ -1002,7 +1002,7 @@ pub trait Ord: Eq + PartialOrd<Self> {
where
Self: Sized,
{
min_by(self, other, Ord::cmp)
if self <= other { self } else { other }
}

/// Restrict a value to a certain interval.
Expand Down Expand Up @@ -1441,10 +1441,7 @@ pub fn min<T: Ord>(v1: T, v2: T) -> T {
#[must_use]
#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
pub fn min_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
match compare(&v1, &v2) {
Ordering::Less | Ordering::Equal => v1,
Ordering::Greater => v2,
}
if compare(&v1, &v2).is_le() { v1 } else { v2 }
}

/// Returns the element that gives the minimum value from the specified function.
Expand All @@ -1466,7 +1463,7 @@ pub fn min_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
#[must_use]
#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
pub fn min_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
min_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
if f(&v1) <= f(&v2) { v1 } else { v2 }
}

/// Compares and returns the maximum of two values.
Expand Down Expand Up @@ -1510,10 +1507,7 @@ pub fn max<T: Ord>(v1: T, v2: T) -> T {
#[must_use]
#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
pub fn max_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
match compare(&v1, &v2) {
Ordering::Less | Ordering::Equal => v2,
Ordering::Greater => v1,
}
if compare(&v1, &v2).is_le() { v2 } else { v1 }
}

/// Returns the element that gives the maximum value from the specified function.
Expand All @@ -1535,7 +1529,7 @@ pub fn max_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
#[must_use]
#[stable(feature = "cmp_min_max_by", since = "1.53.0")]
pub fn max_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
max_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
if f(&v1) <= f(&v2) { v2 } else { v1 }
}

/// Compares and sorts two values, returning minimum and maximum.
Expand Down Expand Up @@ -1620,7 +1614,7 @@ where
F: FnMut(&T) -> K,
K: Ord,
{
minmax_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
if f(&v1) <= f(&v2) { [v1, v2] } else { [v2, v1] }
}

// Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
Expand Down

0 comments on commit f9d2512

Please sign in to comment.