1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#![allow(clippy::wrong_self_convention)]
use std::cmp;
/// [`Iterator`] extension trait
pub trait IteratorExt: Iterator {
/// Returns `true` iff the iterator is a strict total order. This implies
/// the iterator is sorted and all elements are unique.
///
/// ```ignore
/// [x_1, ..., x_n].is_strict_total_order()
/// := x_1 < x_2 < ... < x_n
/// ```
///
/// ### Examples
///
/// ```rust
/// use std::iter;
/// use lexe_std::iter::IteratorExt;
///
/// assert!(iter::empty::<u32>().is_strict_total_order());
/// assert!(&[1].iter().is_strict_total_order());
/// assert!(&[1, 2, 6].iter().is_strict_total_order());
///
/// assert!(!&[2, 1].iter().is_strict_total_order());
/// assert!(!&[1, 2, 2, 3].iter().is_strict_total_order());
/// ```
fn is_strict_total_order(mut self) -> bool
where
Self: Sized,
Self::Item: PartialOrd,
{
let mut prev = match self.next() {
Some(first) => first,
// Trivially true
None => return true,
};
for next in self {
if let Some(cmp::Ordering::Greater)
| Some(cmp::Ordering::Equal)
| None = prev.partial_cmp(&next)
{
return false;
}
prev = next;
}
true
}
/// Returns `true` iff the iterator is a strict total order according to the
/// key extraction function `f`.
///
/// ```ignore
/// [x_1, ..., x_n].is_strict_total_order_by_key(f)
/// := f(x_1) < f(x_2) < ... < f(x_n)
/// ```
fn is_strict_total_order_by_key<F, K>(self, f: F) -> bool
where
Self: Sized,
F: FnMut(Self::Item) -> K,
K: PartialOrd,
{
self.map(f).is_strict_total_order()
}
/// Return the minimum and maximum elements of an [`Iterator`], in one pass.
#[inline]
fn min_max(mut self) -> Option<(Self::Item, Self::Item)>
where
Self: Sized,
Self::Item: Copy + Ord,
{
let first = self.next()?;
let init = (first, first);
Some(self.fold(init, |acc, elt| (acc.0.min(elt), acc.1.max(elt))))
}
}
impl<I: Iterator> IteratorExt for I {}
#[cfg(test)]
mod test {
use proptest::{prop_assert_eq, proptest};
use super::*;
#[test]
fn test_iter_min_max() {
proptest!(|(xs: Vec<u8>)| {
let actual = xs.iter().copied().min_max();
let expected_min = xs.iter().copied().min();
let expected_max = xs.iter().copied().max();
let expected = expected_min.zip(expected_max);
prop_assert_eq!(actual, expected);
});
}
}