From f9d25129f30d94c5b3fcfc90a7945a02e168e838 Mon Sep 17 00:00:00 2001 From: Waffle Lapkin Date: Thu, 30 Jan 2025 17:27:16 +0100 Subject: [PATCH] implement all min/max fns in terms of `<=`/`is_le` --- library/core/src/cmp.rs | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/library/core/src/cmp.rs b/library/core/src/cmp.rs index 97974d195fec6..460fe06f3be7e 100644 --- a/library/core/src/cmp.rs +++ b/library/core/src/cmp.rs @@ -981,7 +981,7 @@ pub trait Ord: Eq + PartialOrd { where Self: Sized, { - max_by(self, other, Ord::cmp) + if self <= other { other } else { self } } /// Compares and returns the minimum of two values. @@ -1002,7 +1002,7 @@ pub trait Ord: Eq + PartialOrd { where Self: Sized, { - min_by(self, other, Ord::cmp) + if self <= other { self } else { other } } /// Restrict a value to a certain interval. @@ -1441,10 +1441,7 @@ pub fn min(v1: T, v2: T) -> T { #[must_use] #[stable(feature = "cmp_min_max_by", since = "1.53.0")] pub fn min_by 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. @@ -1466,7 +1463,7 @@ pub fn min_by 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 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. @@ -1510,10 +1507,7 @@ pub fn max(v1: T, v2: T) -> T { #[must_use] #[stable(feature = "cmp_min_max_by", since = "1.53.0")] pub fn max_by 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. @@ -1535,7 +1529,7 @@ pub fn max_by 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 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. @@ -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