"the last change" for ranges

MLT none at anon.com
Wed May 20 19:22:14 PDT 2009


Andrei Alexandrescu Wrote:

> MLT wrote:
> > I think that if
> >> R last = r;
> > then after
> >> r.popFront;
> > the order of elements in "last" should not change, no matter what
> > type of range you are dealing with. (That means that input operations
> > would be buffered to the leftmost range that still extsts.)
> > 
> > If I understood the logic of ranges, popFront() just changes the
> > range, and not the elements it points to.
> 
> That's the case for all ranges except input ranges. Consider:
> 
> FileByCharacter
> {
>      private FILE* _f;
>      private dchar _last;
>      bool empty() { return _last == 0xffff; }
>      void popFront() { _last = fgetc(_f); }
>      dchar front() { return _last; }
> }
> 
> Consider what happens when you copy this range around.
> 
> 
> Andrei


I thought more of something like:

FileByCharacter
 {
      private FILE* _f;
      private dchar[] _buf;
      bool empty() { return _buf[0] == 0xffff; } 
      void popFront() { 
        _buf = _buf[1..$] ; 
        if( _buf.length < 1 ) _buf ~= fgetc(_f); 
      }
      dchar front() { return _buf[0]; }
 }

The idea is that you continue to expand an array. Another copy of the range will continue to step over the same array. This doesn't really work, because the second copy doesn't really know how much the first copy already read. But that should be fixable....
the problem is in the line
        if( _buf.length < 1 ) _buf ~= fgetc(_f); 
which should only trigger if _buf reached the end of the read part, not the end of the current copy of _buf.

I'm also not sure if D's GC will handle dropping the part of the array that no one looks at.

One needs something like a lazy semi-infinite range, that only calls a certain function when it reaches an unexplored part.



More information about the Digitalmars-d mailing list