I think the idea is interesting. With regard to safety, I'd recommend that byRef() just take a pointer instead of a ref parameter. This way, if the address of a stack variable is being taken, it's explicit from the client's side and byRange is only as unsafe as the client's usage of it.
On Thu, May 19, 2011 at 10:14 AM, Lars Tandle Kyllingstad < [email protected]> wrote: > Below is a simple implementation of a range which iterates another > (input) range by reference, for those cases when using an > InputRangeObject is overkill. I've used it quite a bit and I find it > immensely useful. > > It is sort of the opposite of save(). Where save() ensures that you are > only consuming a copy of the original range, byRef() ensures that you > are consuming the original range. > > Would this be useful for Phobos? I guess it is a tad unsafe, since it > stores the address of the range, which may well be stored on the stack. > > > /** Range that iterates another range by reference. */ > auto byRef(Range)(ref Range range) if (isInputRange!Range) > { > static struct ByRef > { > private Range* _range; > > static if (isInfinite!Range) > { > enum empty = false; > } > else > { > @property bool empty() { return (*_range).empty; } > } > > @property ElementType!Range front() > { > return (*_range).front; > } > > void popFront() > { > (*_range).popFront(); > } > } > > return ByRef(&range); > } > > unittest > { > auto a = [1, 2, 3, 4]; > auto b = take(byRef(a), 2); > > assert (equal(b, [1, 2])); > assert (equal(a, [3, 4])); > } > > > -Lars > > _______________________________________________ > phobos mailing list > [email protected] > http://lists.puremagic.com/mailman/listinfo/phobos >
_______________________________________________ phobos mailing list [email protected] http://lists.puremagic.com/mailman/listinfo/phobos
