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
#![no_std]
//! Versions of [`FlatMap`] and [`Flatten`] that know their inner iterators’ size in advance.
//! Note that [`core`] & `std` already provide this functionality for some types through a hack using specialization.
//! This crate’s contribution is that the trait [`ConstSizeIntoIterator`] is public and the functionality is therefore extensible.
//!
//! To use, just `use const_size_flatten::ConstSizeFlattenIteratorExtension`.
//!
//! [`FlatMap`]: core::iter::FlatMap
//! [`Flatten`]: core::iter::Flatten

mod flatmap;
pub use flatmap::*;
mod flatten;
pub use flatten::*;
mod flatten_base;

/// Implementors of this trait promise that all iterators they produce always produce the same number of elements.
/// This number is given by the associated constant [`SIZE`].
/// The iterator they produce must always know its remaining length (implement [`ExactSizeIterator`]).
///
/// [`SIZE`]: ConstSizeIntoIterator::SIZE
pub trait ConstSizeIntoIterator: IntoIterator
where
    Self::IntoIter: ExactSizeIterator,
{
    const SIZE: usize;
}

impl<T, const N: usize> ConstSizeIntoIterator for [T; N] {
    const SIZE: usize = N;
}

impl<T, const N: usize> ConstSizeIntoIterator for &[T; N] {
    const SIZE: usize = N;
}

impl<T, const N: usize> ConstSizeIntoIterator for &mut [T; N] {
    const SIZE: usize = N;
}

/// Convenience `trait` that allows you to construct [`ConstSizeFlatten`] and [`ConstSizeFlatMap`].
pub trait ConstSizeIteratorExtension {
    /// Construct a [`ConstSizeFlatten`] from an [`Iterator`].
    /// This is the `impl` version of [`const_size_flatten`]
    fn const_size_flatten(self) -> ConstSizeFlatten<Self>
    where
        Self: Iterator,
        Self::Item: ConstSizeIntoIterator,
        <Self::Item as IntoIterator>::IntoIter: ExactSizeIterator,
        Self: Sized,
    {
        const_size_flatten(self)
    }

    /// Construct a [`ConstSizeFlatMap`] from an [`Iterator`].
    /// This is the `impl` version of [`const_size_flat_map`]
    fn const_size_flat_map<U, F>(self, f: F) -> ConstSizeFlatMap<Self, U, F>
    where
        Self: Iterator,
        F: FnMut(Self::Item) -> U,
        U: ConstSizeIntoIterator,
        U::IntoIter: ExactSizeIterator,
        Self: Sized,
    {
        const_size_flat_map(self, f)
    }
}

impl<T> ConstSizeIteratorExtension for T {}