ddmd

How to pass file.ByChunk in dlang?


I'm newbie in D.

I have following code:

auto file = File("test.txt", "r");
scope(exit) file.close();

foreach (letter; getTextKernel(file.byChunk(8192))) {
    writeln(letter);
}

and my getTextKernel looks like:

string[] getTextKernel(InputRange!ubyte[] text) pure { ... }

I receive error: getTextKernel (InputRange!ubyte[] text) is not callable using argument types (ByChunk)

documentation about byChunk : Returns an input range set up to read from the file handle a chunk at a time.

UPDATE: WHOLE PROGRAM

import std.stdio;

string[] getTextKernel(R)(R text) pure {
    return ["aa", "bbb", "ccc"];
}

void main() {
    writeln("Hello master dmitry!");

    auto file = File("test.txt", "r");
    scope(exit) file.close();

    // StubdGenetics genetic;
    foreach (letter; getTextKernel(file.byChunk(8192))) {
        writeln(letter);
    }
}

error: pure function 'app.getTextKernel!(ByChunk).getTextKernel' cannot call impure destructor 'std.stdio.File.ByChunk.~this'


Solution

  • The usual approach is to make getTextKernel accept a template argument.

    string[] getTextKernel(R)(R text) pure   { ... }
    

    Because ranges are lazy in D they are often custom, one-off types. InputRange is almost never used in my experience. There are reasons to use it but it's slower (using runtime dispatch instead of compile time) and just generally not needed.