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