Skip to content

Commit 5349e69

Browse files
committed
Auto merge of #64047 - timvermeulen:cmp_min_max_by, r=cuviper
Add `cmp::{min_by, min_by_key, max_by, max_by_key}` This adds the following functions to `core::cmp`: - `min_by` - `min_by_key` - `max_by` - `max_by_key` `min_by` and `max_by` are somewhat trivial to implement, but not entirely because `min_by` returns the first value in case the two are equal (and `max_by` the second). `min` and `max` can be implemented in terms of `min_by` and `max_by`, but not as easily the other way around. To give an example of why I think these functions could be useful: the `Iterator::{min_by, min_by_key, max_by, max_by_key}` methods all currently hard-code the behavior mentioned above which is an ever so small duplication of logic. If we delegate them to `cmp::{min_by, max_by}` methods instead, we get the correct behavior for free. (edit: this is now included in the PR) I added `min_by_key` / `max_by_key` for consistency's sake but I wouldn't mind removing them. I don't have a particular use case in mind for them, and `min_by` / `max_by` seem to be more useful. Tracking issue: #64460
2 parents 97e58c0 + 7217591 commit 5349e69

File tree

4 files changed

+129
-34
lines changed

4 files changed

+129
-34
lines changed

src/libcore/cmp.rs

+88-2
Original file line numberDiff line numberDiff line change
@@ -570,7 +570,7 @@ pub trait Ord: Eq + PartialOrd<Self> {
570570
#[inline]
571571
fn max(self, other: Self) -> Self
572572
where Self: Sized {
573-
if other >= self { other } else { self }
573+
max_by(self, other, Ord::cmp)
574574
}
575575

576576
/// Compares and returns the minimum of two values.
@@ -587,7 +587,7 @@ pub trait Ord: Eq + PartialOrd<Self> {
587587
#[inline]
588588
fn min(self, other: Self) -> Self
589589
where Self: Sized {
590-
if self <= other { self } else { other }
590+
min_by(self, other, Ord::cmp)
591591
}
592592

593593
/// Restrict a value to a certain interval.
@@ -898,6 +898,49 @@ pub fn min<T: Ord>(v1: T, v2: T) -> T {
898898
v1.min(v2)
899899
}
900900

901+
/// Returns the minimum of two values with respect to the specified comparison function.
902+
///
903+
/// Returns the first argument if the comparison determines them to be equal.
904+
///
905+
/// # Examples
906+
///
907+
/// ```
908+
/// #![feature(cmp_min_max_by)]
909+
///
910+
/// use std::cmp;
911+
///
912+
/// assert_eq!(cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 1);
913+
/// assert_eq!(cmp::min_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
914+
/// ```
915+
#[inline]
916+
#[unstable(feature = "cmp_min_max_by", issue = "64460")]
917+
pub fn min_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
918+
match compare(&v1, &v2) {
919+
Ordering::Less | Ordering::Equal => v1,
920+
Ordering::Greater => v2,
921+
}
922+
}
923+
924+
/// Returns the element that gives the minimum value from the specified function.
925+
///
926+
/// Returns the first argument if the comparison determines them to be equal.
927+
///
928+
/// # Examples
929+
///
930+
/// ```
931+
/// #![feature(cmp_min_max_by)]
932+
///
933+
/// use std::cmp;
934+
///
935+
/// assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1);
936+
/// assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2);
937+
/// ```
938+
#[inline]
939+
#[unstable(feature = "cmp_min_max_by", issue = "64460")]
940+
pub fn min_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
941+
min_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
942+
}
943+
901944
/// Compares and returns the maximum of two values.
902945
///
903946
/// Returns the second argument if the comparison determines them to be equal.
@@ -918,6 +961,49 @@ pub fn max<T: Ord>(v1: T, v2: T) -> T {
918961
v1.max(v2)
919962
}
920963

