-
-
Notifications
You must be signed in to change notification settings - Fork 700
/
package.d
13486 lines (11756 loc) · 383 KB
/
package.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 module defines the notion of a range. Ranges generalize the concept of
arrays, lists, or anything that involves sequential access. This abstraction
enables the same set of algorithms (see $(MREF std, algorithm)) to be used
with a vast variety of different concrete types. For example,
a linear search algorithm such as $(REF find, std, algorithm, searching)
works not just for arrays, but for linked-lists, input files,
incoming network data, etc.
Guides:
There are many articles available that can bolster understanding ranges:
$(UL
$(LI Ali Çehreli's $(HTTP ddili.org/ders/d.en/ranges.html, tutorial on ranges)
for the basics of working with and creating range-based code.)
$(LI Jonathan M. Davis $(LINK2 http://dconf.org/2015/talks/davis.html, $(I Introduction to Ranges))
talk at DConf 2015 a vivid introduction from its core constructs to practical advice.)
$(LI The DLang Tour's $(LINK2 http://tour.dlang.org/tour/en/basics/ranges, chapter on ranges)
for an interactive introduction.)
$(LI H. S. Teoh's $(LINK2 http://wiki.dlang.org/Component_programming_with_ranges, tutorial on
component programming with ranges) for a real-world showcase of the influence
of range-based programming on complex algorithms.)
$(LI Andrei Alexandrescu's article
$(LINK2 http://www.informit.com/articles/printerfriendly.aspx?p=1407357$(AMP)rll=1,
$(I On Iteration)) for conceptual aspect of ranges and the motivation
)
)
Submodules:
This module has two submodules:
The $(MREF std, range, primitives) submodule
provides basic range functionality. It defines several templates for testing
whether a given object is a range, what kind of range it is, and provides
some common range operations.
The $(MREF std, range, interfaces) submodule
provides object-based interfaces for working with ranges via runtime
polymorphism.
The remainder of this module provides a rich set of range creation and
composition templates that let you construct new ranges out of existing ranges:
$(SCRIPT inhibitQuickIndex = 1;)
$(DIVC quickindex,
$(BOOKTABLE ,
$(TR $(TD $(LREF chain))
$(TD Concatenates several ranges into a single range.
))
$(TR $(TD $(LREF choose))
$(TD Chooses one of two ranges at runtime based on a boolean condition.
))
$(TR $(TD $(LREF chooseAmong))
$(TD Chooses one of several ranges at runtime based on an index.
))
$(TR $(TD $(LREF chunks))
$(TD Creates a range that returns fixed-size chunks of the original
range.
))
$(TR $(TD $(LREF cycle))
$(TD Creates an infinite range that repeats the given forward range
indefinitely. Good for implementing circular buffers.
))
$(TR $(TD $(LREF drop))
$(TD Creates the range that results from discarding the first $(I n)
elements from the given range.
))
$(TR $(TD $(LREF dropBack))
$(TD Creates the range that results from discarding the last $(I n)
elements from the given range.
))
$(TR $(TD $(LREF dropExactly))
$(TD Creates the range that results from discarding exactly $(I n)
of the first elements from the given range.
))
$(TR $(TD $(LREF dropBackExactly))
$(TD Creates the range that results from discarding exactly $(I n)
of the last elements from the given range.
))
$(TR $(TD $(LREF dropOne))
$(TD Creates the range that results from discarding
the first element from the given range.
))
$(TR $(TD $(D $(LREF dropBackOne)))
$(TD Creates the range that results from discarding
the last element from the given range.
))
$(TR $(TD $(LREF enumerate))
$(TD Iterates a range with an attached index variable.
))
$(TR $(TD $(LREF evenChunks))
$(TD Creates a range that returns a number of chunks of
approximately equal length from the original range.
))
$(TR $(TD $(LREF frontTransversal))
$(TD Creates a range that iterates over the first elements of the
given ranges.
))
$(TR $(TD $(LREF generate))
$(TD Creates a range by successive calls to a given function. This
allows to create ranges as a single delegate.
))
$(TR $(TD $(LREF indexed))
$(TD Creates a range that offers a view of a given range as though
its elements were reordered according to a given range of indices.
))
$(TR $(TD $(LREF iota))
$(TD Creates a range consisting of numbers between a starting point
and ending point, spaced apart by a given interval.
))
$(TR $(TD $(LREF lockstep))
$(TD Iterates $(I n) ranges in lockstep, for use in a `foreach`
loop. Similar to `zip`, except that `lockstep` is designed
especially for `foreach` loops.
))
$(TR $(TD $(LREF nullSink))
$(TD An output range that discards the data it receives.
))
$(TR $(TD $(LREF only))
$(TD Creates a range that iterates over the given arguments.
))
$(TR $(TD $(LREF padLeft))
$(TD Pads a range to a specified length by adding a given element to
the front of the range. Is lazy if the range has a known length.
))
$(TR $(TD $(LREF padRight))
$(TD Lazily pads a range to a specified length by adding a given element to
the back of the range.
))
$(TR $(TD $(LREF radial))
$(TD Given a random-access range and a starting point, creates a
range that alternately returns the next left and next right element to
the starting point.
))
$(TR $(TD $(LREF recurrence))
$(TD Creates a forward range whose values are defined by a
mathematical recurrence relation.
))
$(TR $(TD $(LREF refRange))
$(TD Pass a range by reference. Both the original range and the RefRange
will always have the exact same elements.
Any operation done on one will affect the other.
))
$(TR $(TD $(LREF repeat))
$(TD Creates a range that consists of a single element repeated $(I n)
times, or an infinite range repeating that element indefinitely.
))
$(TR $(TD $(LREF retro))
$(TD Iterates a bidirectional range backwards.
))
$(TR $(TD $(LREF roundRobin))
$(TD Given $(I n) ranges, creates a new range that return the $(I n)
first elements of each range, in turn, then the second element of each
range, and so on, in a round-robin fashion.
))
$(TR $(TD $(LREF sequence))
$(TD Similar to `recurrence`, except that a random-access range is
created.
))
$(TR $(TD $(D $(LREF slide)))
$(TD Creates a range that returns a fixed-size sliding window
over the original range. Unlike chunks,
it advances a configurable number of items at a time,
not one chunk at a time.
))
$(TR $(TD $(LREF stride))
$(TD Iterates a range with stride $(I n).
))
$(TR $(TD $(LREF tail))
$(TD Return a range advanced to within `n` elements of the end of
the given range.
))
$(TR $(TD $(LREF take))
$(TD Creates a sub-range consisting of only up to the first $(I n)
elements of the given range.
))
$(TR $(TD $(LREF takeExactly))
$(TD Like `take`, but assumes the given range actually has $(I n)
elements, and therefore also defines the `length` property.
))
$(TR $(TD $(LREF takeNone))
$(TD Creates a random-access range consisting of zero elements of the
given range.
))
$(TR $(TD $(LREF takeOne))
$(TD Creates a random-access range consisting of exactly the first
element of the given range.
))
$(TR $(TD $(LREF tee))
$(TD Creates a range that wraps a given range, forwarding along
its elements while also calling a provided function with each element.
))
$(TR $(TD $(LREF transposed))
$(TD Transposes a range of ranges.
))
$(TR $(TD $(LREF transversal))
$(TD Creates a range that iterates over the $(I n)'th elements of the
given random-access ranges.
))
$(TR $(TD $(LREF zip))
$(TD Given $(I n) ranges, creates a range that successively returns a
tuple of all the first elements, a tuple of all the second elements,
etc.
))
))
Sortedness:
Ranges whose elements are sorted afford better efficiency with certain
operations. For this, the $(LREF assumeSorted) function can be used to
construct a $(LREF SortedRange) from a pre-sorted range. The $(REF
sort, std, algorithm, sorting) function also conveniently
returns a $(LREF SortedRange). $(LREF SortedRange) objects provide some additional
range operations that take advantage of the fact that the range is sorted.
Source: $(PHOBOSSRC std/range/package.d)
License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(HTTP erdani.com, Andrei Alexandrescu), David Simcha,
$(HTTP jmdavisprog.com, Jonathan M Davis), and Jack Stouffer. Credit
for some of the ideas in building this module goes to
$(HTTP fantascienza.net/leonardo/so/, Leonardo Maffi).
*/
module std.range;
public import std.array;
public import std.range.interfaces;
public import std.range.primitives;
public import std.typecons : Flag, Yes, No;
import std.internal.attributes : betterC;
import std.meta : allSatisfy, staticMap;
import std.traits : CommonType, isCallable, isFloatingPoint, isIntegral,
isPointer, isSomeFunction, isStaticArray, Unqual, isInstanceOf;
/**
Iterates a bidirectional range backwards. The original range can be
accessed by using the `source` property. Applying retro twice to
the same range yields the original range.
Params:
r = the bidirectional range to iterate backwards
Returns:
A bidirectional range with length if `r` also provides a length. Or,
if `r` is a random access range, then the return value will be random
access as well.
See_Also:
$(REF reverse, std,algorithm,mutation) for mutating the source range directly.
*/
auto retro(Range)(Range r)
if (isBidirectionalRange!(Unqual!Range))
{
// Check for retro(retro(r)) and just return r in that case
static if (is(typeof(retro(r.source)) == Range))
{
return r.source;
}
else
{
static struct Result()
{
private alias R = Unqual!Range;
// User code can get and set source, too
R source;
static if (hasLength!R)
{
size_t retroIndex(size_t n)
{
return source.length - n - 1;
}
}
public:
alias Source = R;
@property bool empty() { return source.empty; }
@property auto save()
{
return Result(source.save);
}
@property auto ref front() { return source.back; }
void popFront() { source.popBack(); }
@property auto ref back() { return source.front; }
void popBack() { source.popFront(); }
static if (is(typeof(source.moveBack())))
{
ElementType!R moveFront()
{
return source.moveBack();
}
}
static if (is(typeof(source.moveFront())))
{
ElementType!R moveBack()
{
return source.moveFront();
}
}
static if (hasAssignableElements!R)
{
@property void front(ElementType!R val)
{
source.back = val;
}
@property void back(ElementType!R val)
{
source.front = val;
}
}
static if (isRandomAccessRange!(R) && hasLength!(R))
{
auto ref opIndex(size_t n) { return source[retroIndex(n)]; }
static if (hasAssignableElements!R)
{
void opIndexAssign(ElementType!R val, size_t n)
{
source[retroIndex(n)] = val;
}
}
static if (is(typeof(source.moveAt(0))))
{
ElementType!R moveAt(size_t index)
{
return source.moveAt(retroIndex(index));
}
}
static if (hasSlicing!R)
typeof(this) opSlice(size_t a, size_t b)
{
return typeof(this)(source[source.length - b .. source.length - a]);
}
}
mixin ImplementLength!source;
}
return Result!()(r);
}
}
///
pure @safe nothrow @nogc unittest
{
import std.algorithm.comparison : equal;
int[5] a = [ 1, 2, 3, 4, 5 ];
int[5] b = [ 5, 4, 3, 2, 1 ];
assert(equal(retro(a[]), b[]));
assert(retro(a[]).source is a[]);
assert(retro(retro(a[])) is a[]);
}
pure @safe nothrow unittest
{
import std.algorithm.comparison : equal;
static assert(isBidirectionalRange!(typeof(retro("hello"))));
int[] a;
static assert(is(typeof(a) == typeof(retro(retro(a)))));
assert(retro(retro(a)) is a);
static assert(isRandomAccessRange!(typeof(retro([1, 2, 3]))));
void test(int[] input, int[] witness)
{
auto r = retro(input);
assert(r.front == witness.front);
assert(r.back == witness.back);
assert(equal(r, witness));
}
test([ 1 ], [ 1 ]);
test([ 1, 2 ], [ 2, 1 ]);
test([ 1, 2, 3 ], [ 3, 2, 1 ]);
test([ 1, 2, 3, 4 ], [ 4, 3, 2, 1 ]);
test([ 1, 2, 3, 4, 5 ], [ 5, 4, 3, 2, 1 ]);
test([ 1, 2, 3, 4, 5, 6 ], [ 6, 5, 4, 3, 2, 1 ]);
immutable foo = [1,2,3].idup;
auto r = retro(foo);
assert(equal(r, [3, 2, 1]));
}
pure @safe nothrow unittest
{
import std.internal.test.dummyrange : AllDummyRanges, propagatesRangeType,
ReturnBy;
foreach (DummyType; AllDummyRanges)
{
static if (!isBidirectionalRange!DummyType)
{
static assert(!__traits(compiles, Retro!DummyType));
}
else
{
DummyType dummyRange;
dummyRange.reinit();
auto myRetro = retro(dummyRange);
static assert(propagatesRangeType!(typeof(myRetro), DummyType));
assert(myRetro.front == 10);
assert(myRetro.back == 1);
assert(myRetro.moveFront() == 10);
assert(myRetro.moveBack() == 1);
static if (isRandomAccessRange!DummyType && hasLength!DummyType)
{
assert(myRetro[0] == myRetro.front);
assert(myRetro.moveAt(2) == 8);
static if (DummyType.r == ReturnBy.Reference)
{
{
myRetro[9]++;
scope(exit) myRetro[9]--;
assert(dummyRange[0] == 2);
myRetro.front++;
scope(exit) myRetro.front--;
assert(myRetro.front == 11);
myRetro.back++;
scope(exit) myRetro.back--;
assert(myRetro.back == 3);
}
{
myRetro.front = 0xFF;
scope(exit) myRetro.front = 10;
assert(dummyRange.back == 0xFF);
myRetro.back = 0xBB;
scope(exit) myRetro.back = 1;
assert(dummyRange.front == 0xBB);
myRetro[1] = 11;
scope(exit) myRetro[1] = 8;
assert(dummyRange[8] == 11);
}
}
}
}
}
}
pure @safe nothrow @nogc unittest
{
import std.algorithm.comparison : equal;
auto LL = iota(1L, 4L);
auto r = retro(LL);
long[3] excepted = [3, 2, 1];
assert(equal(r, excepted[]));
}
// https://issues.dlang.org/show_bug.cgi?id=12662
pure @safe nothrow @nogc unittest
{
int[3] src = [1,2,3];
int[] data = src[];
foreach_reverse (x; data) {}
foreach (x; data.retro) {}
}
/**
Iterates range `r` with stride `n`. If the range is a
random-access range, moves by indexing into the range; otherwise,
moves by successive calls to `popFront`. Applying stride twice to
the same range results in a stride with a step that is the
product of the two applications. It is an error for `n` to be 0.
Params:
r = the $(REF_ALTTEXT input range, isInputRange, std,range,primitives) to stride over
n = the number of elements to skip over
Returns:
At minimum, an input range. The resulting range will adopt the
range primitives of the underlying range as long as
$(REF hasLength, std,range,primitives) is `true`.
*/
auto stride(Range)(Range r, size_t n)
if (isInputRange!(Unqual!Range))
in
{
assert(n != 0, "stride cannot have step zero.");
}
do
{
import std.algorithm.comparison : min;
static if (is(typeof(stride(r.source, n)) == Range))
{
// stride(stride(r, n1), n2) is stride(r, n1 * n2)
return stride(r.source, r._n * n);
}
else
{
static struct Result
{
private alias R = Unqual!Range;
public R source;
private size_t _n;
// Chop off the slack elements at the end
static if (hasLength!R &&
(isRandomAccessRange!R && hasSlicing!R
|| isBidirectionalRange!R))
private void eliminateSlackElements()
{
auto slack = source.length % _n;
if (slack)
{
slack--;
}
else if (!source.empty)
{
slack = min(_n, source.length) - 1;
}
else
{
slack = 0;
}
if (!slack) return;
static if (isRandomAccessRange!R && hasLength!R && hasSlicing!R)
{
source = source[0 .. source.length - slack];
}
else static if (isBidirectionalRange!R)
{
foreach (i; 0 .. slack)
{
source.popBack();
}
}
}
static if (isForwardRange!R)
{
@property auto save()
{
return Result(source.save, _n);
}
}
static if (isInfinite!R)
{
enum bool empty = false;
}
else
{
@property bool empty()
{
return source.empty;
}
}
@property auto ref front()
{
return source.front;
}
static if (is(typeof(.moveFront(source))))
{
ElementType!R moveFront()
{
return source.moveFront();
}
}
static if (hasAssignableElements!R)
{
@property void front(ElementType!R val)
{
source.front = val;
}
}
void popFront()
{
source.popFrontN(_n);
}
static if (isBidirectionalRange!R && hasLength!R)
{
void popBack()
{
popBackN(source, _n);
}
@property auto ref back()
{
eliminateSlackElements();
return source.back;
}
static if (is(typeof(.moveBack(source))))
{
ElementType!R moveBack()
{
eliminateSlackElements();
return source.moveBack();
}
}
static if (hasAssignableElements!R)
{
@property void back(ElementType!R val)
{
eliminateSlackElements();
source.back = val;
}
}
}
static if (isRandomAccessRange!R && hasLength!R)
{
auto ref opIndex(size_t n)
{
return source[_n * n];
}
/**
Forwards to $(D moveAt(source, n)).
*/
static if (is(typeof(source.moveAt(0))))
{
ElementType!R moveAt(size_t n)
{
return source.moveAt(_n * n);
}
}
static if (hasAssignableElements!R)
{
void opIndexAssign(ElementType!R val, size_t n)
{
source[_n * n] = val;
}
}
}
static if (hasSlicing!R && hasLength!R)
typeof(this) opSlice(size_t lower, size_t upper)
{
assert(upper >= lower && upper <= length,
"Attempt to get out-of-bounds slice of `stride` range");
immutable translatedUpper = (upper == 0) ? 0 :
(upper * _n - (_n - 1));
immutable translatedLower = min(lower * _n, translatedUpper);
assert(translatedLower <= translatedUpper,
"Overflow when calculating slice of `stride` range");
return typeof(this)(source[translatedLower .. translatedUpper], _n);
}
static if (hasLength!R)
{
@property auto length()
{
return (source.length + _n - 1) / _n;
}
alias opDollar = length;
}
}
return Result(r, n);
}
}
///
pure @safe nothrow unittest
{
import std.algorithm.comparison : equal;
int[] a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ];
assert(equal(stride(a, 3), [ 1, 4, 7, 10 ][]));
assert(stride(stride(a, 2), 3) == stride(a, 6));
}
pure @safe nothrow @nogc unittest
{
import std.algorithm.comparison : equal;
int[4] testArr = [1,2,3,4];
static immutable result = [1, 3];
assert(equal(testArr[].stride(2), result));
}
debug pure nothrow @system unittest
{//check the contract
int[4] testArr = [1,2,3,4];
bool passed = false;
scope (success) assert(passed);
import core.exception : AssertError;
//std.exception.assertThrown won't do because it can't infer nothrow
// https://issues.dlang.org/show_bug.cgi?id=12647
try
{
auto unused = testArr[].stride(0);
}
catch (AssertError unused)
{
passed = true;
}
}
pure @safe nothrow unittest
{
import std.algorithm.comparison : equal;
import std.internal.test.dummyrange : AllDummyRanges, propagatesRangeType,
ReturnBy;
static assert(isRandomAccessRange!(typeof(stride([1, 2, 3], 2))));
void test(size_t n, int[] input, int[] witness)
{
assert(equal(stride(input, n), witness));
}
test(1, [], []);
int[] arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
assert(stride(stride(arr, 2), 3) is stride(arr, 6));
test(1, arr, arr);
test(2, arr, [1, 3, 5, 7, 9]);
test(3, arr, [1, 4, 7, 10]);
test(4, arr, [1, 5, 9]);
// Test slicing.
auto s1 = stride(arr, 1);
assert(equal(s1[1 .. 4], [2, 3, 4]));
assert(s1[1 .. 4].length == 3);
assert(equal(s1[1 .. 5], [2, 3, 4, 5]));
assert(s1[1 .. 5].length == 4);
assert(s1[0 .. 0].empty);
assert(s1[3 .. 3].empty);
// assert(s1[$ .. $].empty);
assert(s1[s1.opDollar .. s1.opDollar].empty);
auto s2 = stride(arr, 2);
assert(equal(s2[0 .. 2], [1,3]));
assert(s2[0 .. 2].length == 2);
assert(equal(s2[1 .. 5], [3, 5, 7, 9]));
assert(s2[1 .. 5].length == 4);
assert(s2[0 .. 0].empty);
assert(s2[3 .. 3].empty);
// assert(s2[$ .. $].empty);
assert(s2[s2.opDollar .. s2.opDollar].empty);
// Test fix for https://issues.dlang.org/show_bug.cgi?id=5035
auto m = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]; // 3 rows, 4 columns
auto col = stride(m, 4);
assert(equal(col, [1, 1, 1]));
assert(equal(retro(col), [1, 1, 1]));
immutable int[] immi = [ 1, 2, 3 ];
static assert(isRandomAccessRange!(typeof(stride(immi, 1))));
// Check for infiniteness propagation.
static assert(isInfinite!(typeof(stride(repeat(1), 3))));
foreach (DummyType; AllDummyRanges)
{
DummyType dummyRange;
dummyRange.reinit();
auto myStride = stride(dummyRange, 4);
// Should fail if no length and bidirectional b/c there's no way
// to know how much slack we have.
static if (hasLength!DummyType || !isBidirectionalRange!DummyType)
{
static assert(propagatesRangeType!(typeof(myStride), DummyType));
}
assert(myStride.front == 1);
assert(myStride.moveFront() == 1);
assert(equal(myStride, [1, 5, 9]));
static if (hasLength!DummyType)
{
assert(myStride.length == 3);
}
static if (isBidirectionalRange!DummyType && hasLength!DummyType)
{
assert(myStride.back == 9);
assert(myStride.moveBack() == 9);
}
static if (isRandomAccessRange!DummyType && hasLength!DummyType)
{
assert(myStride[0] == 1);
assert(myStride[1] == 5);
assert(myStride.moveAt(1) == 5);
assert(myStride[2] == 9);
static assert(hasSlicing!(typeof(myStride)));
}
static if (DummyType.r == ReturnBy.Reference)
{
// Make sure reference is propagated.
{
myStride.front++;
scope(exit) myStride.front--;
assert(dummyRange.front == 2);
}
{
myStride.front = 4;
scope(exit) myStride.front = 1;
assert(dummyRange.front == 4);
}
static if (isBidirectionalRange!DummyType && hasLength!DummyType)
{
{
myStride.back++;
scope(exit) myStride.back--;
assert(myStride.back == 10);
}
{
myStride.back = 111;
scope(exit) myStride.back = 9;
assert(myStride.back == 111);
}
static if (isRandomAccessRange!DummyType)
{
{
myStride[1]++;
scope(exit) myStride[1]--;
assert(dummyRange[4] == 6);
}
{
myStride[1] = 55;
scope(exit) myStride[1] = 5;
assert(dummyRange[4] == 55);
}
}
}
}
}
}
pure @safe nothrow unittest
{
import std.algorithm.comparison : equal;
auto LL = iota(1L, 10L);
auto s = stride(LL, 3);
assert(equal(s, [1L, 4L, 7L]));
}
/**
Spans multiple ranges in sequence. The function `chain` takes any
number of ranges and returns a $(D Chain!(R1, R2,...)) object. The
ranges may be different, but they must have the same element type. The
result is a range that offers the `front`, `popFront`, and $(D
empty) primitives. If all input ranges offer random access and $(D
length), `Chain` offers them as well.
If only one range is offered to `Chain` or `chain`, the $(D
Chain) type exits the picture by aliasing itself directly to that
range's type.
Params:
rs = the $(REF_ALTTEXT input ranges, isInputRange, std,range,primitives) to chain together
Returns:
An input range at minimum. If all of the ranges in `rs` provide
a range primitive, the returned range will also provide that range
primitive.
See_Also: $(LREF only) to chain values to a range
*/
auto chain(Ranges...)(Ranges rs)
if (Ranges.length > 0 &&
allSatisfy!(isInputRange, staticMap!(Unqual, Ranges)) &&
!is(CommonType!(staticMap!(ElementType, staticMap!(Unqual, Ranges))) == void))
{
static if (Ranges.length == 1)
{
return rs[0];
}
else
{
static struct Result
{
private:
alias R = staticMap!(Unqual, Ranges);
alias RvalueElementType = CommonType!(staticMap!(.ElementType, R));
private template sameET(A)
{
enum sameET = is(.ElementType!A == RvalueElementType);
}
enum bool allSameType = allSatisfy!(sameET, R);
alias ElementType = RvalueElementType;
static if (allSameType && allSatisfy!(hasLvalueElements, R))
{
static ref RvalueElementType fixRef(ref RvalueElementType val)
{
return val;
}
}
else
{
static RvalueElementType fixRef(RvalueElementType val)
{
return val;
}
}
// This is the entire state
R source;
// TODO: use a vtable (or more) instead of linear iteration
public:
this(R input)
{
foreach (i, v; input)
{
source[i] = v;
}
}
import std.meta : anySatisfy;
static if (anySatisfy!(isInfinite, R))
{
// Propagate infiniteness.
enum bool empty = false;
}
else
{
@property bool empty()
{
foreach (i, Unused; R)
{
if (!source[i].empty) return false;
}
return true;
}
}
static if (allSatisfy!(isForwardRange, R))
@property auto save()
{
auto saveSource(size_t len)()
{
import std.typecons : tuple;
static assert(len > 0);
static if (len == 1)
{
return tuple(source[0].save);
}
else
{
return saveSource!(len - 1)() ~
tuple(source[len - 1].save);
}
}
return Result(saveSource!(R.length).expand);
}
void popFront()
{
foreach (i, Unused; R)
{
if (source[i].empty) continue;
source[i].popFront();
return;
}
assert(false, "Attempt to `popFront` of empty `chain` range");
}
@property auto ref front()
{
foreach (i, Unused; R)
{
if (source[i].empty) continue;
return fixRef(source[i].front);
}
assert(false, "Attempt to get `front` of empty `chain` range");
}