Crate array_builder[][src]

Expand description

ArrayBuilder makes it easy to dynamically build arrays safely and efficiently.

use array_builder::ArrayBuilder;

struct ArrayIterator<I: Iterator, const N: usize> {
    builder: ArrayBuilder<I::Item, N>,
    iter: I,
}

impl<I: Iterator, const N: usize> Iterator for ArrayIterator<I, N> {
    type Item = [I::Item; N];

    fn next(&mut self) -> Option<Self::Item> {
        for _ in self.builder.len()..N {
            self.builder.push(self.iter.next()?);
        }
        self.builder.take().build().ok()
    }
}

impl<I: Iterator, const N: usize> ArrayIterator<I, N> {
    pub fn new(i: impl IntoIterator<IntoIter=I>) -> Self {
        Self {
            builder: ArrayBuilder::new(),
            iter: i.into_iter(),
        }
    }

    pub fn remaining(&self) -> &[I::Item] {
        &self.builder
    }
}

let mut i = ArrayIterator::new(0..10);
assert_eq!(Some([0, 1, 2, 3]), i.next());
assert_eq!(Some([4, 5, 6, 7]), i.next());
assert_eq!(None, i.next());
assert_eq!(&[8, 9], i.remaining());

Structs

ArrayBuilder

ArrayBuilder makes it easy to dynamically build arrays safely and efficiently.