rust_3d/
skip_empty.rs

1/*
2Copyright 2020 Martin Buck
3
4Permission is hereby granted, free of charge, to any person obtaining a copy
5of this software and associated documentation files (the "Software"),
6to deal in the Software without restriction, including without limitation the
7rights to use, copy, modify, merge, publish, distribute, sublicense,
8and/or sell copies of the Software, and to permit persons to whom the Software
9is furnished to do so, subject to the following conditions:
10
11The above copyright notice and this permission notice shall
12be included all copies or substantial portions of the Software.
13
14THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
20OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21*/
22
23//! Iterator that skips empty elements
24
25/// Iterator that skips empty elements
26#[derive(Clone)]
27pub struct SkipEmpty<'a, T, I>
28where
29    T: 'a,
30    I: Iterator<Item = &'a [T]>,
31{
32    iterator: I,
33}
34
35impl<'a, T, I> SkipEmpty<'a, T, I>
36where
37    T: 'a,
38    I: Iterator<Item = &'a [T]>,
39{
40    pub fn new(iterator: I) -> Self {
41        Self { iterator }
42    }
43}
44
45impl<'a, T, I> Iterator for SkipEmpty<'a, T, I>
46where
47    T: 'a,
48    I: Iterator<Item = &'a [T]>,
49{
50    type Item = &'a [T];
51
52    fn next(&mut self) -> Option<Self::Item> {
53        loop {
54            match self.iterator.next() {
55                None => return None,
56                Some([]) => continue,
57                x @ Some(_) => return x,
58            }
59        }
60    }
61}
62
63//------------------------------------------------------------------------------
64
65/// Utility trait to easily spawn the SkipEmpty iterator
66pub trait IsSkipEmptyProducer<'a, T>: Iterator<Item = &'a [T]>
67where
68    T: 'a,
69    Self: Sized,
70{
71    fn skip_empty(self) -> SkipEmpty<'a, T, Self>;
72}
73
74impl<'a, T, F> IsSkipEmptyProducer<'a, T> for std::slice::Split<'a, T, F>
75where
76    F: FnMut(&T) -> bool,
77{
78    fn skip_empty(self) -> SkipEmpty<'a, T, Self> {
79        SkipEmpty::new(self)
80    }
81}