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.

Constructors

this
this(Source source, size_t chunkSize)

Standard constructor

Members

Functions

opIndex
auto opIndex(size_t index)
opSlice
typeof(this) opSlice(size_t lower, size_t upper)

Indexing and slicing operations. Provided only if hasSlicing!Source is true.

popBack
void popBack()

Bidirectional range primitives. Provided only if both hasSlicing!Source and hasLength!Source are true.

popFront
void popFront()

Input range primitives. Always present.

Properties

back
auto back [@property getter]

Bidirectional range primitives. Provided only if both hasSlicing!Source and hasLength!Source are true.

empty
bool empty [@property getter]

Input range primitives. Always present.

front
auto front [@property getter]

Input range primitives. Always present.

length
size_t length [@property getter]

Length. Only if hasLength!Source is true

save
typeof(this) save [@property getter]

Forward range primitives. Only present if Source is a forward range.

Return Value

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