-
-
Notifications
You must be signed in to change notification settings - Fork 731
/
Copy pathmutation.d
2917 lines (2572 loc) · 80.3 KB
/
mutation.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Written in the D programming language.
/**
This is a submodule of $(MREF std, algorithm).
It contains generic mutation algorithms.
$(SCRIPT inhibitQuickIndex = 1;)
$(BOOKTABLE Cheat Sheet,
$(TR $(TH Function Name) $(TH Description))
$(T2 bringToFront,
If `a = [1, 2, 3]` and `b = [4, 5, 6, 7]`,
`bringToFront(a, b)` leaves `a = [4, 5, 6]` and
`b = [7, 1, 2, 3]`.)
$(T2 copy,
Copies a range to another. If
`a = [1, 2, 3]` and `b = new int[5]`, then `copy(a, b)`
leaves `b = [1, 2, 3, 0, 0]` and returns `b[3 .. $]`.)
$(T2 fill,
Fills a range with a pattern,
e.g., if `a = new int[3]`, then `fill(a, 4)`
leaves `a = [4, 4, 4]` and `fill(a, [3, 4])` leaves
`a = [3, 4, 3]`.)
$(T2 initializeAll,
If `a = [1.2, 3.4]`, then `initializeAll(a)` leaves
`a = [double.init, double.init]`.)
$(T2 move,
`move(a, b)` moves `a` into `b`. `move(a)` reads `a`
destructively when necessary.)
$(T2 moveEmplace,
Similar to `move` but assumes `target` is uninitialized.)
$(T2 moveAll,
Moves all elements from one range to another.)
$(T2 moveEmplaceAll,
Similar to `moveAll` but assumes all elements in `target` are uninitialized.)
$(T2 moveSome,
Moves as many elements as possible from one range to another.)
$(T2 moveEmplaceSome,
Similar to `moveSome` but assumes all elements in `target` are uninitialized.)
$(T2 remove,
Removes elements from a range in-place, and returns the shortened
range.)
$(T2 reverse,
If `a = [1, 2, 3]`, `reverse(a)` changes it to `[3, 2, 1]`.)
$(T2 strip,
Strips all leading and trailing elements equal to a value, or that
satisfy a predicate.
If `a = [1, 1, 0, 1, 1]`, then `strip(a, 1)` and
`strip!(e => e == 1)(a)` returns `[0]`.)
$(T2 stripLeft,
Strips all leading elements equal to a value, or that satisfy a
predicate. If `a = [1, 1, 0, 1, 1]`, then `stripLeft(a, 1)` and
`stripLeft!(e => e == 1)(a)` returns `[0, 1, 1]`.)
$(T2 stripRight,
Strips all trailing elements equal to a value, or that satisfy a
predicate.
If `a = [1, 1, 0, 1, 1]`, then `stripRight(a, 1)` and
`stripRight!(e => e == 1)(a)` returns `[1, 1, 0]`.)
$(T2 swap,
Swaps two values.)
$(T2 swapAt,
Swaps two values by indices.)
$(T2 swapRanges,
Swaps all elements of two ranges.)
$(T2 uninitializedFill,
Fills a range (assumed uninitialized) with a value.)
)
Copyright: Andrei Alexandrescu 2008-.
License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(HTTP erdani.com, Andrei Alexandrescu)
Source: $(PHOBOSSRC std/algorithm/mutation.d)
Macros:
T2=$(TR $(TDNW $(LREF $1)) $(TD $+))
*/
module std.algorithm.mutation;
import std.range.primitives;
import std.traits : isArray, isAssignable, isBlitAssignable, isNarrowString,
Unqual, isSomeChar, isMutable;
import std.meta : allSatisfy;
// FIXME
import std.typecons; // : tuple, Tuple;
// bringToFront
/**
`bringToFront` takes two ranges `front` and `back`, which may
be of different types. Considering the concatenation of `front` and
`back` one unified range, `bringToFront` rotates that unified
range such that all elements in `back` are brought to the beginning
of the unified range. The relative ordering of elements in `front`
and `back`, respectively, remains unchanged.
The `bringToFront` function treats strings at the code unit
level and it is not concerned with Unicode character integrity.
`bringToFront` is designed as a function for moving elements
in ranges, not as a string function.
Performs $(BIGOH max(front.length, back.length)) evaluations of $(D
swap).
The `bringToFront` function can rotate elements in one buffer left or right, swap
buffers of equal length, and even move elements across disjoint
buffers of different types and different lengths.
Preconditions:
Either `front` and `back` are disjoint, or `back` is
reachable from `front` and `front` is not reachable from $(D
back).
Params:
front = an $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
back = a $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives)
Returns:
The number of elements brought to the front, i.e., the length of `back`.
See_Also:
$(LINK2 http://en.cppreference.com/w/cpp/algorithm/rotate, STL's `rotate`)
*/
size_t bringToFront(InputRange, ForwardRange)(InputRange front, ForwardRange back)
if (isInputRange!InputRange && isForwardRange!ForwardRange)
{
import std.string : representation;
static if (isNarrowString!InputRange)
{
auto frontW = representation(front);
}
else
{
alias frontW = front;
}
static if (isNarrowString!ForwardRange)
{
auto backW = representation(back);
}
else
{
alias backW = back;
}
return bringToFrontImpl(frontW, backW);
}
/**
The simplest use of `bringToFront` is for rotating elements in a
buffer. For example:
*/
@safe unittest
{
auto arr = [4, 5, 6, 7, 1, 2, 3];
auto p = bringToFront(arr[0 .. 4], arr[4 .. $]);
assert(p == arr.length - 4);
assert(arr == [ 1, 2, 3, 4, 5, 6, 7 ]);
}
/**
The `front` range may actually "step over" the `back`
range. This is very useful with forward ranges that cannot compute
comfortably right-bounded subranges like `arr[0 .. 4]` above. In
the example below, `r2` is a right subrange of `r1`.
*/
@safe unittest
{
import std.algorithm.comparison : equal;
import std.container : SList;
import std.range.primitives : popFrontN;
auto list = SList!(int)(4, 5, 6, 7, 1, 2, 3);
auto r1 = list[];
auto r2 = list[]; popFrontN(r2, 4);
assert(equal(r2, [ 1, 2, 3 ]));
bringToFront(r1, r2);
assert(equal(list[], [ 1, 2, 3, 4, 5, 6, 7 ]));
}
/**
Elements can be swapped across ranges of different types:
*/
@safe unittest
{
import std.algorithm.comparison : equal;
import std.container : SList;
auto list = SList!(int)(4, 5, 6, 7);
auto vec = [ 1, 2, 3 ];
bringToFront(list[], vec);
assert(equal(list[], [ 1, 2, 3, 4 ]));
assert(equal(vec, [ 5, 6, 7 ]));
}
/**
Unicode integrity is not preserved:
*/
@safe unittest
{
import std.string : representation;
auto ar = representation("a".dup);
auto br = representation("ç".dup);
bringToFront(ar, br);
auto a = cast(char[]) ar;
auto b = cast(char[]) br;
// Illegal UTF-8
assert(a == "\303");
// Illegal UTF-8
assert(b == "\247a");
}
private size_t bringToFrontImpl(InputRange, ForwardRange)(InputRange front, ForwardRange back)
if (isInputRange!InputRange && isForwardRange!ForwardRange)
{
import std.array : sameHead;
import std.range : take, Take;
enum bool sameHeadExists = is(typeof(front.sameHead(back)));
size_t result;
for (bool semidone; !front.empty && !back.empty; )
{
static if (sameHeadExists)
{
if (front.sameHead(back)) break; // shortcut
}
// Swap elements until front and/or back ends.
auto back0 = back.save;
size_t nswaps;
do
{
static if (sameHeadExists)
{
// Detect the stepping-over condition.
if (front.sameHead(back0)) back0 = back.save;
}
swapFront(front, back);
++nswaps;
front.popFront();
back.popFront();
}
while (!front.empty && !back.empty);
if (!semidone) result += nswaps;
// Now deal with the remaining elements.
if (back.empty)
{
if (front.empty) break;
// Right side was shorter, which means that we've brought
// all the back elements to the front.
semidone = true;
// Next pass: bringToFront(front, back0) to adjust the rest.
back = back0;
}
else
{
assert(front.empty, "Expected front to be empty");
// Left side was shorter. Let's step into the back.
static if (is(InputRange == Take!ForwardRange))
{
front = take(back0, nswaps);
}
else
{
immutable subresult = bringToFront(take(back0, nswaps),
back);
if (!semidone) result += subresult;
break; // done
}
}
}
return result;
}
@safe unittest
{
import std.algorithm.comparison : equal;
import std.conv : text;
import std.random : Random = Xorshift, uniform;
// a more elaborate test
{
auto rnd = Random(123_456_789);
int[] a = new int[uniform(100, 200, rnd)];
int[] b = new int[uniform(100, 200, rnd)];
foreach (ref e; a) e = uniform(-100, 100, rnd);
foreach (ref e; b) e = uniform(-100, 100, rnd);
int[] c = a ~ b;
// writeln("a= ", a);
// writeln("b= ", b);
auto n = bringToFront(c[0 .. a.length], c[a.length .. $]);
//writeln("c= ", c);
assert(n == b.length);
assert(c == b ~ a, text(c, "\n", a, "\n", b));
}
// different types, moveFront, no sameHead
{
static struct R(T)
{
T[] data;
size_t i;
@property
{
R save() { return this; }
bool empty() { return i >= data.length; }
T front() { return data[i]; }
T front(real e) { return data[i] = cast(T) e; }
}
void popFront() { ++i; }
}
auto a = R!int([1, 2, 3, 4, 5]);
auto b = R!real([6, 7, 8, 9]);
auto n = bringToFront(a, b);
assert(n == 4);
assert(a.data == [6, 7, 8, 9, 1]);
assert(b.data == [2, 3, 4, 5]);
}
// front steps over back
{
int[] arr, r1, r2;
// back is shorter
arr = [4, 5, 6, 7, 1, 2, 3];
r1 = arr;
r2 = arr[4 .. $];
bringToFront(r1, r2) == 3 || assert(0);
assert(equal(arr, [1, 2, 3, 4, 5, 6, 7]));
// front is shorter
arr = [5, 6, 7, 1, 2, 3, 4];
r1 = arr;
r2 = arr[3 .. $];
bringToFront(r1, r2) == 4 || assert(0);
assert(equal(arr, [1, 2, 3, 4, 5, 6, 7]));
}
// Bugzilla 16959
auto arr = ['4', '5', '6', '7', '1', '2', '3'];
auto p = bringToFront(arr[0 .. 4], arr[4 .. $]);
assert(p == arr.length - 4);
assert(arr == ['1', '2', '3', '4', '5', '6', '7']);
}
// Tests if types are arrays and support slice assign.
private enum bool areCopyCompatibleArrays(T1, T2) =
isArray!T1 && isArray!T2 && is(typeof(T2.init[] = T1.init[]));
// copy
/**
Copies the content of `source` into `target` and returns the
remaining (unfilled) part of `target`.
Preconditions: `target` shall have enough room to accommodate
the entirety of `source`.
Params:
source = an $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
target = an output range
Returns:
The unfilled part of target
*/
TargetRange copy(SourceRange, TargetRange)(SourceRange source, TargetRange target)
if (areCopyCompatibleArrays!(SourceRange, TargetRange))
{
const tlen = target.length;
const slen = source.length;
assert(tlen >= slen,
"Cannot copy a source range into a smaller target range.");
immutable overlaps = __ctfe || () @trusted {
return source.ptr < target.ptr + tlen &&
target.ptr < source.ptr + slen; }();
if (overlaps)
{
foreach (idx; 0 .. slen)
target[idx] = source[idx];
return target[slen .. tlen];
}
else
{
// Array specialization. This uses optimized memory copying
// routines under the hood and is about 10-20x faster than the
// generic implementation.
target[0 .. slen] = source[];
return target[slen .. $];
}
}
/// ditto
TargetRange copy(SourceRange, TargetRange)(SourceRange source, TargetRange target)
if (!areCopyCompatibleArrays!(SourceRange, TargetRange) &&
isInputRange!SourceRange &&
isOutputRange!(TargetRange, ElementType!SourceRange))
{
// Specialize for 2 random access ranges.
// Typically 2 random access ranges are faster iterated by common
// index than by x.popFront(), y.popFront() pair
static if (isRandomAccessRange!SourceRange &&
hasLength!SourceRange &&
hasSlicing!TargetRange &&
isRandomAccessRange!TargetRange &&
hasLength!TargetRange)
{
auto len = source.length;
foreach (idx; 0 .. len)
target[idx] = source[idx];
return target[len .. target.length];
}
else
{
foreach (element; source)
put(target, element);
return target;
}
}
///
@safe unittest
{
int[] a = [ 1, 5 ];
int[] b = [ 9, 8 ];
int[] buf = new int[](a.length + b.length + 10);
auto rem = a.copy(buf); // copy a into buf
rem = b.copy(rem); // copy b into remainder of buf
assert(buf[0 .. a.length + b.length] == [1, 5, 9, 8]);
assert(rem.length == 10); // unused slots in buf
}
/**
As long as the target range elements support assignment from source
range elements, different types of ranges are accepted:
*/
@safe unittest
{
float[] src = [ 1.0f, 5 ];
double[] dest = new double[src.length];
src.copy(dest);
}
/**
To _copy at most `n` elements from a range, you may want to use
$(REF take, std,range):
*/
@safe unittest
{
import std.range;
int[] src = [ 1, 5, 8, 9, 10 ];
auto dest = new int[](3);
src.take(dest.length).copy(dest);
assert(dest == [ 1, 5, 8 ]);
}
/**
To _copy just those elements from a range that satisfy a predicate,
use $(LREF filter):
*/
@safe unittest
{
import std.algorithm.iteration : filter;
int[] src = [ 1, 5, 8, 9, 10, 1, 2, 0 ];
auto dest = new int[src.length];
auto rem = src
.filter!(a => (a & 1) == 1)
.copy(dest);
assert(dest[0 .. $ - rem.length] == [ 1, 5, 9, 1 ]);
}
/**
$(REF retro, std,range) can be used to achieve behavior similar to
$(LINK2 http://en.cppreference.com/w/cpp/algorithm/copy_backward, STL's `copy_backward`'):
*/
@safe unittest
{
import std.algorithm, std.range;
int[] src = [1, 2, 4];
int[] dest = [0, 0, 0, 0, 0];
src.retro.copy(dest.retro);
assert(dest == [0, 0, 1, 2, 4]);
}
// Test CTFE copy.
@safe unittest
{
enum c = copy([1,2,3], [4,5,6,7]);
assert(c == [7]);
}
@safe unittest
{
import std.algorithm.iteration : filter;
{
int[] a = [ 1, 5 ];
int[] b = [ 9, 8 ];
auto e = copy(filter!("a > 1")(a), b);
assert(b[0] == 5 && e.length == 1);
}
{
int[] a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
copy(a[5 .. 10], a[4 .. 9]);
assert(a[4 .. 9] == [6, 7, 8, 9, 10]);
}
{ // Test for bug 7898
enum v =
{
import std.algorithm;
int[] arr1 = [10, 20, 30, 40, 50];
int[] arr2 = arr1.dup;
copy(arr1, arr2);
return 35;
}();
assert(v == 35);
}
}
@safe unittest
{
// Issue 13650
import std.meta : AliasSeq;
static foreach (Char; AliasSeq!(char, wchar, dchar))
{{
Char[3] a1 = "123";
Char[6] a2 = "456789";
assert(copy(a1[], a2[]) is a2[3..$]);
assert(a1[] == "123");
assert(a2[] == "123789");
}}
}
@safe unittest // issue 18804
{
static struct NullSink
{
void put(E)(E) {}
}
int line = 0;
struct R
{
int front;
@property bool empty() { return line == 1; }
void popFront() { line = 1; }
}
R r;
copy(r, NullSink());
assert(line == 1);
}
/**
Assigns `value` to each element of input range `range`.
Alternatively, instead of using a single `value` to fill the `range`,
a `filter` $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives)
can be provided. The length of `filler` and `range` do not need to match, but
`filler` must not be empty.
Params:
range = An
$(REF_ALTTEXT input range, isInputRange, std,range,primitives)
that exposes references to its elements and has assignable
elements
value = Assigned to each element of range
filler = A
$(REF_ALTTEXT forward range, isForwardRange, std,range,primitives)
representing the _fill pattern.
Throws: If `filler` is empty.
See_Also:
$(LREF uninitializedFill)
$(LREF initializeAll)
*/
void fill(Range, Value)(auto ref Range range, auto ref Value value)
if ((isInputRange!Range && is(typeof(range.front = value)) ||
isSomeChar!Value && is(typeof(range[] = value))))
{
alias T = ElementType!Range;
static if (is(typeof(range[] = value)))
{
range[] = value;
}
else static if (is(typeof(range[] = T(value))))
{
range[] = T(value);
}
else
{
for ( ; !range.empty; range.popFront() )
{
range.front = value;
}
}
}
///
@safe unittest
{
int[] a = [ 1, 2, 3, 4 ];
fill(a, 5);
assert(a == [ 5, 5, 5, 5 ]);
}
// issue 16342, test fallback on mutable narrow strings
@safe unittest
{
char[] chars = ['a', 'b'];
fill(chars, 'c');
assert(chars == "cc");
char[2] chars2 = ['a', 'b'];
fill(chars2, 'c');
assert(chars2 == "cc");
wchar[] wchars = ['a', 'b'];
fill(wchars, wchar('c'));
assert(wchars == "cc"w);
dchar[] dchars = ['a', 'b'];
fill(dchars, dchar('c'));
assert(dchars == "cc"d);
}
@nogc @safe unittest
{
const(char)[] chars;
assert(chars.length == 0);
static assert(!__traits(compiles, fill(chars, 'c')));
wstring wchars;
assert(wchars.length == 0);
static assert(!__traits(compiles, fill(wchars, wchar('c'))));
}
@nogc @safe unittest
{
char[] chars;
fill(chars, 'c');
assert(chars == ""c);
}
@safe unittest
{
shared(char)[] chrs = ['r'];
fill(chrs, 'c');
assert(chrs == [shared(char)('c')]);
}
@nogc @safe unittest
{
struct Str(size_t len)
{
private char[len] _data;
void opIndexAssign(char value) @safe @nogc
{_data[] = value;}
}
Str!2 str;
str.fill(':');
assert(str._data == "::");
}
@safe unittest
{
char[] chars = ['a','b','c','d'];
chars[1 .. 3].fill(':');
assert(chars == "a::d");
}
// end issue 16342
@safe unittest
{
import std.conv : text;
import std.internal.test.dummyrange;
int[] a = [ 1, 2, 3 ];
fill(a, 6);
assert(a == [ 6, 6, 6 ], text(a));
void fun0()
{
foreach (i; 0 .. 1000)
{
foreach (ref e; a) e = 6;
}
}
void fun1() { foreach (i; 0 .. 1000) fill(a, 6); }
// fill should accept InputRange
alias InputRange = DummyRange!(ReturnBy.Reference, Length.No, RangeType.Input);
enum filler = uint.max;
InputRange range;
fill(range, filler);
foreach (value; range.arr)
assert(value == filler);
}
@safe unittest
{
//ER8638_1 IS_NOT self assignable
static struct ER8638_1
{
void opAssign(int){}
}
//ER8638_1 IS self assignable
static struct ER8638_2
{
void opAssign(ER8638_2){}
void opAssign(int){}
}
auto er8638_1 = new ER8638_1[](10);
auto er8638_2 = new ER8638_2[](10);
er8638_1.fill(5); //generic case
er8638_2.fill(5); //opSlice(T.init) case
}
@safe unittest
{
{
int[] a = [1, 2, 3];
immutable(int) b = 0;
a.fill(b);
assert(a == [0, 0, 0]);
}
{
double[] a = [1, 2, 3];
immutable(int) b = 0;
a.fill(b);
assert(a == [0, 0, 0]);
}
}
/// ditto
void fill(InputRange, ForwardRange)(InputRange range, ForwardRange filler)
if (isInputRange!InputRange
&& (isForwardRange!ForwardRange
|| (isInputRange!ForwardRange && isInfinite!ForwardRange))
&& is(typeof(InputRange.init.front = ForwardRange.init.front)))
{
static if (isInfinite!ForwardRange)
{
//ForwardRange is infinite, no need for bounds checking or saving
static if (hasSlicing!ForwardRange && hasLength!InputRange
&& is(typeof(filler[0 .. range.length])))
{
copy(filler[0 .. range.length], range);
}
else
{
//manual feed
for ( ; !range.empty; range.popFront(), filler.popFront())
{
range.front = filler.front;
}
}
}
else
{
import std.exception : enforce;
enforce(!filler.empty, "Cannot fill range with an empty filler");
static if (hasLength!InputRange && hasLength!ForwardRange
&& is(typeof(range.length > filler.length)))
{
//Case we have access to length
immutable len = filler.length;
//Start by bulk copies
while (range.length > len)
{
range = copy(filler.save, range);
}
//and finally fill the partial range. No need to save here.
static if (hasSlicing!ForwardRange && is(typeof(filler[0 .. range.length])))
{
//use a quick copy
auto len2 = range.length;
range = copy(filler[0 .. len2], range);
}
else
{
//iterate. No need to check filler, it's length is longer than range's
for (; !range.empty; range.popFront(), filler.popFront())
{
range.front = filler.front;
}
}
}
else
{
//Most basic case.
auto bck = filler.save;
for (; !range.empty; range.popFront(), filler.popFront())
{
if (filler.empty) filler = bck.save;
range.front = filler.front;
}
}
}
}
///
@safe unittest
{
int[] a = [ 1, 2, 3, 4, 5 ];
int[] b = [ 8, 9 ];
fill(a, b);
assert(a == [ 8, 9, 8, 9, 8 ]);
}
@safe unittest
{
import std.exception : assertThrown;
import std.internal.test.dummyrange;
int[] a = [ 1, 2, 3, 4, 5 ];
int[] b = [1, 2];
fill(a, b);
assert(a == [ 1, 2, 1, 2, 1 ]);
// fill should accept InputRange
alias InputRange = DummyRange!(ReturnBy.Reference, Length.No, RangeType.Input);
InputRange range;
fill(range,[1,2]);
foreach (i,value;range.arr)
assert(value == (i%2 == 0?1:2));
//test with a input being a "reference forward" range
fill(a, new ReferenceForwardRange!int([8, 9]));
assert(a == [8, 9, 8, 9, 8]);
//test with a input being an "infinite input" range
fill(a, new ReferenceInfiniteInputRange!int());
assert(a == [0, 1, 2, 3, 4]);
//empty filler test
assertThrown(fill(a, a[$..$]));
}
/**
Initializes all elements of `range` with their `.init` value.
Assumes that the elements of the range are uninitialized.
Params:
range = An
$(REF_ALTTEXT input range, isInputRange, std,range,primitives)
that exposes references to its elements and has assignable
elements
See_Also:
$(LREF fill)
$(LREF uninitializeFill)
*/
void initializeAll(Range)(Range range)
if (isInputRange!Range && hasLvalueElements!Range && hasAssignableElements!Range)
{
import core.stdc.string : memset, memcpy;
import std.traits : hasElaborateAssign, isDynamicArray;
alias T = ElementType!Range;
static if (hasElaborateAssign!T)
{
import std.algorithm.internal : addressOf;
//Elaborate opAssign. Must go the memcpy road.
//We avoid calling emplace here, because our goal is to initialize to
//the static state of T.init,
//So we want to avoid any un-necassarilly CC'ing of T.init
static if (!__traits(isZeroInit, T))
{
auto p = typeid(T).initializer();
for ( ; !range.empty ; range.popFront() )
{
static if (__traits(isStaticArray, T))
{
// static array initializer only contains initialization
// for one element of the static array.
auto elemp = cast(void *) addressOf(range.front);
auto endp = elemp + T.sizeof;
while (elemp < endp)
{
memcpy(elemp, p.ptr, p.length);
elemp += p.length;
}
}
else
{
memcpy(addressOf(range.front), p.ptr, T.sizeof);
}
}
}
else
static if (isDynamicArray!Range)
memset(range.ptr, 0, range.length * T.sizeof);
else
for ( ; !range.empty ; range.popFront() )
memset(addressOf(range.front), 0, T.sizeof);
}
else
fill(range, T.init);
}
/// ditto
void initializeAll(Range)(Range range)
if (is(Range == char[]) || is(Range == wchar[]))
{
alias T = ElementEncodingType!Range;
range[] = T.init;
}
///
@system unittest
{
import core.stdc.stdlib : malloc, free;
struct S
{
int a = 10;
}
auto s = (cast(S*) malloc(5 * S.sizeof))[0 .. 5];
initializeAll(s);
assert(s == [S(10), S(10), S(10), S(10), S(10)]);
scope(exit) free(s.ptr);
}
@system unittest
{
import std.algorithm.iteration : filter;
import std.meta : AliasSeq;
import std.traits : hasElaborateAssign;
//Test strings:
//Must work on narrow strings.
//Must reject const
char[3] a = void;
a[].initializeAll();
assert(a[] == [char.init, char.init, char.init]);
string s;
assert(!__traits(compiles, s.initializeAll()));
assert(!__traits(compiles, s.initializeAll()));
assert(s.empty);
//Note: Cannot call uninitializedFill on narrow strings
enum e {e1, e2}
e[3] b1 = void;
b1[].initializeAll();
assert(b1[] == [e.e1, e.e1, e.e1]);
e[3] b2 = void;
b2[].uninitializedFill(e.e2);
assert(b2[] == [e.e2, e.e2, e.e2]);
static struct S1
{
int i;
}
static struct S2
{
int i = 1;
}
static struct S3
{
int i;
this(this){}
}
static struct S4
{
int i = 1;
this(this){}
}
static assert(!hasElaborateAssign!S1);
static assert(!hasElaborateAssign!S2);
static assert( hasElaborateAssign!S3);
static assert( hasElaborateAssign!S4);
assert(!typeid(S1).initializer().ptr);
assert( typeid(S2).initializer().ptr);
assert(!typeid(S3).initializer().ptr);
assert( typeid(S4).initializer().ptr);
static foreach (S; AliasSeq!(S1, S2, S3, S4))
{
//initializeAll
{
//Array
S[3] ss1 = void;
ss1[].initializeAll();
assert(ss1[] == [S.init, S.init, S.init]);
//Not array