964+
/// Returns the maximum of two values with respect to the specified comparison function.
965+
///
966+
/// Returns the second argument if the comparison determines them to be equal.
967+
///
968+
/// # Examples
969+
///
970+
/// ```
971+
/// #![feature(cmp_min_max_by)]
972+
///
973+
/// use std::cmp;
974+
///
975+
/// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
976+
/// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2);
977+
/// ```
978+
#[inline]
979+
#[unstable(feature = "cmp_min_max_by", issue = "64460")]
980+
pub fn max_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
981+
match compare(&v1, &v2) {
982+
Ordering::Less | Ordering::Equal => v2,
983+
Ordering::Greater => v1,
984+
}
985+
}
986+
987+
/// Returns the element that gives the maximum value from the specified function.
988+
///
989+
/// Returns the second argument if the comparison determines them to be equal.
990+
///
991+
/// # Examples
992+
///
993+
/// ```
994+
/// #![feature(cmp_min_max_by)]
995+
///
996+
/// use std::cmp;
997+
///
998+
/// assert_eq!(cmp::max_by_key(-2, 1, |x: &i32| x.abs()), -2);
999+
/// assert_eq!(cmp::max_by_key(-2, 2, |x: &i32| x.abs()), 2);
1000+
/// ```
1001+
#[inline]
1002+
#[unstable(feature = "cmp_min_max_by", issue = "64460")]
1003+
pub fn max_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
1004+
max_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
1005+
}
1006+
9211007
// Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
9221008
mod impls {
9231009
use crate::cmp::Ordering::{self, Less, Greater, Equal};

src/libcore/iter/traits/iterator.rs

+17-31
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::cmp::Ordering;
1+
use crate::cmp::{self, Ordering};
22
use crate::ops::{Add, Try};
33

44
use super::super::LoopState;
@@ -2223,13 +2223,12 @@ pub trait Iterator {
22232223
move |x| (f(&x), x)
22242224
}
22252225

2226-
// switch to y even if it is only equal, to preserve stability.
22272226
#[inline]
2228-
fn select<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> bool {
2229-
x_p <= y_p
2227+
fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2228+
x_p.cmp(y_p)
22302229
}
22312230

2232-
let (_, x) = select_fold1(self.map(key(f)), select)?;
2231+
let (_, x) = self.map(key(f)).max_by(compare)?;
22332232
Some(x)
22342233
}
22352234

@@ -2252,13 +2251,12 @@ pub trait Iterator {
22522251
fn max_by<F>(self, compare: F) -> Option<Self::Item>
22532252
where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
22542253
{
2255-
// switch to y even if it is only equal, to preserve stability.
22562254
#[inline]
2257-
fn select<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(&T, &T) -> bool {
2258-
move |x, y| compare(x, y) != Ordering::Greater
2255+
fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2256+
move |x, y| cmp::max_by(x, y, &mut compare)
22592257
}
22602258

2261-
select_fold1(self, select(compare))
2259+
fold1(self, fold(compare))
22622260
}
22632261

22642262
/// Returns the element that gives the minimum value from the
@@ -2285,13 +2283,12 @@ pub trait Iterator {
22852283
move |x| (f(&x), x)
22862284
}
22872285

2288-
// only switch to y if it is strictly smaller, to preserve stability.
22892286
#[inline]
2290-
fn select<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> bool {
2291-
x_p > y_p
2287+
fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2288+
x_p.cmp(y_p)
22922289
}
22932290

2294-
let (_, x) = select_fold1(self.map(key(f)), select)?;
2291+
let (_, x) = self.map(key(f)).min_by(compare)?;
22952292
Some(x)
22962293
}
22972294

