Is this a bug in iota?

Jonathan M Davis jmdavisProg at gmx.com
Thu Apr 19 01:07:00 PDT 2012


On Thursday, April 19, 2012 09:58:00 Somedude wrote:
> Le 19/04/2012 05:36, bearophile a écrit :
> > Brad Anderson:
> >> You can popFront() for as long as you want well passed the length.
> >> Obviously popping off the front of a zero length range isn't valid but
> >> I would have expected a range violation to occur rather than it to
> >> silently continuing the series with a wrapped around length.
> > 
> > I think it's a matter of design and it's a matter of having an
> > alternative Phobos release that contains asserts too. Adding the test
> > slows down something (iota) that must be as fast as possible. And
> > currently asserts are removed from the compiled Phobos...
> > 
> > Bye,
> > bearophile
> 
> You've gotta be kidding. How can this NOT be a bug ?
> 
> import std.range, std.stdio;
> 
> void main()
> {
>     auto r = iota(3);
>     //writeln(isInfinite!r);
>     assert(!isInfinite!(int[]));
>     assert(isInfinite!(Repeat!(int)));
>     //assert(isRandomAccessRange!i);
>     writeln(r.front, ", length: ", r.length, " empty ? ", r.empty);
> r.popFront();
>     writeln(r.front, ", length: ", r.length, " empty ? ", r.empty);
> r.popFront();
>     writeln(r.front, ", length: ", r.length, " empty ? ", r.empty);
> r.popFront();
>     writeln(r.front, ", length: ", r.length, " empty ? ", r.empty);
> r.popFront();
>     writeln(r.front, ", length: ", r.length, " empty ? ", r.empty);
> r.popFront();
> }
> 
> Returns:
> 0, length: 3 empty ? false
> 1, length: 2 empty ? false
> 2, length: 1 empty ? false
> 3, length: 0 empty ? true
> 4, length: 4294967295 empty ? false

Having an assertion may be desirable, but the bug is in the usage of iota, not 
iota itself. At best, the assertion would help indicate that the caller has a 
bug. It's exactly the same as doing something like

for(size_t i = 3; cond; --i) {}

It's basic integer arithmetic. If you subtract from the minimum value that the 
integral type will hold, then its value will wrap around to the maximum. So, 
while adding an assertion would be desirable, I don't see how this could be 
considered a bug in iota.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list