Created
April 26, 2015 04:58
-
-
Save TurkeyMan/1f551bc5a0d2cec8af2e to your computer and use it in GitHub Desktop.
Literal/constant ranges
This file contains 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
auto literalRange(alias value)(size_t length) | |
{ | |
struct LiteralRange(alias Value) | |
{ | |
alias value = Value; | |
size_t length; | |
@property bool empty() const { return !length; } | |
@property auto front() inout { return value; } | |
void popFront() { --length; } | |
@property auto back() inout { return value; } | |
void popBack() { --length; } | |
@property auto save() { return this; } | |
auto opIndex(ulong n) inout { return value; } | |
auto opSlice() inout { return this; } | |
auto opSlice(ulong lower, ulong upper) inout { return typeof(this)(upper-lower); } | |
alias opDollar = length; | |
} | |
return LiteralRange!(value)(length); | |
} | |
auto constantRange(T)(T value, size_t length) | |
{ | |
struct ConstantRange(T) | |
{ | |
T value; | |
size_t length; | |
@property bool empty() const { return !length; } | |
@property inout(T) front() inout { return value; } | |
void popFront() { --length; } | |
@property inout(T) back() inout { return value; } | |
void popBack() { --length; } | |
@property auto save() { return this; } | |
inout(T) opIndex(ulong n) inout { return value; } | |
auto opSlice() inout { return this; } | |
auto opSlice(ulong lower, ulong upper) inout { return typeof(this)(value, upper-lower); } | |
alias opDollar = length; | |
} | |
return ConstantRange!T(value, length); | |
} | |
void test() | |
{ | |
writeln(literalRange!10(100)); // compile-time literal | |
writeln(constantRange(10, 100)); // takes a copy of some runtime variable | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment