1#![cfg(feature = "use_alloc")]
2use alloc::{vec, vec::Vec};
3use std::cmp::Ordering;
4
5/// Implementation guts for `min_set`, `min_set_by`, and `min_set_by_key`.
6pub fn min_set_impl<I, K, F, Compare>(
7 mut it: I,
8 mut key_for: F,
9 mut compare: Compare,
10) -> Vec<I::Item>
11where
12 I: Iterator,
13 F: FnMut(&I::Item) -> K,
14 Compare: FnMut(&I::Item, &I::Item, &K, &K) -> Ordering,
15{
16 match it.next() {
17 None => Vec::new(),
18 Some(element: ::Item) => {
19 let mut current_key: K = key_for(&element);
20 let mut result: Vec<::Item> = vec![element];
21 it.for_each(|element: ::Item| {
22 let key: K = key_for(&element);
23 match compare(&element, &result[0], &key, &current_key) {
24 Ordering::Less => {
25 result.clear();
26 result.push(element);
27 current_key = key;
28 }
29 Ordering::Equal => {
30 result.push(element);
31 }
32 Ordering::Greater => {}
33 }
34 });
35 result
36 }
37 }
38}
39
40/// Implementation guts for `ax_set`, `max_set_by`, and `max_set_by_key`.
41pub fn max_set_impl<I, K, F, Compare>(it: I, key_for: F, mut compare: Compare) -> Vec<I::Item>
42where
43 I: Iterator,
44 F: FnMut(&I::Item) -> K,
45 Compare: FnMut(&I::Item, &I::Item, &K, &K) -> Ordering,
46{
47 min_set_impl(it, key_for, |it1: &::Item, it2: &::Item, key1: &K, key2: &K| {
48 compare(it2, it1, key2, key1)
49 })
50}
51