lsm_tree/
windows.rs

1pub trait GrowingWindowsExt<T> {
2    fn growing_windows<'a>(&'a self) -> impl Iterator<Item = &'a [T]>
3    where
4        T: 'a;
5}
6
7impl<T> GrowingWindowsExt<T> for [T] {
8    fn growing_windows<'a>(&'a self) -> impl Iterator<Item = &'a [T]>
9    where
10        T: 'a,
11    {
12        (1..=self.len()).flat_map(|size| self.windows(size))
13    }
14}
15
16pub trait ShrinkingWindowsExt<T> {
17    fn shrinking_windows<'a>(&'a self) -> impl Iterator<Item = &'a [T]>
18    where
19        T: 'a;
20}
21
22impl<T> ShrinkingWindowsExt<T> for [T] {
23    fn shrinking_windows<'a>(&'a self) -> impl Iterator<Item = &'a [T]>
24    where
25        T: 'a,
26    {
27        (1..=self.len()).rev().flat_map(|size| self.windows(size))
28    }
29}
30
31#[cfg(test)]
32mod tests {
33    use super::*;
34
35    #[test]
36    #[allow(clippy::unwrap_used)]
37    fn test_growing_windows() {
38        let a = [1, 2, 3, 4, 5];
39
40        let mut windows = a.growing_windows();
41
42        assert_eq!(&[1], windows.next().unwrap());
43        assert_eq!(&[2], windows.next().unwrap());
44        assert_eq!(&[3], windows.next().unwrap());
45        assert_eq!(&[4], windows.next().unwrap());
46        assert_eq!(&[5], windows.next().unwrap());
47
48        assert_eq!(&[1, 2], windows.next().unwrap());
49        assert_eq!(&[2, 3], windows.next().unwrap());
50        assert_eq!(&[3, 4], windows.next().unwrap());
51        assert_eq!(&[4, 5], windows.next().unwrap());
52
53        assert_eq!(&[1, 2, 3], windows.next().unwrap());
54        assert_eq!(&[2, 3, 4], windows.next().unwrap());
55        assert_eq!(&[3, 4, 5], windows.next().unwrap());
56
57        assert_eq!(&[1, 2, 3, 4], windows.next().unwrap());
58        assert_eq!(&[2, 3, 4, 5], windows.next().unwrap());
59
60        assert_eq!(&[1, 2, 3, 4, 5], windows.next().unwrap());
61    }
62
63    #[test]
64    #[allow(clippy::unwrap_used)]
65    fn test_shrinking_windows() {
66        let a = [1, 2, 3, 4, 5];
67
68        let mut windows = a.shrinking_windows();
69
70        assert_eq!(&[1, 2, 3, 4, 5], windows.next().unwrap());
71
72        assert_eq!(&[1, 2, 3, 4], windows.next().unwrap());
73        assert_eq!(&[2, 3, 4, 5], windows.next().unwrap());
74
75        assert_eq!(&[1, 2, 3], windows.next().unwrap());
76        assert_eq!(&[2, 3, 4], windows.next().unwrap());
77        assert_eq!(&[3, 4, 5], windows.next().unwrap());
78
79        assert_eq!(&[1, 2], windows.next().unwrap());
80        assert_eq!(&[2, 3], windows.next().unwrap());
81        assert_eq!(&[3, 4], windows.next().unwrap());
82        assert_eq!(&[4, 5], windows.next().unwrap());
83
84        assert_eq!(&[1], windows.next().unwrap());
85        assert_eq!(&[2], windows.next().unwrap());
86        assert_eq!(&[3], windows.next().unwrap());
87        assert_eq!(&[4], windows.next().unwrap());
88        assert_eq!(&[5], windows.next().unwrap());
89    }
90}