/
range.d
6937 lines (6092 loc) · 188 KB
/
range.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 $(LINK2 std_algorithm.html,
std.algorithm)) to be used with a vast variety of different concrete types. For
example, a linear search algorithm such as $(LINK2 std_algorithm.html#find,
std.algorithm.find) works not just for arrays, but for linked-lists, input
files, incoming network data, etc.
For more detailed information about the conceptual aspect of ranges and the
motivation behind them, see Andrei Alexandrescu's article
$(LINK2 http://www.informit.com/articles/printerfriendly.aspx?p=1407357&rll=1,
$(I On Iteration)).
This module defines several templates for testing whether a given object is a
_range, and what kind of _range it is:
$(BOOKTABLE ,
$(TR $(TD $(D $(LREF isInputRange)))
$(TD Tests if something is an $(I input _range), defined to be something from
which one can sequentially read data using the primitives $(D front), $(D
popFront), and $(D empty).
))
$(TR $(TD $(D $(LREF isOutputRange)))
$(TD Tests if something is an $(I output _range), defined to be something to
which one can sequentially write data using the $(D $(LREF put)) primitive.
))
$(TR $(TD $(D $(LREF isForwardRange)))
$(TD Tests if something is a $(I forward _range), defined to be an input _range
with the additional capability that one can save one's current position with
the $(D save) primitive, thus allowing one to iterate over the same _range
multiple times.
))
$(TR $(TD $(D $(LREF isBidirectionalRange)))
$(TD Tests if something is a $(I bidirectional _range), that is, an input
_range that allows reverse traversal using the primitives $(D back) and $(D
popBack).
))
$(TR $(TD $(D $(LREF isRandomAccessRange)))
$(TD Tests if something is a $(I random access _range), which is a
bidirectional _range that also supports the array subscripting operation via
the primitive $(D opIndex).
))
)
A number of templates are provided that test for various _range capabilities:
$(BOOKTABLE ,
$(TR $(TD $(D $(LREF hasMobileElements)))
$(TD Tests if a given _range's elements can be moved around using the
primitives $(D moveFront), $(D moveBack), or $(D moveAt).
))
$(TR $(TD $(D $(LREF ElementType)))
$(TD Returns the element type of a given _range.
))
$(TR $(TD $(D $(LREF ElementEncodingType)))
$(TD Returns the encoding element type of a given _range.
))
$(TR $(TD $(D $(LREF hasSwappableElements)))
$(TD Tests if a _range is a forward _range with swappable elements.
))
$(TR $(TD $(D $(LREF hasAssignableElements)))
$(TD Tests if a _range is a forward _range with mutable elements.
))
$(TR $(TD $(D $(LREF hasLvalueElements)))
$(TD Tests if a _range is a forward _range with elements that can be passed by
reference and have their address taken.
))
$(TR $(TD $(D $(LREF hasLength)))
$(TD Tests if a given _range has the $(D length) attribute.
))
$(TR $(TD $(D $(LREF isInfinite)))
$(TD Tests if a given _range is an $(I infinite _range).
))
$(TR $(TD $(D $(LREF hasSlicing)))
$(TD Tests if a given _range supports the array slicing operation $(D R[x..y]).
))
$(TR $(TD $(D $(LREF walkLength)))
$(TD Computes the length of any _range in O(n) time.
))
)
A rich set of _range creation and composition templates are provided that let
you construct new ranges out of existing ranges:
$(BOOKTABLE ,
$(TR $(TD $(D $(LREF retro)))
$(TD Iterates a bidirectional _range backwards.
))
$(TR $(TD $(D $(LREF stride)))
$(TD Iterates a _range with stride $(I n).
))
$(TR $(TD $(D $(LREF chain)))
$(TD Concatenates several ranges into a single _range.
))
$(TR $(TD $(D $(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 $(D $(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 $(D $(LREF take)))
$(TD Creates a sub-_range consisting of only up to the first $(I n) elements of
the given _range.
))
$(TR $(TD $(D $(LREF takeExactly)))
$(TD Like $(D take), but assumes the given _range actually has $(I n) elements,
and therefore also defines the $(D length) property.
))
$(TR $(TD $(D $(LREF takeOne)))
$(TD Creates a random-access _range consisting of exactly the first element of
the given _range.
))
$(TR $(TD $(D $(LREF takeNone)))
$(TD Creates a random-access _range consisting of zero elements of the given
_range.
))
$(TR $(TD $(D $(LREF drop)))
$(TD Creates the _range that results from discarding the first $(I n) elements
from the given _range.
))
$(TR $(TD $(D $(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 $(D $(LREF cycle)))
$(TD Creates an infinite _range that repeats the given forward _range
indefinitely. Good for implementing circular buffers.
))
$(TR $(TD $(D $(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.
))
$(TR $(TD $(D $(LREF lockstep)))
$(TD Iterates $(I n) _ranges in lockstep, for use in a $(D foreach) loop.
Similar to $(D zip), except that $(D lockstep) is designed especially for $(D
foreach) loops.
))
$(TR $(TD $(D $(LREF recurrence)))
$(TD Creates a forward _range whose values are defined by a mathematical
recurrence relation.
))
$(TR $(TD $(D $(LREF sequence)))
$(TD Similar to $(D recurrence), except that a random-access _range is created.
))
$(TR $(TD $(D $(LREF iota)))
$(TD Creates a _range consisting of numbers between a starting point and ending
point, spaced apart by a given interval.
))
$(TR $(TD $(D $(LREF frontTransversal)))
$(TD Creates a _range that iterates over the first elements of the given
ranges.
))
$(TR $(TD $(D $(LREF transversal)))
$(TD Creates a _range that iterates over the $(I n)'th elements of the given
random-access ranges.
))
$(TR $(TD $(D $(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 $(D $(LREF chunks)))
$(TD Creates a _range that returns fixed-size chunks of the original _range.
))
)
These _range-construction tools are implemented using templates; but sometimes
an object-based interface for ranges is needed. For this purpose, this module
provides a number of object and $(D interface) definitions that can be used to
wrap around _range objects created by the above templates:
$(BOOKTABLE ,
$(TR $(TD $(D $(LREF InputRange)))
$(TD Wrapper for input ranges.
))
$(TR $(TD $(D $(LREF InputAssignable)))
$(TD Wrapper for input ranges with assignable elements.
))
$(TR $(TD $(D $(LREF ForwardRange)))
$(TD Wrapper for forward ranges.
))
$(TR $(TD $(D $(LREF ForwardAssignable)))
$(TD Wrapper for forward ranges with assignable elements.
))
$(TR $(TD $(D $(LREF BidirectionalRange)))
$(TD Wrapper for bidirectional ranges.
))
$(TR $(TD $(D $(LREF BidirectionalAssignable)))
$(TD Wrapper for bidirectional ranges with assignable elements.
))
$(TR $(TD $(D $(LREF RandomAccessFinite)))
$(TD Wrapper for finite random-access ranges.
))
$(TR $(TD $(D $(LREF RandomAccessAssignable)))
$(TD Wrapper for finite random-access ranges with assignable elements.
))
$(TR $(TD $(D $(LREF RandomAccessInfinite)))
$(TD Wrapper for infinite random-access ranges.
))
$(TR $(TD $(D $(LREF OutputRange)))
$(TD Wrapper for output ranges.
))
$(TR $(TD $(D $(LREF OutputRangeObject)))
$(TD Class that implements the $(D OutputRange) interface and wraps the
$(D put) methods in virtual functions.
))
$(TR $(TD $(D $(LREF InputRangeObject)))
$(TD Class that implements the $(D InputRange) interface and wraps the input
_range methods in virtual functions.
))
)
Ranges whose elements are sorted afford better efficiency with certain
operations. For this, the $(D $(LREF assumeSorted)) function can be used to
construct a $(D $(LREF SortedRange)) from a pre-sorted _range. The $(D $(LINK2
std_algorithm.html#sort, std.algorithm.sort)) function also conveniently
returns a $(D SortedRange). $(D SortedRange) objects provide some additional
_range operations that take advantage of the fact that the _range is sorted.
Finally, this module also defines some convenience functions for
manipulating ranges:
$(BOOKTABLE ,
$(TR $(TD $(D $(LREF popFrontN)))
$(TD Advances a given _range by $(I n) elements.
))
$(TR $(TD $(D $(LREF popBackN)))
$(TD Advances a given bidirectional _range from the right by $(I n) elements.
))
$(TR $(TD $(D $(LREF moveFront)))
$(TD Removes the front element of a _range.
))
$(TR $(TD $(D $(LREF moveBack)))
$(TD Removes the back element of a bidirectional _range.
))
$(TR $(TD $(D $(LREF moveAt)))
$(TD Removes the $(I i)'th element of a random-access _range.
))
)
Source: $(PHOBOSSRC std/_range.d)
Macros:
WIKI = Phobos/StdRange
Copyright: Copyright by authors 2008-.
License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(WEB erdani.com, Andrei Alexandrescu), David Simcha. Credit
for some of the ideas in building this module goes to $(WEB
fantascienza.net/leonardo/so/, Leonardo Maffi).
*/
module std.range;
public import std.array;
import core.bitop;
import std.algorithm, std.conv, std.exception, std.functional,
std.traits, std.typecons, std.typetuple;
// For testing only. This code is included in a string literal to be included
// in whatever module it's needed in, so that each module that uses it can be
// tested individually, without needing to link to std.range.
enum dummyRanges = q{
// Used with the dummy ranges for testing higher order ranges.
enum RangeType {
Input,
Forward,
Bidirectional,
Random
}
enum Length {
Yes,
No
}
enum ReturnBy {
Reference,
Value
}
// Range that's useful for testing other higher order ranges,
// can be parametrized with attributes. It just dumbs down an array of
// numbers 1..10.
struct DummyRange(ReturnBy _r, Length _l, RangeType _rt) {
// These enums are so that the template params are visible outside
// this instantiation.
enum r = _r;
enum l = _l;
enum rt = _rt;
uint[] arr = [1U, 2U, 3U, 4U, 5U, 6U, 7U, 8U, 9U, 10U];
void reinit() {
// Workaround for DMD bug 4378
arr = [1U, 2U, 3U, 4U, 5U, 6U, 7U, 8U, 9U, 10U];
}
void popFront() {
arr = arr[1..$];
}
@property bool empty() {
return arr.length == 0;
}
static if(r == ReturnBy.Reference) {
@property ref uint front() {
return arr[0];
}
@property void front(uint val) {
arr[0] = val;
}
} else {
@property uint front() {
return arr[0];
}
}
static if(rt >= RangeType.Forward) {
@property typeof(this) save() {
return this;
}
}
static if(rt >= RangeType.Bidirectional) {
void popBack() {
arr = arr[0..$ - 1];
}
static if(r == ReturnBy.Reference) {
@property ref uint back() {
return arr[$ - 1];
}
@property void back(uint val) {
arr[$ - 1] = val;
}
} else {
@property uint back() {
return arr[$ - 1];
}
}
}
static if(rt >= RangeType.Random) {
static if(r == ReturnBy.Reference) {
ref uint opIndex(size_t index) {
return arr[index];
}
void opIndexAssign(uint val, size_t index) {
arr[index] = val;
}
} else {
@property uint opIndex(size_t index) {
return arr[index];
}
}
typeof(this) opSlice(size_t lower, size_t upper) {
auto ret = this;
ret.arr = arr[lower..upper];
return ret;
}
}
static if(l == Length.Yes) {
@property size_t length() {
return arr.length;
}
alias length opDollar;
}
}
enum dummyLength = 10;
alias TypeTuple!(
DummyRange!(ReturnBy.Reference, Length.Yes, RangeType.Forward),
DummyRange!(ReturnBy.Reference, Length.Yes, RangeType.Bidirectional),
DummyRange!(ReturnBy.Reference, Length.Yes, RangeType.Random),
DummyRange!(ReturnBy.Reference, Length.No, RangeType.Forward),
DummyRange!(ReturnBy.Reference, Length.No, RangeType.Bidirectional),
DummyRange!(ReturnBy.Value, Length.Yes, RangeType.Input),
DummyRange!(ReturnBy.Value, Length.Yes, RangeType.Forward),
DummyRange!(ReturnBy.Value, Length.Yes, RangeType.Bidirectional),
DummyRange!(ReturnBy.Value, Length.Yes, RangeType.Random),
DummyRange!(ReturnBy.Value, Length.No, RangeType.Input),
DummyRange!(ReturnBy.Value, Length.No, RangeType.Forward),
DummyRange!(ReturnBy.Value, Length.No, RangeType.Bidirectional)
) AllDummyRanges;
};
version(unittest)
{
import std.container, std.conv, std.math, std.stdio;
mixin(dummyRanges);
// Tests whether forward, bidirectional and random access properties are
// propagated properly from the base range(s) R to the higher order range
// H. Useful in combination with DummyRange for testing several higher
// order ranges.
template propagatesRangeType(H, R...) {
static if(allSatisfy!(isRandomAccessRange, R)) {
enum bool propagatesRangeType = isRandomAccessRange!H;
} else static if(allSatisfy!(isBidirectionalRange, R)) {
enum bool propagatesRangeType = isBidirectionalRange!H;
} else static if(allSatisfy!(isForwardRange, R)) {
enum bool propagatesRangeType = isForwardRange!H;
} else {
enum bool propagatesRangeType = isInputRange!H;
}
}
template propagatesLength(H, R...) {
static if(allSatisfy!(hasLength, R)) {
enum bool propagatesLength = hasLength!H;
} else {
enum bool propagatesLength = !hasLength!H;
}
}
}
/**
Returns $(D true) if $(D R) is an input range. An input range must
define the primitives $(D empty), $(D popFront), and $(D front). The
following code should compile for any input range.
----
R r; // can define a range object
if (r.empty) {} // can test for empty
r.popFront(); // can invoke popFront()
auto h = r.front; // can get the front of the range of non-void type
----
The semantics of an input range (not checkable during compilation) are
assumed to be the following ($(D r) is an object of type $(D R)):
$(UL $(LI $(D r.empty) returns $(D false) iff there is more data
available in the range.) $(LI $(D r.front) returns the current
element in the range. It may return by value or by reference. Calling
$(D r.front) is allowed only if calling $(D r.empty) has, or would
have, returned $(D false).) $(LI $(D r.popFront) advances to the next
element in the range. Calling $(D r.popFront) is allowed only if
calling $(D r.empty) has, or would have, returned $(D false).))
*/
template isInputRange(R)
{
enum bool isInputRange = is(typeof(
{
R r = void; // can define a range object
if (r.empty) {} // can test for empty
r.popFront(); // can invoke popFront()
auto h = r.front; // can get the front of the range
}));
}
unittest
{
struct A {}
static assert(!isInputRange!(A));
struct B
{
void popFront();
@property bool empty();
@property int front();
}
static assert(isInputRange!(B));
static assert(isInputRange!(int[]));
static assert(isInputRange!(char[]));
static assert(!isInputRange!(char[4]));
}
/**
Outputs $(D e) to $(D r). The exact effect is dependent upon the two
types. Several cases are accepted, as described below. The code snippets
are attempted in order, and the first to compile "wins" and gets
evaluated.
$(BOOKTABLE ,
$(TR $(TH Code Snippet) $(TH Scenario))
$(TR $(TD $(D r.put(e);)) $(TD $(D R) specifically defines a method
$(D put) accepting an $(D E).))
$(TR $(TD $(D r.put([ e ]);)) $(TD $(D R) specifically defines a
method $(D put) accepting an $(D E[]).))
$(TR $(TD $(D r.front = e; r.popFront();)) $(TD $(D R) is an input
range and $(D e) is assignable to $(D r.front).))
$(TR $(TD $(D for (; !e.empty; e.popFront()) put(r, e.front);)) $(TD
Copying range $(D E) to range $(D R).))
$(TR $(TD $(D r(e);)) $(TD $(D R) is e.g. a delegate accepting an $(D
E).))
$(TR $(TD $(D r([ e ]);)) $(TD $(D R) is e.g. a $(D delegate)
accepting an $(D E[]).))
)
*/
void put(R, E)(ref R r, E e)
{
static if (hasMember!(R, "put") ||
(isPointer!R && is(PointerTarget!R == struct) &&
hasMember!(PointerTarget!R, "put")))
{
// commit to using the "put" method
static if (!isArray!R && is(typeof(r.put(e))))
{
r.put(e);
}
else static if (!isArray!R && is(typeof(r.put((&e)[0..1]))))
{
r.put((&e)[0..1]);
}
else static if (isInputRange!E && is(typeof(put(r, e.front))))
{
for (; !e.empty; e.popFront()) put(r, e.front);
}
else
{
static assert(false,
"Cannot put a "~E.stringof~" into a "~R.stringof);
}
}
else
{
static if (isInputRange!R)
{
// Commit to using assignment to front
static if (is(typeof(r.front = e, r.popFront())))
{
r.front = e;
r.popFront();
}
else static if (isInputRange!E && is(typeof(put(r, e.front))))
{
for (; !e.empty; e.popFront()) put(r, e.front);
}
else
{
static assert(false,
"Cannot put a "~E.stringof~" into a "~R.stringof);
}
}
else
{
// Commit to using opCall
static if (is(typeof(r(e))))
{
r(e);
}
else static if (is(typeof(r((&e)[0..1]))))
{
r((&e)[0..1]);
}
else
{
static assert(false,
"Cannot put a "~E.stringof~" into a "~R.stringof);
}
}
}
}
unittest
{
struct A {}
static assert(!isInputRange!(A));
struct B
{
void put(int) {}
}
B b;
put(b, 5);
}
unittest
{
int[] a = [1, 2, 3], b = [10, 20];
auto c = a;
put(a, b);
assert(c == [10, 20, 3]);
assert(a == [3]);
}
unittest
{
int[] a = new int[10];
int b;
static assert(isInputRange!(typeof(a)));
put(a, b);
}
unittest
{
void myprint(in char[] s) { }
auto r = &myprint;
put(r, 'a');
}
unittest
{
int[] a = new int[10];
static assert(!__traits(compiles, put(a, 1.0L)));
static assert( __traits(compiles, put(a, 1)));
/*
* a[0] = 65; // OK
* a[0] = 'A'; // OK
* a[0] = "ABC"[0]; // OK
* put(a, "ABC"); // OK
*/
static assert( __traits(compiles, put(a, "ABC")));
}
unittest
{
char[] a = new char[10];
static assert(!__traits(compiles, put(a, 1.0L)));
static assert(!__traits(compiles, put(a, 1)));
// char[] is NOT output range.
static assert(!__traits(compiles, put(a, 'a')));
static assert(!__traits(compiles, put(a, "ABC")));
}
unittest
{
// Test fix for bug 7476.
struct LockingTextWriter
{
void put(dchar c){}
}
struct RetroResult
{
bool end = false;
@property bool empty() const { return end; }
@property dchar front(){ return 'a'; }
void popFront(){ end = true; }
}
LockingTextWriter w;
RetroResult r;
put(w, r);
}
/**
Returns $(D true) if $(D R) is an output range for elements of type
$(D E). An output range is defined functionally as a range that
supports the operation $(D put(r, e)) as defined above.
*/
template isOutputRange(R, E)
{
enum bool isOutputRange = is(typeof(
{
R r = void;
E e;
put(r, e);
}));
}
unittest
{
void myprint(in char[] s) { writeln('[', s, ']'); }
static assert(isOutputRange!(typeof(&myprint), char));
auto app = appender!string();
string s;
static assert( isOutputRange!(Appender!string, string));
static assert( isOutputRange!(Appender!string*, string));
static assert(!isOutputRange!(Appender!string, int));
static assert(!isOutputRange!(char[], char));
static assert(!isOutputRange!(wchar[], wchar));
static assert( isOutputRange!(dchar[], char));
static assert( isOutputRange!(dchar[], wchar));
static assert( isOutputRange!(dchar[], dchar));
}
/**
Returns $(D true) if $(D R) is a forward range. A forward range is an
input range $(D r) that can save "checkpoints" by saving $(D r.save)
to another value of type $(D R). Notable examples of input ranges that
are $(I not) forward ranges are file/socket ranges; copying such a
range will not save the position in the stream, and they most likely
reuse an internal buffer as the entire stream does not sit in
memory. Subsequently, advancing either the original or the copy will
advance the stream, so the copies are not independent.
The following code should compile for any forward range.
----
static assert(isInputRange!R);
R r1;
R r2 = r1.save; // can save the current position into another range
----
Saving a range is not duplicating it; in the example above, $(D r1)
and $(D r2) still refer to the same underlying data. They just
navigate that data independently.
The semantics of a forward range (not checkable during compilation)
are the same as for an input range, with the additional requirement
that backtracking must be possible by saving a copy of the range
object with $(D save) and using it later.
*/
template isForwardRange(R)
{
enum bool isForwardRange = isInputRange!R && is(typeof(
{
R r1 = void;
R r2 = r1.save; // can call "save" against a range object
}));
}
unittest
{
static assert(!isForwardRange!(int));
static assert(isForwardRange!(int[]));
}
/**
Returns $(D true) if $(D R) is a bidirectional range. A bidirectional
range is a forward range that also offers the primitives $(D back) and
$(D popBack). The following code should compile for any bidirectional
range.
----
R r;
static assert(isForwardRange!R); // is forward range
r.popBack(); // can invoke popBack
auto t = r.back; // can get the back of the range
auto w = r.front;
static assert(is(typeof(t) == typeof(w))); // same type for front and back
----
The semantics of a bidirectional range (not checkable during
compilation) are assumed to be the following ($(D r) is an object of
type $(D R)):
$(UL $(LI $(D r.back) returns (possibly a reference to) the last
element in the range. Calling $(D r.back) is allowed only if calling
$(D r.empty) has, or would have, returned $(D false).))
*/
template isBidirectionalRange(R)
{
enum bool isBidirectionalRange = isForwardRange!R && is(typeof(
{
R r = void;
r.popBack();
auto t = r.back;
auto w = r.front;
static assert(is(typeof(t) == typeof(w)));
}));
}
unittest
{
struct A {}
static assert(!isBidirectionalRange!(A));
struct B
{
void popFront();
@property bool empty();
@property int front();
}
static assert(!isBidirectionalRange!(B));
struct C
{
@property bool empty();
@property C save();
void popFront();
@property int front();
void popBack();
@property int back();
}
static assert(isBidirectionalRange!(C));
static assert(isBidirectionalRange!(int[]));
static assert(isBidirectionalRange!(char[]));
}
/**
Returns $(D true) if $(D R) is a random-access range. A random-access
range is a bidirectional range that also offers the primitive $(D
opIndex), OR an infinite forward range that offers $(D opIndex). In
either case, the range must either offer $(D length) or be
infinite. The following code should compile for any random-access
range.
----
R r;
static assert(isForwardRange!R); // range is forward
static assert(isBidirectionalRange!R || isInfinite!R);
// range is bidirectional or infinite
auto e = r[1]; // can index
----
The semantics of a random-access range (not checkable during
compilation) are assumed to be the following ($(D r) is an object of
type $(D R)): $(UL $(LI $(D r.opIndex(n)) returns a reference to the
$(D n)th element in the range.))
Although $(D char[]) and $(D wchar[]) (as well as their qualified
versions including $(D string) and $(D wstring)) are arrays, $(D
isRandomAccessRange) yields $(D false) for them because they use
variable-length encodings (UTF-8 and UTF-16 respectively). These types
are bidirectional ranges only.
*/
template isRandomAccessRange(R)
{
enum bool isRandomAccessRange = is(typeof(
{
static assert(isBidirectionalRange!R ||
isForwardRange!R && isInfinite!R);
R r = void;
auto e = r[1];
static assert(!isNarrowString!R);
static assert(hasLength!R || isInfinite!R);
}));
}
unittest
{
struct A {}
static assert(!isRandomAccessRange!(A));
struct B
{
void popFront();
@property bool empty();
@property int front();
}
static assert(!isRandomAccessRange!(B));
struct C
{
void popFront();
@property bool empty();
@property int front();
void popBack();
@property int back();
}
static assert(!isRandomAccessRange!(C));
struct D
{
@property bool empty();
@property D save();
@property int front();
void popFront();
@property int back();
void popBack();
ref int opIndex(uint);
@property size_t length();
alias length opDollar;
//int opSlice(uint, uint);
}
static assert(isRandomAccessRange!(D));
static assert(isRandomAccessRange!(int[]));
}
unittest
{
// Test fix for bug 6935.
struct R
{
@disable this();
@disable static @property R init();
@property bool empty() const { return false; }
@property int front() const { return 0; }
void popFront() {}
@property R save() { return this; }
@property int back() const { return 0; }
void popBack(){}
int opIndex(size_t n) const { return 0; }
@property size_t length() const { return 0; }
alias length opDollar;
void put(int e){ }
}
static assert(isInputRange!R);
static assert(isForwardRange!R);
static assert(isBidirectionalRange!R);
static assert(isRandomAccessRange!R);
static assert(isOutputRange!(R, int));
}
/**
Returns $(D true) iff the range supports the $(D moveFront) primitive,
as well as $(D moveBack) and $(D moveAt) if it's a bidirectional or
random access range. These may be explicitly implemented, or may work
via the default behavior of the module level functions $(D moveFront)
and friends.
*/
template hasMobileElements(R)
{
enum bool hasMobileElements = is(typeof(
{
R r = void;
return moveFront(r);
}))
&& (!isBidirectionalRange!R || is(typeof(
{
R r = void;
return moveBack(r);
})))
&& (!isRandomAccessRange!R || is(typeof(
{
R r = void;
return moveAt(r, 0);
})));
}
unittest
{
static struct HasPostblit
{
this(this) {}
}
auto nonMobile = map!"a"(repeat(HasPostblit.init));
static assert(!hasMobileElements!(typeof(nonMobile)));
static assert(hasMobileElements!(int[]));
static assert(hasMobileElements!(typeof(iota(1000))));
}
/**
The element type of $(D R). $(D R) does not have to be a range. The