-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathLazy.swift.gyb
1425 lines (1198 loc) · 44.9 KB
/
Lazy.swift.gyb
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
//===--- Lazy.swift - Tests for LazySequence and LazyCollection -----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swiftgyb
// REQUIRES: executable_test
// REQUIRES: reflection
// With a non-optimized stdlib the test takes very long.
// REQUIRES: optimized_stdlib
import StdlibUnittest
import StdlibCollectionUnittest
% from gyb_stdlib_support import TRAVERSALS, collectionForTraversal
var LazyTestSuite = TestSuite("Lazy")
protocol TestProtocol1 {}
//===----------------------------------------------------------------------===//
// repeatElement(), Repeated<Element>
//===----------------------------------------------------------------------===//
// Check that the generic parameter is called 'Element'.
extension Repeated where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
LazyTestSuite.test("Repeated/AssociatedTypes") {
typealias Subject = Repeated<OpaqueValue<Int>>
expectRandomAccessCollectionAssociatedTypes(
collectionType: Subject.self,
iteratorType: IndexingIterator<Subject>.self,
subSequenceType: Slice<Subject>.self,
indexType: Int.self,
indicesType: Range<Int>.self)
}
LazyTestSuite.test("repeatedValue()/TypeInference") {
var r = repeatElement(OpaqueValue(42), count: 42)
expectType(Repeated<OpaqueValue<Int>>.self, &r)
}
LazyTestSuite.test("repeatedValue()/NegativeCount") {
expectCrashLater()
_ = repeatElement(OpaqueValue(42), count: -1)
}
LazyTestSuite.test("Repeated")
.forEach(in: [ 0, 1, 3 ]) {
count in
let c = repeatElement(OpaqueValue(42), count: count)
expectEqual(0, c.startIndex)
expectEqual(count, c.endIndex)
expectEqual(count, c.count)
expectEqual(42, c.repeatedValue.value)
let expected = (0..<count).map { _ in OpaqueValue(42) }
checkRandomAccessCollection(expected, c) { $0.value == $1.value }
}
// FIXME: trap tests.
//===----------------------------------------------------------------------===//
// IteratorOverOne
//===----------------------------------------------------------------------===//
// Check that the generic parameter is called 'Element'.
// FIXME: this should be extension CollectionOfOne.Iterator, but this needs
// a fix to the compiler.
extension IteratorOverOne where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
LazyTestSuite.test("IteratorOverOne") {
checkIterator(
[] as Array<OpaqueValue<Int>>,
CollectionOfOne.Iterator(_elements: nil as Optional<OpaqueValue<Int>>))
{ $0.value == $1.value }
checkIterator(
[ OpaqueValue(42) ] as Array<OpaqueValue<Int>>,
CollectionOfOne.Iterator(_elements: OpaqueValue(42)))
{ $0.value == $1.value }
}
//===----------------------------------------------------------------------===//
// CollectionOfOne
//===----------------------------------------------------------------------===//
// Check that the generic parameter is called 'Element'.
extension CollectionOfOne where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
LazyTestSuite.test("CollectionOfOne") {
let c = CollectionOfOne(OpaqueValue(42))
expectEqual(0, c.startIndex)
expectEqual(1, c.endIndex)
expectEqual(0..<1, c.indices)
checkRandomAccessCollection(
[ OpaqueValue(42) ], c) { $0.value == $1.value }
}
LazyTestSuite.test("CollectionOfOne/AssociatedTypes") {
typealias Subject = CollectionOfOne<OpaqueValue<Int>>
expectRandomAccessCollectionAssociatedTypes(
collectionType: Subject.self,
iteratorType: Subject.Iterator.self,
subSequenceType: Slice<Subject>.self,
indexType: Int.self,
indicesType: Range<Int>.self)
}
let collectionOfOneIndexTests: [(String,(inout CollectionOfOne<OpaqueValue<Int>>,Int)->Void,[Int])] = [
("index(after:)", { _ = $0.index(after: $1) }, [-2, -1, 1, 2]),
("index(before:)", { _ = $0.index(before: $1) }, [-1, 0, 2]),
("subscript(Index)/Get", { _ = $0[$1] }, [-2, -1, 1, 2]),
("subscript(Index)/Set", { $0[$1] = OpaqueValue(42) }, [-2, -1, 1, 2]),
]
for (name,operation,indices) in collectionOfOneIndexTests {
LazyTestSuite.test("CollectionOfOne/\(name)")
.forEach(in: indices) { i in
var c = CollectionOfOne<OpaqueValue<Int>>(OpaqueValue(42))
expectCrashLater()
operation(&c,i)
}
}
LazyTestSuite.test("CollectionOfOne/index(after:), index(before:)") {
let c = CollectionOfOne<OpaqueValue<Int>>(OpaqueValue(42))
expectEqual(1, c.index(after: 0))
expectEqual(0, c.index(before: 1))
}
LazyTestSuite.test("CollectionOfOne/subscript(Index)/Get/Set/NoTrap") {
var c = CollectionOfOne<OpaqueValue<Int>>(OpaqueValue(42))
c[0] = OpaqueValue(4242)
expectEqual(4242, c[0].value)
expectEqualSequence([OpaqueValue(4242)], c) { $0.value == $1.value }
}
let collectionOfOneInvalidRanges = [-1 ..< -1, -1..<0, -1..<1, 1..<2, 2..<2]
LazyTestSuite.test("CollectionOfOne/subscript(Range<Index>)/Get/Trap")
.forEach(in: collectionOfOneInvalidRanges) { r in
let c = CollectionOfOne<OpaqueValue<Int>>(OpaqueValue(42))
expectCrashLater()
_ = c[r]
}
LazyTestSuite.test("CollectionOfOne/subscript(Range<Index>)/Set/Trap")
.forEach(in: collectionOfOneInvalidRanges) { r in
var c = CollectionOfOne<OpaqueValue<Int>>(OpaqueValue(42))
let slice = r.count == 0 ? c[0..<0] : c[0..<1]
expectCrashLater()
c[r] = slice
}
LazyTestSuite.test("CollectionOfOne/subscript(Range<Index>)/Set/DifferentLength/Trap")
.forEach(in: [ 0..<0, 0..<1, 1..<1 ] as [Range<Int>]) {
r in
var c = CollectionOfOne<OpaqueValue<Int>>(OpaqueValue(42))
let slice = r.count == 0 ? c[0..<1] : c[0..<0]
expectCrashLater()
c[r] = slice
}
LazyTestSuite.test("CollectionOfOne/subscript(Range<Index>)/Get/Set/Empty/NoTrap") {
var c = CollectionOfOne<OpaqueValue<Int>>(OpaqueValue(42))
let slice0 = c[0..<0]
let slice1 = c[1..<1]
checkRandomAccessCollection([], slice0) { $0.value == $1.value }
checkRandomAccessCollection([], slice1) { $0.value == $1.value }
c[0..<0] = slice0
c[0..<0] = slice1
c[1..<1] = slice0
c[1..<1] = slice1
expectEqualSequence([OpaqueValue(42)], c) { $0.value == $1.value }
}
LazyTestSuite.test("CollectionOfOne/{CustomDebugStringConvertible,CustomReflectable}") {
let c = CollectionOfOne(CustomPrintableValue(42))
expectPrinted("CollectionOfOne((value: 42).debugDescription)", c)
expectDebugPrinted("CollectionOfOne((value: 42).debugDescription)", c)
expectDumped(
"▿ CollectionOfOne((value: 42).debugDescription)\n" +
" ▿ element: (value: 42).debugDescription\n" +
" - value: 42\n" +
" - identity: 0\n",
c)
}
//===----------------------------------------------------------------------===//
// EmptyCollection
//===----------------------------------------------------------------------===//
// Check that the generic parameter is called 'Element'.
extension EmptyCollection where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
LazyTestSuite.test("EmptyCollection") {
let c = EmptyCollection<OpaqueValue<Int>>()
expectEqual(0, c.startIndex)
expectEqual(0, c.endIndex)
expectEqual(0..<0, c.indices)
checkRandomAccessCollection([], c) { $0.value == $1.value }
}
LazyTestSuite.test("EmptyCollection/CustomReflectable") {
let c = EmptyCollection<OpaqueValue<Int>>()
expectPrinted("EmptyCollection<OpaqueValue<Int>>()", c)
expectDebugPrinted("Swift.EmptyCollection<StdlibUnittest.OpaqueValue<Swift.Int>>()", c)
expectDumped(
"- Swift.EmptyCollection<StdlibUnittest.OpaqueValue<Swift.Int>>\n",
c)
}
LazyTestSuite.test("EmptyCollection/Equatable") {
let instances = [ EmptyCollection<OpaqueValue<Int>>() ]
checkEquatable(instances, oracle: { $0 == $1 })
}
LazyTestSuite.test("EmptyCollection/AssociatedTypes") {
typealias Subject = EmptyCollection<OpaqueValue<Int>>
expectRandomAccessCollectionAssociatedTypes(
collectionType: Subject.self,
iteratorType: EmptyCollection<OpaqueValue<Int>>.Iterator.self,
subSequenceType: Subject.self,
indexType: Int.self,
indicesType: Range<Int>.self)
}
let emptyCollectionIndexTests: [(String,(inout EmptyCollection<OpaqueValue<Int>>,Int)->Void)] = [
("index(after:)", { _ = $0.index(after: $1) }),
("index(before:)", { _ = $0.index(before: $1) }),
("subscript(Index)/Get", { _ = $0[$1] }),
("subscript(Index)/Set", { $0[$1] = OpaqueValue(42) }),
]
for (name,operation) in emptyCollectionIndexTests {
LazyTestSuite.test("EmptyCollection/\(name)")
.forEach(in: [-1, 0, 1]) { i in
var c = EmptyCollection<OpaqueValue<Int>>()
expectCrashLater()
operation(&c,i)
}
}
% for (name, operation) in [
% ('subscript(Range<Index>)/Get', '_ = c[r]'),
% ('subscript(Range<Index>)/Set', 'c[r] = c'),
% ]:
LazyTestSuite.test("EmptyCollection/${name}/Trap")
.forEach(in: [-1 ..< -1, -1..<0, -1..<1, 0..<1, 1..<1] as [Range<Int>]) {
r in
var c = EmptyCollection<OpaqueValue<Int>>()
// Access is guarded by a _debugPrecondition in EmptyCollection
if _isDebugAssertConfiguration() {
expectCrashLater()
}
${operation}
}
LazyTestSuite.test("EmptyCollection/${name}/NoTrap") {
var c = EmptyCollection<OpaqueValue<Int>>()
let r: Range<Int> = 0..<0
${operation}
expectEqualSequence([], c[0..<0]) { $0.value == $1.value }
}
% end
LazyTestSuite.test("EmptyCollection/index(_:offsetBy:)/Trap")
.forEach(in: [
(-1, -1), (-1, 0), (-1, 1),
(0, 1), (0, -1),
(1, -1), (1, 0), (1, 1),
]) {
(i, offset) in
let c = EmptyCollection<OpaqueValue<Int>>()
// Access is guarded by a _debugPrecondition in EmptyCollection
if _isDebugAssertConfiguration() {
expectCrashLater()
}
_ = c.index(i, offsetBy: offset)
}
LazyTestSuite.test("EmptyCollection/index(_:offsetBy:)/NoTrap") {
let c = EmptyCollection<OpaqueValue<Int>>()
expectEqual(c.startIndex, c.index(c.startIndex, offsetBy: 0))
}
LazyTestSuite.test("EmptyCollection/index(_:offsetBy:limitedBy:)/Trap")
.forEach(in: [
(-1, 0, 0), (-1, 1, 0),
(0, 0, -1), (0, 0, 1),
(1, -1, 0), (1, 0, 0), (1, 0, 1),
]) {
(i, offset, limit) in
let c = EmptyCollection<OpaqueValue<Int>>()
// Access is guarded by a _debugPrecondition in EmptyCollection
if _isDebugAssertConfiguration() {
expectCrashLater()
}
_ = c.index(i, offsetBy: offset, limitedBy: limit)
}
LazyTestSuite.test("EmptyCollection/index(_:offsetBy:limitedBy:)/NoTrap")
.forEach(in: [
-10, -1, 0, 1, 10,
]) {
offset in
let c = EmptyCollection<OpaqueValue<Int>>()
let result =
c.index(c.startIndex, offsetBy: offset, limitedBy: c.startIndex)
if offset == 0 {
expectEqual(c.startIndex, result)
} else {
expectNil(result)
}
}
LazyTestSuite.test("EmptyCollection/distance(from:to:)/Trap")
.forEach(in: [
(-1, -1), (-1, 0), (-1, 1),
(0, 1), (0, -1),
(1, -1), (1, 0), (1, 1),
]) {
(start, end) in
let c = EmptyCollection<OpaqueValue<Int>>()
// Access is guarded by a _debugPrecondition in EmptyCollection
if _isDebugAssertConfiguration() {
expectCrashLater()
}
_ = c.distance(from: start, to: end)
}
LazyTestSuite.test("EmptyCollection/distance(from:to:)/NoTrap") {
let c = EmptyCollection<OpaqueValue<Int>>()
expectEqual(0, c.distance(from: 0, to: 0))
}
LazyTestSuite.test("EmptyCollection/_failEarlyRangeCheck/NoTrap") {
let c = EmptyCollection<OpaqueValue<Int>>()
c._failEarlyRangeCheck(0, bounds: 0..<0)
c._failEarlyRangeCheck(0..<0, bounds: 0..<0)
}
//===----------------------------------------------------------------------===//
// EmptyIterator
//===----------------------------------------------------------------------===//
// Check that the generic parameter is called 'Element'.
extension EmptyIterator where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
LazyTestSuite.test("EmptyIterator") {
checkIterator(
[] as Array<OpaqueValue<Int>>,
EmptyCollection<OpaqueValue<Int>>.Iterator())
{ $0.value == $1.value }
}
// FIXME: trap tests.
//===----------------------------------------------------------------------===//
// lazy
//===----------------------------------------------------------------------===//
LazyTestSuite.test("isEmpty") {
expectTrue((0..<0).lazy.isEmpty)
expectFalse((0...0).lazy.isEmpty)
}
LazyTestSuite.test("first") {
expectEqual(7, (7..<42).lazy.first)
}
LazyTestSuite.test("first empty") {
expectNil((7..<7).lazy.first)
}
LazyTestSuite.test("last") {
expectEqual(41, (7..<42).lazy.last)
}
LazyTestSuite.test("last empty") {
expectNil((7..<7).lazy.last)
}
//===----------------------------------------------------------------------===//
// LazySequence
//===----------------------------------------------------------------------===//
// Check that the generic parameter is called 'Base'.
extension LazySequence where Base : TestProtocol1 {
var _baseIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
LazyTestSuite.test("LazySequence<Sequence>/underestimatedCount") {
let s = MinimalSequence(
elements: [ 0, 30, 10, 90 ].map(OpaqueValue.init),
underestimatedCount: .value(42))
var lazySeq = s.lazy
expectType(LazySequence<MinimalSequence<OpaqueValue<Int>>>.self, &lazySeq)
expectEqual(42, lazySeq.underestimatedCount)
}
% for Traversal in TRAVERSALS:
% TraversalCollection = collectionForTraversal(Traversal)
LazyTestSuite.test("LazySequence<${TraversalCollection}>/underestimatedCount") {
let s = Minimal${TraversalCollection}(
elements: [ 0, 30, 10, 90 ].map(OpaqueValue.init),
underestimatedCount: .value(42))
var lazySeq = s.lazy
expectType(
LazyCollection<
Minimal${TraversalCollection}<OpaqueValue<Int>>
>.self,
&lazySeq)
expectEqual(42, lazySeq.underestimatedCount)
}
% end
//===----------------------------------------------------------------------===//
// MapSequence
//===----------------------------------------------------------------------===//
LazyTestSuite.test("MapSequence<Sequence>/underestimatedCount") {
let s = MinimalSequence(
elements: [ 0, 30, 10, 90 ].map(OpaqueValue.init),
underestimatedCount: .value(42))
var lazyMap = s.lazy.map { OpaqueValue(Int32($0.value)) }
expectType(
LazyMapSequence<MinimalSequence<OpaqueValue<Int>>, OpaqueValue<Int32>>.self,
&lazyMap)
expectEqual(42, lazyMap.underestimatedCount)
}
struct SequenceWithCustomUnderestimatedCount : Sequence {
init(_ data: [Int]) {
self._data = MinimalSequence(elements: data.map(OpaqueValue.init))
}
func makeIterator() -> MinimalSequence<OpaqueValue<Int>>.Iterator {
return _data.makeIterator()
}
var underestimatedCount: Int {
SequenceWithCustomUnderestimatedCount.timesUnderestimatedCountWasCalled += 1
return _data.underestimatedCount
}
static var timesUnderestimatedCountWasCalled: Int = 0
let _data: MinimalSequence<OpaqueValue<Int>>
}
LazyTestSuite.test("LazySequence.array") {
SequenceWithCustomUnderestimatedCount.timesUnderestimatedCountWasCalled = 0
let base = SequenceWithCustomUnderestimatedCount([ 0, 30, 10, 90 ])
expectEqual([ 0, 30, 10, 90 ], base.lazy.map { $0.value })
// Lazy sequences should use underestimated count to preallocate array
// storage.
expectEqual(1, SequenceWithCustomUnderestimatedCount.timesUnderestimatedCountWasCalled)
expectEqualSequence(
[], Array(base).map { $0.value }, "sequence should be consumed")
}
% for Traversal in TRAVERSALS:
% TraversalCollection = collectionForTraversal(Traversal)
LazyTestSuite.test("MapCollection<${TraversalCollection}>/underestimatedCount") {
let s = Minimal${TraversalCollection}(
elements: [ 0, 30, 10, 90 ].map(OpaqueValue.init),
underestimatedCount: .value(42))
var lazyMap = s.lazy.map {
(input: OpaqueValue<Int>) -> OpaqueValue<Int32> in
OpaqueValue(Int32(input.value))
}
expectType(
LazyMapCollection<
Minimal${TraversalCollection}<OpaqueValue<Int>>, OpaqueValue<Int32>
>.self,
&lazyMap)
expectEqual(42, lazyMap.underestimatedCount)
}
% end
//===----------------------------------------------------------------------===//
// LazyCollection
//===----------------------------------------------------------------------===//
// Check that the generic parameter is called 'Base'.
extension LazyCollection where Base : TestProtocol1 {
var _baseIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
%for (Traversal, ReversedType) in [
% ('Forward', None),
% ('Bidirectional', 'ReversedCollection'),
% ('RandomAccess', 'ReversedCollection')
%]:
% TraversalCollection = collectionForTraversal(Traversal)
LazyTestSuite.test("Lazy${TraversalCollection}.array") {
let base = Minimal${TraversalCollection}(
elements: [ 0, 30, 10, 90 ], underestimatedCount: .value(42))
let arrayFromLazy = Array(base.lazy)
expectEqual([ 0, 30, 10, 90 ], arrayFromLazy)
// Lazy collections should not use underestimated count to preallocate array
// storage, since they have access to real count instead.
expectLE(4, arrayFromLazy.capacity)
expectGE(40, arrayFromLazy.capacity)
}
% if ReversedType is not None:
LazyTestSuite.test("Lazy${TraversalCollection}.reversed") {
let base = Minimal${TraversalCollection}(
elements: [ 0, 30, 10, 90 ].map(OpaqueValue.init),
underestimatedCount: .value(42))
var reversed = base.lazy.reversed()
expectType(
${ReversedType}<LazyCollection
<Minimal${TraversalCollection}<OpaqueValue<Int>>>
>.self, &reversed)
let expected: [OpaqueValue<Int>] = [ 90, 10, 30, 0 ].map(OpaqueValue.init)
check${Traversal}Collection(expected, reversed) { $0.value == $1.value }
var reversedTwice = reversed.reversed()
expectType(
${ReversedType}<${ReversedType}<LazyCollection<
Minimal${TraversalCollection}<OpaqueValue<Int>>
>>>.self, &reversedTwice)
check${Traversal}Collection(
[ 0, 30, 10, 90 ].map(OpaqueValue.init) as [OpaqueValue<Int>],
reversedTwice) { $0.value == $1.value }
}
% end
%end
//===----------------------------------------------------------------------===//
// ReversedCollection
//===----------------------------------------------------------------------===//
// Check that the generic parameter is called 'Base'.
extension ReversedCollection where Base : TestProtocol1 {
var _baseIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
//===----------------------------------------------------------------------===//
// ReversedIndex
//===----------------------------------------------------------------------===//
// Check that the generic parameter is called 'Base'.
extension ReversedCollection.Index where Base : TestProtocol1 {
var _baseIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
//===----------------------------------------------------------------------===//
// RandomAccessReversedCollection
//===----------------------------------------------------------------------===//
// Check that the generic parameter is called 'Base'.
extension ReversedCollection
where Base : TestProtocol1, Base : RandomAccessCollection {
var _baseIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
//===----------------------------------------------------------------------===//
// ReversedIndex for RandomAccessCollections
//===----------------------------------------------------------------------===//
// Check that the generic parameter is called 'Base'.
extension ReversedCollection.Index
where Base : TestProtocol1, Base : RandomAccessCollection {
var _baseIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
var tests = TestSuite("NewLazy")
tests.test("LazySequence/Sequence") {
let expected = (0..<100).map(OpaqueValue.init)
var actual = MinimalSequence(elements: expected).lazy
expectType(
LazySequence<MinimalSequence<OpaqueValue<Int>>>.self, &actual)
// Asking for .lazy again doesn't re-wrap the type
var again = actual.lazy
expectType(
LazySequence<MinimalSequence<OpaqueValue<Int>>>.self, &again)
var elements = actual.elements
// Expect .elements to strip a lazy wrapper
expectType(MinimalSequence<OpaqueValue<Int>>.self, &elements)
checkSequence(expected, actual, resiliencyChecks: .none) {
$0.value == $1.value
}
}
func expectSequencePassthrough<
S : LazySequenceProtocol,
Base : Sequence
>(_ s: S, base: Base, arbitraryElement: S.Iterator.Element, count: Int)
where Base : LoggingType,
Base.Iterator.Element == S.Iterator.Element {
let baseType = type(of: base)
SequenceLog.makeIterator.expectIncrement(baseType) { _ = s.makeIterator() }
SequenceLog.underestimatedCount.expectIncrement(baseType) {
_ = s.underestimatedCount
}
SequenceLog._customContainsEquatableElement.expectIncrement(baseType) {
_ = s._customContainsEquatableElement(arbitraryElement)
}
SequenceLog._copyToContiguousArray.expectIncrement(baseType) {
_ = s._copyToContiguousArray()
}
SequenceLog._copyContents.expectIncrement(baseType) { () -> Void in
let ptr = UnsafeMutablePointer<S.Iterator.Element>.allocate(capacity: count)
let buf = UnsafeMutableBufferPointer(start: ptr, count: count)
var (remainders,writtenUpTo) = s._copyContents(initializing: buf)
expectTrue(remainders.next() == nil,
"_copyContents returned unwritten elements")
expectTrue(writtenUpTo == buf.endIndex,
"_copyContents failed to use entire buffer")
ptr.deinitialize(count: count)
ptr.deallocate()
}
}
tests.test("LazySequence/Passthrough") {
// Test that operations that might be optimized are passed
// through to the underlying sequence.
let a = (0..<100).map(OpaqueValue.init)
let base = LoggingSequence(wrapping: a)
expectSequencePassthrough(
base.lazy,
base: base, arbitraryElement: OpaqueValue(0), count: a.count)
}
% for Traversal in TRAVERSALS:
% TraversalCollection = collectionForTraversal(Traversal)
tests.test("Lazy${TraversalCollection}/Collection") {
let expected = (0..<100).map(OpaqueValue.init)
let base = Minimal${TraversalCollection}(elements: expected)
var actual = base.lazy
expectType(LazyCollection<
Minimal${TraversalCollection}<OpaqueValue<Int>>
>.self, &actual)
// Asking for .lazy again doesn't re-wrap the type
var again = actual.lazy
expectType(LazyCollection<
Minimal${TraversalCollection}<OpaqueValue<Int>>
>.self, &again)
checkOneLevelOf${Traversal}Collection(
expected, base.lazy, resiliencyChecks: .none
) { $0.value == $1.value }
var elements = base.lazy.elements
expectType(Minimal${TraversalCollection}<OpaqueValue<Int>>.self, &elements)
}
% end
tests.test("LazyCollection/Passthrough") {
let expected = (0..<100).map(OpaqueValue.init)
let base = LoggingCollection(wrapping: expected)
expectSequencePassthrough(
base.lazy,
base: base.lazy.elements,
arbitraryElement: OpaqueValue(0),
count: Int(expected.count))
let s = base.lazy
let baseType = type(of: base)
let startIndex = CollectionLog.startIndex.expectIncrement(baseType) {
s.startIndex
}
let endIndex = CollectionLog.endIndex.expectIncrement(baseType) {
s.endIndex
}
CollectionLog.subscriptIndex.expectIncrement(baseType) { _ = s[startIndex] }
CollectionLog.subscriptRange.expectUnchanged(baseType) {
_ = s[startIndex..<endIndex]
}
CollectionLog.isEmpty.expectIncrement(baseType) { _ = s.isEmpty }
CollectionLog.count.expectIncrement(baseType) { _ = s.count }
CollectionLog._customIndexOfEquatableElement.expectIncrement(baseType) {
_ = s._customIndexOfEquatableElement(OpaqueValue(0))
}
}
//===--- Map --------------------------------------------------------------===//
tests.test("LazyMapSequence") {
let base = MinimalSequence(
elements: [2, 3, 5, 7, 11].map(OpaqueValue.init)).lazy
var calls = 0
var mapped = base.map {
(x: OpaqueValue<Int>) -> OpaqueValue<Double> in
calls += 1
return OpaqueValue(Double(x.value) / 2.0)
}
expectEqual(0, calls)
expectType(
LazyMapSequence<
MinimalSequence<OpaqueValue<Int>>,
OpaqueValue<Double>>.self,
&mapped)
let expected = [ 1.0, 1.5, 2.5, 3.5, 5.5 ].map(OpaqueValue.init)
checkSequence(expected, mapped, resiliencyChecks: .none) {
$0.value == $1.value
}
expectEqual(expected.count, calls)
}
tests.test("MapSequence/Passthrough") {
let expected = (0..<100).map(OpaqueValue.init)
let base = LoggingSequence(wrapping: expected)
let mapped = base.lazy.map { OpaqueValue(Double($0.value) / 2.0) }
CollectionLog.underestimatedCount.expectIncrement(type(of: base)) {
_ = mapped.underestimatedCount
}
// Not exactly passthrough because we wrap the result
CollectionLog.makeIterator.expectIncrement(type(of: base)) {
_ = mapped.makeIterator()
}
}
% for Traversal in TRAVERSALS:
% TraversalCollection = collectionForTraversal(Traversal)
tests.test("LazyMap${TraversalCollection}/Collection") {
let base = Minimal${TraversalCollection}(
elements: [2, 3, 5, 7, 11].map(OpaqueValue.init)).lazy
var calls = 0
var mapped = base.map {
(x: OpaqueValue<Int>) -> OpaqueValue<Double> in
calls += 1
return OpaqueValue(Double(x.value) / 2.0)
}
expectEqual(0, calls)
expectType(
LazyMapCollection<
Minimal${TraversalCollection}<OpaqueValue<Int>>,
OpaqueValue<Double>>.self,
&mapped)
let expected = [ 1.0, 1.5, 2.5, 3.5, 5.5 ].map(OpaqueValue.init)
check${Traversal}Collection(expected, mapped, resiliencyChecks: .none) {
$0.value == $1.value
}
// check${Traversal}Collection makes multiple passes over the input,
// so we test that each element was transformed *at least* once.
expectLE(expected.count, calls)
}
%end
tests.test("LazyMapCollection/Passthrough") {
let expected = (0..<100).map(OpaqueValue.init)
let base = LoggingCollection(wrapping: expected)
let mapped = base.lazy.map { OpaqueValue(Double($0.value) / 2.0) }
let startIndex = CollectionLog.startIndex.expectIncrement(type(of: base)) {
mapped.startIndex
}
_ = CollectionLog.endIndex.expectIncrement(type(of: base)) {
mapped.endIndex
}
// Not exactly passthrough, because mapping transforms the result
CollectionLog.subscriptIndex.expectIncrement(type(of: base)) {
_ = mapped[startIndex]
}
CollectionLog.isEmpty.expectIncrement(type(of: base)) {
_ = mapped.isEmpty
}
CollectionLog.underestimatedCount.expectIncrement(type(of: base)) {
_ = mapped.underestimatedCount
}
// Not exactly passthrough because we wrap the result
CollectionLog.makeIterator.expectIncrement(type(of: base)) {
_ = mapped.makeIterator()
}
}
tests.test("LazyMapSequence/AssociatedTypes") {
typealias Base = MinimalSequence<OpaqueValue<Int>>
typealias Subject = LazyMapSequence<Base, OpaqueValue<Int32>>
expectSequenceAssociatedTypes(
sequenceType: Subject.self,
iteratorType: LazyMapSequence<Base, OpaqueValue<Int32>>.Iterator.self)
}
tests.test("LazyMapCollection/AssociatedTypes") {
typealias Base = MinimalCollection<OpaqueValue<Int>>
typealias Subject = LazyMapCollection<Base, OpaqueValue<Int32>>
expectCollectionAssociatedTypes(
collectionType: Subject.self,
iteratorType: LazyMapCollection<Base, OpaqueValue<Int32>>.Iterator.self,
subSequenceType: LazyMapCollection<Base.SubSequence, OpaqueValue<Int32>>.self,
indexType: Base.Index.self,
indicesType: Base.Indices.self)
}
tests.test("LazyMapBidirectionalCollection/AssociatedTypes") {
typealias Base = MinimalBidirectionalCollection<OpaqueValue<Int>>
typealias Subject = LazyMapCollection<Base, OpaqueValue<Int32>>
expectBidirectionalCollectionAssociatedTypes(
collectionType: Subject.self,
iteratorType: LazyMapCollection<Base, OpaqueValue<Int32>>.Iterator.self,
subSequenceType: LazyMapCollection<Base.SubSequence, OpaqueValue<Int32>>.self,
indexType: Base.Index.self,
indicesType: Base.Indices.self)
}
tests.test("LazyMapRandomAccessCollection/AssociatedTypes") {
typealias Base = MinimalRandomAccessCollection<OpaqueValue<Int>>
typealias Subject = LazyMapCollection<Base, OpaqueValue<Int32>>
expectRandomAccessCollectionAssociatedTypes(
collectionType: Subject.self,
iteratorType: LazyMapCollection<Base, OpaqueValue<Int32>>.Iterator.self,
subSequenceType: LazyMapCollection<Base.SubSequence, OpaqueValue<Int32>>.self,
indexType: Base.Index.self,
indicesType: Base.Indices.self)
}
tests.test("lazy.mapped/TypeInference") {
let baseArray: [OpaqueValue<Int>] = (0..<10).map(OpaqueValue.init)
do {
var mapped = MinimalSequence(elements: baseArray)
.lazy.map { _ in OpaqueValue<Int8>(0) }
expectType(
LazyMapSequence<
MinimalSequence<OpaqueValue<Int>>,
OpaqueValue<Int8>
>.self,
&mapped)
}
do {
var mapped = MinimalCollection(elements: baseArray)
.lazy.map { _ in OpaqueValue<Int8>(0) }
expectType(
LazyMapCollection<
MinimalCollection<OpaqueValue<Int>>,
OpaqueValue<Int8>
>.self,
&mapped)
}
do {
var mapped = MinimalBidirectionalCollection(elements: baseArray)
.lazy.map { _ in OpaqueValue<Int8>(0) }
expectType(
LazyMapCollection<
MinimalBidirectionalCollection<OpaqueValue<Int>>,
OpaqueValue<Int8>
>.self,
&mapped)
}
do {
var mapped = MinimalRandomAccessCollection(elements: baseArray)
.lazy.map { _ in OpaqueValue<Int8>(0) }
expectType(
LazyMapCollection<
MinimalRandomAccessCollection<OpaqueValue<Int>>,
OpaqueValue<Int8>
>.self,
&mapped)
}
}
//===--- Reverse ----------------------------------------------------------===//
tests.test("ReversedCollection") {
let expected = Array(stride(from: 11, through: 0, by: -1))
let r = 0..<12
checkRandomAccessCollection(
expected,
r.reversed())
// Check that the reverse collection is still eager
do {
var calls = 0
_ = r.reversed().map { _ in calls += 1 }
expectEqual(r.count, calls)
}
checkBidirectionalCollection(
"raboof",
"foobar".reversed())
// Check that the reverse collection is still eager
do {
var calls = 0
_ = "foobar".reversed().map { _ in calls += 1 }
expectEqual("foobar".count, calls)
}
}
enum _Void {}
struct ExpectType<T> {
static func test(_: T){ print("T") }
static func test(_: Any) { fatalError() }
static func test(_: Any) -> _Void { fatalError() }
}
tests.test("ReversedCollection/Lazy") {
// Check that reversing a lazy collection, or lazy-ing a reverse
// collection, produces the same lazy reverse collection.
do {
let base = Array(stride(from: 11, through: 0, by: -1)).lazy.map { $0 }
typealias Base = LazyMapCollection<[Int], Int>
ExpectType<Base>.test(base)
typealias LazyReversedBase = ReversedCollection<Base>
let reversed = base.reversed()
ExpectType<LazyReversedBase>.test(reversed)
var calls = 0
let reversedAndMapped = reversed.map { (x) -> Int in calls += 1; return x }
expectEqual(0, calls)
checkRandomAccessCollection(0...11, reversedAndMapped)
expectNotEqual(0, calls)
}
do {
let base = "foobar".lazy.map { $0 }
typealias Base = LazyMapCollection<String, Character>