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 Iterator
s with the capability to iterate
over const-sized arrays of items.
Required Associated Types§
Required Methods§
Sourcefn const_chunks<const N: usize>(self) -> ConstChunks<N, Self::Inner> ⓘ
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.