chunks

This range iterates over fixed-sized chunks of size chunkSize of a source range. Source must be an input range. chunkSize must be greater than zero.

If !isInfinite!Source and source.walkLength is not evenly divisible by chunkSize, the back element of this range will contain fewer than chunkSize elements.

If Source is a forward range, the resulting range will be forward ranges as well. Otherwise, the resulting chunks will be input ranges consuming the same input: iterating over front will shrink the chunk such that subsequent invocations of front will no longer return the full chunk, and calling popFront on the outer range will invalidate any lingering references to previous values of front.

Chunks!Source
chunks
(
Source
)
(
Source source
,
size_t chunkSize
)
if (
isInputRange!Source
)

Parameters

source Source

Range from which the chunks will be selected

chunkSize size_t

Chunk size

Return Value

Type: Chunks!Source

Range of chunks.

Examples

import std.algorithm.comparison : equal;
auto source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
auto chunks = chunks(source, 4);
assert(chunks[0] == [1, 2, 3, 4]);
assert(chunks[1] == [5, 6, 7, 8]);
assert(chunks[2] == [9, 10]);
assert(chunks.back == chunks[2]);
assert(chunks.front == chunks[0]);
assert(chunks.length == 3);
assert(equal(retro(array(chunks)), array(retro(chunks))));

Non-forward input ranges are supported, but with limited semantics.

import std.algorithm.comparison : equal;

int i;

// The generator doesn't save state, so it cannot be a forward range.
auto inputRange = generate!(() => ++i).take(10);

// We can still process it in chunks, but it will be single-pass only.
auto chunked = inputRange.chunks(2);

assert(chunked.front.equal([1, 2]));
assert(chunked.front.empty); // Iterating the chunk has consumed it
chunked.popFront;
assert(chunked.front.equal([3, 4]));

See Also

Meta