protocol for using InputRanges
Steven Schveighoffer
schveiguy at yahoo.com
Wed Mar 26 05:29:15 PDT 2014
On Wed, 26 Mar 2014 06:46:26 -0400, Regan Heath <regan at netmail.co.nz>
wrote:
>
> On Tue, 25 Mar 2014 23:22:18 -0000, Walter Bright
> <newshound2 at digitalmars.com> wrote:
>> On 3/25/2014 2:29 PM, Andrei Alexandrescu wrote:
>>>> The range instance gets bigger and
>>>> more expensive to copy, and the cost of manipulating the flag and the
>>>> buffer is added to every loop iteration. Note that the user of a range
>>>> can trivially use:
>>>> auto e = r.front;
>>>> ... using e multiple times ...
>>>> instead.
>>>
>>> That would pessimize code using arrays of large structs.
>>
>> You're already requiring copying with the buffering requirement. And
>> besides, if I was creating a range of expensive-to-copy objects, I
>> would add a layer of indirection to cheapen it.
>
> Surely you'd simply start with a range of pointers to expensive-to-copy
> objects? Or, return them by reference from the underlying
> range/array/source. You want to avoid *ever* copying them except
> explicitly where required.
>
>>> The proposed protocol pessimizes arrays of large structs
>>
>> Not really more than the existing protocol does (i.e. required
>> buffering).
>>
>>> and will trip the unwary if calling r.front again returns something
>>> else.
>>
>> I'm not proposing that calling them wrongly would make things unsafe.
>> But I don't think it's unreasonable to expect the protocol to be
>> followed, just like file open/read/close.
>
> My immediate expectation upon encountering ranges was that r.front would
> return the same item repeatedly until r.popFront was called. Breaking
> that guarantee will trip a *lot* of people up.
>
> IMO the rules should be something like:
> - r.empty WILL return false if there is more data available in the
> range.
>
> - r.empty MUST be called before r.front, r.front WILL succeed if
> r.empty returned false.
> - r.front WILL repeatably return the current element in the range. It
> MAY return by value or by reference.
>
> - r.empty SHOULD be called before r.popFront, otherwise r.popFront MAY
> do nothing or throw
> (could also make this one a 'MUST')
> - r.popFront WILL advance to the next element in the range.
These two rules are not necessary if you know the range is not empty. See
the conversation inside this pull:
https://github.com/D-Programming-Language/phobos/pull/1987
-Steve
More information about the Digitalmars-d
mailing list