[phobos] Would you find a ByRef range useful?

David Simcha dsimcha at gmail.com
Thu May 19 07:20:28 PDT 2011


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 <
lars at kyllingen.net> 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
> phobos at puremagic.com
> http://lists.puremagic.com/mailman/listinfo/phobos
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/phobos/attachments/20110519/8e007adf/attachment.html>


More information about the phobos mailing list