Function std.stdio.File.byChunk
Returns an input range set up to read from the file handle a chunk at a time.
The element type for the range will be ubyte[]. Range primitives
may throw on I/O StdioExceptionerror.
Prototypes
auto std.stdio. File. ByChunk byChunk( ulong chunkSize ); std. stdio. File. ByChunk byChunk( ubyte[] buffer );
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, accepts a
user-provided byChunkbuffer 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.dup).
In the example above, buffer.length is 4096 for all iterations, except
for the last one, in which case buffer.length may be less than 4096 (but
always greater than zero).
With the mentioned limitations, byChunks 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()); }
std.algorithm.iteration.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 returns a range initialized with the byChunkFileobject 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