Created
February 5, 2011 18:57
-
-
Save JesseKPhillips/812681 to your computer and use it in GitHub Desktop.
Attempt to make a slice-able forward range.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module filerange; | |
import std.algorithm; | |
import std.array; | |
import std.conv; | |
import std.exception; | |
import std.file; | |
import std.range; | |
import std.stdio; | |
enum size = 4; | |
struct FileRange { | |
private: | |
size_t index; | |
string buff; | |
File.ByChunk chunks; | |
public: | |
static auto opCall(File file) { | |
FileRange fr; | |
fr.chunks = file.byChunk(size); | |
fr.prime(); | |
return fr; | |
} | |
auto empty() { | |
return buff.length == index; | |
} | |
auto popFront() { | |
index++; | |
if(index > buff.length - size/2 && !chunks.empty) { | |
prime(); | |
} | |
} | |
auto save() { | |
FileRange fr; | |
fr.chunks = chunks; | |
fr.buff = buff; | |
return fr; | |
} | |
auto front() { | |
return buff[index..$].front; | |
} | |
auto length() { | |
return buff.length; | |
} | |
private void prime() { | |
buff ~= cast(string)chunks.front.idup; | |
chunks.popFront(); | |
} | |
auto opSlice(size_t x, size_t y) { | |
FileRange fr; | |
fr.chunks = chunks; | |
if(y == buff.length) | |
fr.buff = buff[x+index..y]; | |
else | |
fr.buff = buff[x+index..y+index]; | |
return fr; | |
} | |
auto opAssign(FileRange fr) { | |
chunks = fr.chunks; | |
index = fr.index; | |
buff = fr.buff; | |
} | |
auto opOpAssign(string op)(FileRange fr) if(op == "~") { | |
chunks = fr.chunks; | |
buff ~= fr.buff; | |
} | |
} | |
struct InputFileRange { | |
private: | |
string buff; | |
File.ByChunk chunks; | |
public: | |
static auto opCall(File file) { | |
FileRange fr; | |
fr.chunks = file.byChunk(4096); | |
fr.prime(); | |
return fr; | |
} | |
auto empty() { | |
return buff.length == 0; | |
} | |
auto popFront() { | |
buff.popFront(); | |
if(buff.length < 2048 && !chunks.empty) { | |
prime(); | |
} | |
} | |
auto front() { | |
return buff.front; | |
} | |
private void prime() { | |
buff ~= cast(string)chunks.front.idup; | |
chunks.popFront(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment