non_empty_iter/
flat_map.rs

1//! Mapping non-empty iterators' items to non-empty iterators that have their items yielded.
2
3use core::iter;
4
5use crate::non_empty::{IntoNonEmptyIterator, NonEmptyIterator};
6
7/// Represents non-empty iterators which map items to non-empty iterators that have
8/// their items yielded.
9///
10/// This `struct` is created by the [`flat_map`] method on [`NonEmptyIterator`].
11/// See its documentation for more.
12///
13/// [`flat_map`]: NonEmptyIterator::flat_map
14#[derive(Debug, Clone)]
15#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
16pub struct FlatMap<I: NonEmptyIterator, J: IntoNonEmptyIterator, F: FnMut(I::Item) -> J> {
17    non_empty: I,
18    function: F,
19}
20
21impl<I: NonEmptyIterator, J: IntoNonEmptyIterator, F: FnMut(I::Item) -> J> FlatMap<I, J, F> {
22    /// Constructs [`Self`].
23    pub const fn new(non_empty: I, function: F) -> Self {
24        Self {
25            non_empty,
26            function,
27        }
28    }
29}
30
31impl<I: NonEmptyIterator, J: IntoNonEmptyIterator, F: FnMut(I::Item) -> J> IntoIterator
32    for FlatMap<I, J, F>
33{
34    type Item = J::Item;
35
36    type IntoIter = iter::FlatMap<I::IntoIter, J, F>;
37
38    fn into_iter(self) -> Self::IntoIter {
39        self.non_empty.into_iter().flat_map(self.function)
40    }
41}
42
43unsafe impl<I: NonEmptyIterator, J: IntoNonEmptyIterator, F: FnMut(I::Item) -> J> NonEmptyIterator
44    for FlatMap<I, J, F>
45{
46}