Function std.stdio.File.byChunk
Returns an input range set up to read from the file handle a chunk at a time.
std .stdio .File .ByChunkImpl byChunk
(
ulong chunkSize
);
std .stdio .File .ByChunkImpl byChunk
(
ubyte[] buffer
);
The element type for the range will be ubyte[]
. Range primitives
may throw StdioException
on I/O error.
Example
void main()
{
// Read standard input 4KB at a time
foreach (ubyte[] buffer; stdin .byChunk(4096))
{
... use buffer ...
}
}
The parameter may be a number (as shown in the example above) dictating the
size of each chunk. Alternatively, byChunk
accepts a
user-provided buffer that it uses directly.
Example
void main()
{
// Read standard input 4KB at a time
foreach (ubyte[] buffer; stdin .byChunk(new ubyte[4096]))
{
... use buffer ...
}
}
In either case, the content of the buffer is reused across calls. That means
front
will not persist after popFront
is called, so if retention is
needed, the caller must copy its contents (e.g. by calling buffer
).
In the example above, buffer
is 4096 for all iterations, except
for the last one, in which case buffer
may be less than 4096 (but
always greater than zero).
With the mentioned limitations, byChunk
works with any algorithm
compatible with input ranges.
Example
// Efficient file copy, 1MB at a time.
import std .algorithm, std .stdio;
void main()
{
stdin .byChunk(1024 * 1024) .copy(stdout .lockingTextWriter());
}
joiner
can be used to join chunks together into
a single range lazily.
Example
import std .algorithm, std .stdio;
void main()
{
//Range of ranges
static assert(is(typeof(stdin .byChunk(4096) .front) == ubyte[]));
//Range of elements
static assert(is(typeof(stdin .byChunk(4096) .joiner .front) == ubyte));
}
Returns
A call to byChunk
returns a range initialized with the File
object and the appropriate buffer.
Throws
If the user-provided size is zero or the user-provided buffer
is empty, throws an Exception
. In case of an I/O error throws
StdioException
.
Authors
Walter Bright, Andrei Alexandrescu, Alex Rønne Petersen