1 /// Assigns value to each element of input range range
2 module ddash.algorithm.fill;
3 
4 ///
5 unittest {
6     int[] a = [1, 2, 3];
7     a.fill(5);
8     assert(a == [5, 5, 5]);
9 
10     int[] b = [1, 2, 3, 4, 5];
11     b.fill(9, 2, 4);
12     assert(b == [1, 2, 9, 9, 5]);
13 
14     int[] c = [1, 2, 3, 4, 5];
15     c.fill(9, 1, 100);
16     assert(c == [1, 9, 9, 9, 9]);
17 }
18 
19 import ddash.common;
20 
21 /**
22     Fills a range with a value from `startIndex` to `endIndex`
23 
24     Params:
25         range = mutable input range
26         value = which value to fill the range with
27         startIndex = at which index to start filling the range
28         endIndex = at which index to stop filling the range (this index is not filled)
29 
30     Since:
31         0.0.1
32 */
33 void fill(Range, T)(ref Range range, auto ref T value, size_t startIndex = 0, size_t endIndex = size_t.max)
34 if (from!"std.range".isForwardRange!Range
35     && is(T : from!"std.range".ElementType!Range)
36     && is(typeof(range[] = value)))
37 {
38     import std.algorithm: stdFill = fill;
39     import std.range: drop, take, refRange, save;
40     refRange(&range)
41         .save
42         .drop(startIndex)
43         .take(endIndex - startIndex)
44         .stdFill(value);
45 }
46 
47 unittest {
48     // Should not compile if range is not reference type
49     static assert(!__traits(compiles, [1].fill(3)));
50 
51     // Should not compile if range does not have assignable elements
52     immutable int[] a = [1, 2];
53     static assert(!__traits(compiles, a.fill(3)));
54 }