Trait IteratorConstChunks

Source
pub trait IteratorConstChunks {
    type Inner: Iterator;

    // Required method
    fn const_chunks<const N: usize>(self) -> ConstChunks<N, Self::Inner> ;
}
Expand description

An extension trait providing Iterators with the capability to iterate over const-sized arrays of items.

Required Associated Types§

Source

type Inner: Iterator

The type of iterator from which we take chunks.

Required Methods§

Source

fn const_chunks<const N: usize>(self) -> ConstChunks<N, Self::Inner>

This function returns an iterator over constant-length chunks of items, where the length is provided as a const-generic.

§Usage
use const_chunks::IteratorConstChunks;

let v = vec![1, 2, 3, 4, 5, 6];
let mut v_iter = v.into_iter().const_chunks::<2>();
assert_eq!(v_iter.next(), Some([1,2]));
assert_eq!(v_iter.next(), Some([3,4]));
assert_eq!(v_iter.next(), Some([5,6]));

When the number of items in the iterator cannot be divided exactly into chunks, then the iterator will be fully consumed, but the last chunk will not be yielded.

use const_chunks::IteratorConstChunks;

// Five items cannot fit into chunks of length 2!
let v = [1, 2, 3, 4, 5];

let mut v_iter = v.into_iter().const_chunks::<2>();
assert_eq!(v_iter.next(), Some([1, 2]));
assert_eq!(v_iter.next(), Some([3, 4]));

// `None`, even though there was still one item
assert_eq!(v_iter.next(), None);

To get the remaining items, you can use the ConstChunks::into_remainder method (see for more).

Note that trying to build chunks of size 0 will fail to compile:

use const_chunks::IteratorConstChunks;

let _ = vec![1, 2].into_iter().const_chunks::<0>();

You should get an error similar to this one:

    |     const N_GT_ZERO: () = assert!(N > 0, "chunk size must be non-zero");
    |                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the evaluated program panicked at 'chunk size must be non-zero'

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl<I: Iterator> IteratorConstChunks for I

Blanket implementation over all Iterators.

Source§

type Inner = I