@@ -2314,13 +2311,12 @@ pub trait Iterator {
23142311
fn min_by<F>(self, compare: F) -> Option<Self::Item>
23152312
where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
23162313
{
2317-
// only switch to y if it is strictly smaller, to preserve stability.
23182314
#[inline]
2319-
fn select<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(&T, &T) -> bool {
2320-
move |x, y| compare(x, y) == Ordering::Greater
2315+
fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2316+
move |x, y| cmp::min_by(x, y, &mut compare)
23212317
}
23222318

2323-
select_fold1(self, select(compare))
2319+
fold1(self, fold(compare))
23242320
}
23252321

23262322

@@ -2958,28 +2954,18 @@ pub trait Iterator {
29582954
}
29592955
}
29602956

2961-
/// Select an element from an iterator based on the given "comparison"
2962-
/// function.
2963-
///
2964-
/// This is an idiosyncratic helper to try to factor out the
2965-
/// commonalities of {max,min}{,_by}. In particular, this avoids
2966-
/// having to implement optimizations several times.
2957+
/// Fold an iterator without having to provide an initial value.
29672958
#[inline]
2968-
fn select_fold1<I, F>(mut it: I, f: F) -> Option<I::Item>
2959+
fn fold1<I, F>(mut it: I, f: F) -> Option<I::Item>
29692960
where
29702961
I: Iterator,
2971-
F: FnMut(&I::Item, &I::Item) -> bool,
2962+
F: FnMut(I::Item, I::Item) -> I::Item,
29722963
{
2973-
#[inline]
2974-
fn select<T>(mut f: impl FnMut(&T, &T) -> bool) -> impl FnMut(T, T) -> T {
2975-
move |sel, x| if f(&sel, &x) { x } else { sel }
2976-
}
2977-
29782964
// start with the first element as our selection. This avoids
29792965
// having to use `Option`s inside the loop, translating to a
29802966
// sizeable performance gain (6x in one case).
29812967
let first = it.next()?;
2982-
Some(it.fold(first, select(f)))
2968+
Some(it.fold(first, f))
29832969
}
29842970

29852971
#[stable(feature = "rust1", since = "1.0.0")]

src/libcore/tests/cmp.rs

+23-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use core::cmp::Ordering::{Less, Greater, Equal};
1+
use core::cmp::{self, Ordering::*};
22

33
#[test]
44
fn test_int_totalord() {
@@ -28,6 +28,28 @@ fn test_ord_max_min() {
2828
assert_eq!(1.min(1), 1);
2929
}
3030

31+
#[test]
32+
fn test_ord_min_max_by() {
33+
let f = |x: &i32, y: &i32| x.abs().cmp(&y.abs());
34+
assert_eq!(cmp::min_by(1, -1, f), 1);
35+
assert_eq!(cmp::min_by(1, -2, f), 1);
36+
assert_eq!(cmp::min_by(2, -1, f), -1);
37+
assert_eq!(cmp::max_by(1, -1, f), -1);
38+
assert_eq!(cmp::max_by(1, -2, f), -2);
39+
assert_eq!(cmp::max_by(2, -1, f), 2);
40+
}
41+
42+
#[test]
43+
fn test_ord_min_max_by_key() {
44+
let f = |x: &i32| x.abs();
45+
assert_eq!(cmp::min_by_key(1, -1, f), 1);
46+
assert_eq!(cmp::min_by_key(1, -2, f), 1);
47+
assert_eq!(cmp::min_by_key(2, -1, f), -1);
48+
assert_eq!(cmp::max_by_key(1, -1, f), -1);
49+
assert_eq!(cmp::max_by_key(1, -2, f), -2);
50+
assert_eq!(cmp::max_by_key(2, -1, f), 2);
51+
}
52+
3153
#[test]
3254
fn test_ordering_reverse() {
3355
assert_eq!(Less.reverse(), Greater);

src/libcore/tests/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
#![feature(iter_partition_in_place)]
3535
#![feature(iter_is_partitioned)]
3636
#![feature(iter_order_by)]
37+
#![feature(cmp_min_max_by)]
3738

3839
extern crate test;
3940

0 commit comments

Comments
 (0)