The Phobos Put

Salih Dincer salihdb at hotmail.com
Wed Mar 29 16:27:23 UTC 2023


On Wednesday, 29 March 2023 at 15:01:27 UTC, Ali Çehreli wrote:
> On 3/29/23 04:48, Dennis wrote:
> On the other hand, Phobos's put() works with any OutputRange so 
> it has to take a 'ref' to advance to know where it is left off. 
> This behavior makes its use with slices weird but sometimes 
> such is life. :)

Would not adding a prototype without a ref cause ambiguity? In 
this way, it could also be used directly with slices. For example:

```d
auto put(R)(R[] range, R[] source)
   => putImpl(range, source);

auto put(R)(ref R[] range, R[] source)
   => putImpl(range, source);

void putImpl(R)(ref R[] range, R[] source)
{
   assert(source.length <= range.length);
   foreach(element; source)
   {
     range[0] = element;  // range.front()
     range = range[1..$]; // range.popFront()
   }
}

void main() {
   enum data = [1, 0, 0, 4];
   auto arr = data;
   auto slice = arr[1..$-1];

   slice.put([2]);
   assert(arr == [1, 2, 0, 4]);

   slice.put([3]);
   assert(arr == [1, 2, 3, 4]);

   arr[1..$-1].put([0, 0]);
   assert(arr == data);
}
```

SDB at 79


More information about the Digitalmars-d-learn mailing list