Why must a bidirectional range also be a forward range?
Paul Backus
snarwin at gmail.com
Thu Sep 19 16:02:02 UTC 2019
On Thursday, 19 September 2019 at 09:31:32 UTC, Joseph Rushton
Wakeling wrote:
> For context, the use-case I have is a data structure which
> stores an internal buffer as an array. A robust `save` method
> would therefore have to duplicate the array (or at least the
> active subset of its contents). This means a fresh heap
> allocation per `save`, which has some nasty implications for
> phobos algorithms that eagerly `.save` when they can.
In this case, it is probably better to separate the range from
the data structure it refers to. For example:
struct Container {
int[] data;
private static struct Range {
int[] contents;
bool empty() { return contents.length == 0; }
int front() { return contents[0]; }
void popFront() { contents = contents[1 .. $]; }
int back() { return contents[$ - 1]; }
void popBack() { contents = contents[0 .. $ - 1]; }
Range save() { return this; }
}
Range getRange() {
return Range(data[]);
}
}
More information about the Digitalmars-d-learn
mailing list