Skip to content

Instantly share code, notes, and snippets.

@TurkeyMan
Created April 26, 2015 04:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TurkeyMan/1f551bc5a0d2cec8af2e to your computer and use it in GitHub Desktop.
Save TurkeyMan/1f551bc5a0d2cec8af2e to your computer and use it in GitHub Desktop.
Literal/constant ranges
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