forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinimalCollections.swift
6055 lines (4893 loc) · 173 KB
/
MinimalCollections.swift
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
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import StdlibUnittest
/// State shared by all generators of a MinimalSequence.
internal class _MinimalIteratorSharedState<T> {
internal init(_ data: [T]) {
self.data = data
}
internal let data: [T]
internal var i: Int = 0
internal var underestimatedCount: Int = 0
}
//===----------------------------------------------------------------------===//
// MinimalIterator
//===----------------------------------------------------------------------===//
/// An IteratorProtocol that implements the protocol contract in the most
/// narrow way possible.
///
/// This generator will return `nil` only once.
public struct MinimalIterator<T> : IteratorProtocol {
public init<S : Sequence>(_ s: S) where S.Element == T {
self._sharedState = _MinimalIteratorSharedState(Array(s))
}
public init(_ data: [T]) {
self._sharedState = _MinimalIteratorSharedState(data)
}
internal init(_ _sharedState: _MinimalIteratorSharedState<T>) {
self._sharedState = _sharedState
}
public func next() -> T? {
if _sharedState.i == _sharedState.data.count {
return nil
}
defer { _sharedState.i += 1 }
return _sharedState.data[_sharedState.i]
}
internal let _sharedState: _MinimalIteratorSharedState<T>
}
// A protocol to identify MinimalIterator.
public protocol _MinimalIterator {}
extension MinimalIterator : _MinimalIterator {}
//===----------------------------------------------------------------------===//
// MinimalSequence
//===----------------------------------------------------------------------===//
public enum UnderestimatedCountBehavior {
/// Return the actual number of elements.
case precise
/// Return the actual number of elements divided by 2.
case half
/// Return an overestimated count. Useful to test how algorithms reserve
/// memory.
case overestimate
/// Return the provided value.
case value(Int)
}
/// A Sequence that implements the protocol contract in the most
/// narrow way possible.
///
/// This sequence is consumed when its generator is advanced.
public struct MinimalSequence<T> : Sequence, CustomDebugStringConvertible {
public init<S : Sequence>(
elements: S,
underestimatedCount: UnderestimatedCountBehavior = .value(0)
) where S.Element == T {
let data = Array(elements)
self._sharedState = _MinimalIteratorSharedState(data)
switch underestimatedCount {
case .precise:
self._sharedState.underestimatedCount = data.count
case .half:
self._sharedState.underestimatedCount = data.count / 2
case .overestimate:
self._sharedState.underestimatedCount = data.count * 3 + 5
case .value(let count):
self._sharedState.underestimatedCount = count
}
}
public let timesMakeIteratorCalled = ResettableValue(0)
public func makeIterator() -> MinimalIterator<T> {
timesMakeIteratorCalled.value += 1
return MinimalIterator(_sharedState)
}
public var underestimatedCount: Int {
return Swift.max(0, self._sharedState.underestimatedCount - self._sharedState.i)
}
public var debugDescription: String {
return "MinimalSequence(\(_sharedState.data[_sharedState.i..<_sharedState.data.count]))"
}
internal let _sharedState: _MinimalIteratorSharedState<T>
}
//===----------------------------------------------------------------------===//
// Index invalidation checking
//===----------------------------------------------------------------------===//
internal enum _CollectionOperation : Equatable {
case reserveCapacity(capacity: Int)
case append
case appendContentsOf(count: Int)
case replaceRange(subRange: Range<Int>, replacementCount: Int)
case insert(atIndex: Int)
case insertContentsOf(atIndex: Int, count: Int)
case removeAtIndex(index: Int)
case removeLast
case removeRange(subRange: Range<Int>)
case removeAll(keepCapacity: Bool)
internal func _applyTo(
elementsLastMutatedStateIds: [Int],
endIndexLastMutatedStateId: Int,
nextStateId: Int
) -> ([Int], Int) {
var newElementsIds = elementsLastMutatedStateIds
var newEndIndexId = endIndexLastMutatedStateId
switch self {
case .reserveCapacity:
let invalidIndices = newElementsIds.indices
newElementsIds.replaceSubrange(
invalidIndices,
with: repeatElement(nextStateId, count: invalidIndices.count))
newEndIndexId = nextStateId
case .append:
newElementsIds.append(nextStateId)
newEndIndexId = nextStateId
case .appendContentsOf(let count):
newElementsIds.append(contentsOf:
repeatElement(nextStateId, count: count))
newEndIndexId = nextStateId
case .replaceRange(let subRange, let replacementCount):
newElementsIds.replaceSubrange(
subRange,
with: repeatElement(nextStateId, count: replacementCount))
let invalidIndices = subRange.lowerBound..<newElementsIds.endIndex
newElementsIds.replaceSubrange(
invalidIndices,
with: repeatElement(nextStateId, count: invalidIndices.count))
newEndIndexId = nextStateId
case .insert(let atIndex):
newElementsIds.insert(nextStateId, at: atIndex)
let invalidIndices = atIndex..<newElementsIds.endIndex
newElementsIds.replaceSubrange(
invalidIndices,
with: repeatElement(nextStateId, count: invalidIndices.count))
newEndIndexId = nextStateId
case .insertContentsOf(let atIndex, let count):
newElementsIds.insert(
contentsOf: repeatElement(nextStateId, count: count),
at: atIndex)
let invalidIndices = atIndex..<newElementsIds.endIndex
newElementsIds.replaceSubrange(
invalidIndices,
with: repeatElement(nextStateId, count: invalidIndices.count))
newEndIndexId = nextStateId
case .removeAtIndex(let index):
newElementsIds.remove(at: index)
let invalidIndices = index..<newElementsIds.endIndex
newElementsIds.replaceSubrange(
invalidIndices,
with: repeatElement(nextStateId, count: invalidIndices.count))
newEndIndexId = nextStateId
case .removeLast:
newElementsIds.removeLast()
newEndIndexId = nextStateId
case .removeRange(let subRange):
newElementsIds.removeSubrange(subRange)
let invalidIndices = subRange.lowerBound..<newElementsIds.endIndex
newElementsIds.replaceSubrange(
invalidIndices,
with: repeatElement(nextStateId, count: invalidIndices.count))
newEndIndexId = nextStateId
case .removeAll(let keepCapacity):
newElementsIds.removeAll(keepingCapacity: keepCapacity)
newEndIndexId = nextStateId
}
return (newElementsIds, newEndIndexId)
}
}
internal func == (
lhs: _CollectionOperation,
rhs: _CollectionOperation
) -> Bool {
switch (lhs, rhs) {
case (.reserveCapacity(let lhsCapacity), .reserveCapacity(let rhsCapacity)):
return lhsCapacity == rhsCapacity
case (.append, .append):
return true
case (.appendContentsOf(let lhsCount), .appendContentsOf(let rhsCount)):
return lhsCount == rhsCount
case (
.replaceRange(let lhsSubRange, let lhsReplacementCount),
.replaceRange(let rhsSubRange, let rhsReplacementCount)):
return lhsSubRange == rhsSubRange &&
lhsReplacementCount == rhsReplacementCount
case (.insert(let lhsAtIndex), .insert(let rhsAtIndex)):
return lhsAtIndex == rhsAtIndex
case (
.insertContentsOf(let lhsAtIndex, let lhsCount),
.insertContentsOf(let rhsAtIndex, let rhsCount)):
return lhsAtIndex == rhsAtIndex && lhsCount == rhsCount
case (.removeAtIndex(let lhsIndex), .removeAtIndex(let rhsIndex)):
return lhsIndex == rhsIndex
case (.removeLast, .removeLast):
return true
case (.removeRange(let lhsSubRange), .removeRange(let rhsSubRange)):
return lhsSubRange == rhsSubRange
case (.removeAll(let lhsKeepCapacity), .removeAll(let rhsKeepCapacity)):
return lhsKeepCapacity == rhsKeepCapacity
default:
return false
}
}
public struct _CollectionState : Equatable, Hashable {
internal static var _nextUnusedState: Int = 0
internal static var _namedStates: [String : _CollectionState] = [:]
internal let _id: Int
internal let _elementsLastMutatedStateIds: [Int]
internal let _endIndexLastMutatedStateId: Int
internal init(
id: Int,
elementsLastMutatedStateIds: [Int],
endIndexLastMutatedStateId: Int) {
self._id = id
self._elementsLastMutatedStateIds = elementsLastMutatedStateIds
self._endIndexLastMutatedStateId = endIndexLastMutatedStateId
}
public init(newRootStateForElementCount count: Int) {
self._id = _CollectionState._nextUnusedState
_CollectionState._nextUnusedState += 1
self._elementsLastMutatedStateIds =
Array(repeatElement(self._id, count: count))
self._endIndexLastMutatedStateId = self._id
}
internal init(name: String, elementCount: Int) {
if let result = _CollectionState._namedStates[name] {
self = result
} else {
self = _CollectionState(newRootStateForElementCount: elementCount)
_CollectionState._namedStates[name] = self
}
}
public func hash(into hasher: inout Hasher) {
hasher.combine(_id)
}
}
public func == (lhs: _CollectionState, rhs: _CollectionState) -> Bool {
return lhs._id == rhs._id
}
internal struct _CollectionStateTransition {
internal let _previousState: _CollectionState
internal let _operation: _CollectionOperation
internal let _nextState: _CollectionState
internal static var _allTransitions:
[_CollectionState : Box<[_CollectionStateTransition]>] = [:]
internal init(
previousState: _CollectionState,
operation: _CollectionOperation,
nextState: _CollectionState
) {
var transitions =
_CollectionStateTransition._allTransitions[previousState]
if transitions == nil {
transitions = Box<[_CollectionStateTransition]>([])
_CollectionStateTransition._allTransitions[previousState] = transitions
}
if let i = transitions!.value.firstIndex(where: { $0._operation == operation }) {
self = transitions!.value[i]
return
}
self._previousState = previousState
self._operation = operation
self._nextState = nextState
transitions!.value.append(self)
}
internal init(
previousState: _CollectionState,
operation: _CollectionOperation
) {
let nextStateId = _CollectionState._nextUnusedState
_CollectionState._nextUnusedState += 1
let (newElementStates, newEndIndexState) = operation._applyTo(
elementsLastMutatedStateIds: previousState._elementsLastMutatedStateIds,
endIndexLastMutatedStateId: previousState._endIndexLastMutatedStateId,
nextStateId: nextStateId)
let nextState = _CollectionState(
id: nextStateId,
elementsLastMutatedStateIds: newElementStates,
endIndexLastMutatedStateId: newEndIndexState)
self = _CollectionStateTransition(
previousState: previousState,
operation: operation,
nextState: nextState)
}
}
//===----------------------------------------------------------------------===//
// MinimalIndex
//===----------------------------------------------------------------------===//
/// Asserts that the two indices are allowed to participate in a binary
/// operation.
internal func _expectCompatibleIndices(
_ first: MinimalIndex,
_ second: MinimalIndex,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
if first._collectionState._id == second._collectionState._id {
// Fast path: the indices are derived from the same state.
return
}
// The indices are derived from different states. Check that they point
// to a self-consistent view of the collection.
if first._collectionState._id > second._collectionState._id {
return _expectCompatibleIndices(second, first)
}
func lastMutatedStateId(
of i: MinimalIndex,
in state: _CollectionState
) -> Int {
let offset = i.position
if offset == state._elementsLastMutatedStateIds.endIndex {
return state._id
}
return state._elementsLastMutatedStateIds[offset]
}
let newestCollectionState = second._collectionState
let expectedFirstIndexLastMutatedStateId =
lastMutatedStateId(of: first, in: newestCollectionState)
expectEqual(
expectedFirstIndexLastMutatedStateId,
first._collectionState._id,
"Indices are not compatible:\n" +
"first: \(first)\n" +
"second: \(second)\n" +
"first element last mutated in state id: \(first._collectionState._id)\n" +
"expected state id: \(expectedFirstIndexLastMutatedStateId)\n" +
"newest collection state: \(newestCollectionState)",
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
// To make writing assertions easier, perform a trap.
if expectedFirstIndexLastMutatedStateId != first._collectionState._id {
fatalError("Indices are not compatible")
}
}
public struct MinimalIndex : Comparable {
public init(
collectionState: _CollectionState,
position: Int,
startIndex: Int,
endIndex: Int
) {
expectTrapping(
position,
in: startIndex...endIndex)
self = MinimalIndex(
_collectionState: collectionState,
uncheckedPosition: position)
}
internal init(
_collectionState: _CollectionState,
uncheckedPosition: Int
) {
self._collectionState = _collectionState
self.position = uncheckedPosition
}
public let _collectionState: _CollectionState
public let position: Int
public static var trapOnRangeCheckFailure = ResettableValue(true)
}
public func == (lhs: MinimalIndex, rhs: MinimalIndex) -> Bool {
_expectCompatibleIndices(lhs, rhs)
return lhs.position == rhs.position
}
public func < (lhs: MinimalIndex, rhs: MinimalIndex) -> Bool {
_expectCompatibleIndices(lhs, rhs)
return lhs.position < rhs.position
}
//===----------------------------------------------------------------------===//
// MinimalStrideableIndex
//===----------------------------------------------------------------------===//
/// Asserts that the two indices are allowed to participate in a binary
/// operation.
internal func _expectCompatibleIndices(
_ first: MinimalStrideableIndex,
_ second: MinimalStrideableIndex,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
if first._collectionState._id == second._collectionState._id {
// Fast path: the indices are derived from the same state.
return
}
// The indices are derived from different states. Check that they point
// to a self-consistent view of the collection.
if first._collectionState._id > second._collectionState._id {
return _expectCompatibleIndices(second, first)
}
func lastMutatedStateId(
of i: MinimalStrideableIndex,
in state: _CollectionState
) -> Int {
let offset = i.position
if offset == state._elementsLastMutatedStateIds.endIndex {
return state._id
}
return state._elementsLastMutatedStateIds[offset]
}
let newestCollectionState = second._collectionState
let expectedFirstIndexLastMutatedStateId =
lastMutatedStateId(of: first, in: newestCollectionState)
expectEqual(
expectedFirstIndexLastMutatedStateId,
first._collectionState._id,
"Indices are not compatible:\n" +
"first: \(first)\n" +
"second: \(second)\n" +
"first element last mutated in state id: \(first._collectionState._id)\n" +
"expected state id: \(expectedFirstIndexLastMutatedStateId)\n" +
"newest collection state: \(newestCollectionState)",
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
// To make writing assertions easier, perform a trap.
if expectedFirstIndexLastMutatedStateId != first._collectionState._id {
fatalError("Indices are not compatible")
}
}
public struct MinimalStrideableIndex : Comparable {
public init(
collectionState: _CollectionState,
position: Int,
startIndex: Int,
endIndex: Int
) {
expectTrapping(
position,
in: startIndex...endIndex)
self = MinimalStrideableIndex(
_collectionState: collectionState,
uncheckedPosition: position)
}
internal init(
_collectionState: _CollectionState,
uncheckedPosition: Int
) {
self._collectionState = _collectionState
self.position = uncheckedPosition
}
public let _collectionState: _CollectionState
public let position: Int
public static var trapOnRangeCheckFailure = ResettableValue(true)
public var timesAdvancedCalled = ResettableValue(0)
public var timesDistanceCalled = ResettableValue(0)
}
public func == (lhs: MinimalStrideableIndex, rhs: MinimalStrideableIndex) -> Bool {
_expectCompatibleIndices(lhs, rhs)
return lhs.position == rhs.position
}
public func < (lhs: MinimalStrideableIndex, rhs: MinimalStrideableIndex) -> Bool {
_expectCompatibleIndices(lhs, rhs)
return lhs.position < rhs.position
}
extension MinimalStrideableIndex : Strideable {
public typealias Stride = Int
public func distance(to other: MinimalStrideableIndex) -> Int {
timesDistanceCalled.value += 1
_expectCompatibleIndices(self, other)
return other.position - position
}
public func advanced(by n: Int) -> MinimalStrideableIndex {
timesAdvancedCalled.value += 1
return MinimalStrideableIndex(
_collectionState: _collectionState,
uncheckedPosition: position + n)
}
}
//===----------------------------------------------------------------------===//
// Minimal***[Mutable]?Collection
//===----------------------------------------------------------------------===//
/// A minimal implementation of `Collection` with extra checks.
public struct MinimalCollection<T> : Collection {
/// Creates a collection with given contents, but a unique modification
/// history. No other instance has the same modification history.
public init<S : Sequence>(
elements: S,
underestimatedCount: UnderestimatedCountBehavior = .value(0)
) where S.Element == T {
self._elements = Array(elements)
self._collectionState = _CollectionState(
newRootStateForElementCount: self._elements.count)
switch underestimatedCount {
case .precise:
self.underestimatedCount = _elements.count
case .half:
self.underestimatedCount = _elements.count / 2
case .overestimate:
self.underestimatedCount = _elements.count * 3 + 5
case .value(let count):
self.underestimatedCount = count
}
}
public let timesMakeIteratorCalled = ResettableValue(0)
public func makeIterator() -> MinimalIterator<T> {
timesMakeIteratorCalled.value += 1
return MinimalIterator(_elements)
}
public typealias Index = MinimalIndex
internal func _index(forPosition i: Int) -> MinimalIndex {
return MinimalIndex(
collectionState: _collectionState,
position: i,
startIndex: _elements.startIndex,
endIndex: _elements.endIndex)
}
internal func _uncheckedIndex(forPosition i: Int) -> MinimalIndex {
return MinimalIndex(
_collectionState: _collectionState,
uncheckedPosition: i)
}
public let timesStartIndexCalled = ResettableValue(0)
public var startIndex: MinimalIndex {
timesStartIndexCalled.value += 1
return _uncheckedIndex(forPosition: _elements.startIndex)
}
public let timesEndIndexCalled = ResettableValue(0)
public var endIndex: MinimalIndex {
timesEndIndexCalled.value += 1
return _uncheckedIndex(forPosition: _elements.endIndex)
}
public func _failEarlyRangeCheck(
_ index: MinimalIndex,
bounds: Range<MinimalIndex>
) {
_expectCompatibleIndices(
_uncheckedIndex(forPosition: index.position),
index)
_expectCompatibleIndices(
_uncheckedIndex(forPosition: bounds.lowerBound.position),
bounds.lowerBound)
_expectCompatibleIndices(
_uncheckedIndex(forPosition: bounds.upperBound.position),
bounds.upperBound)
expectTrapping(
index.position,
in: bounds.lowerBound.position..<bounds.upperBound.position)
}
public func _failEarlyRangeCheck(
_ range: Range<MinimalIndex>,
bounds: Range<MinimalIndex>
) {
_expectCompatibleIndices(
_uncheckedIndex(forPosition: range.lowerBound.position),
range.lowerBound)
_expectCompatibleIndices(
_uncheckedIndex(forPosition: range.upperBound.position),
range.upperBound)
_expectCompatibleIndices(
_uncheckedIndex(forPosition: bounds.lowerBound.position),
bounds.lowerBound)
_expectCompatibleIndices(
_uncheckedIndex(forPosition: bounds.upperBound.position),
bounds.upperBound)
expectTrapping(
range.lowerBound.position..<range.upperBound.position,
in: bounds.lowerBound.position..<bounds.upperBound.position)
}
public func index(after i: MinimalIndex) -> MinimalIndex {
_failEarlyRangeCheck(i, bounds: startIndex..<endIndex)
return _uncheckedIndex(forPosition: i.position + 1)
}
public func distance(from start: MinimalIndex, to end: MinimalIndex)
-> Int {
precondition(start <= end,
"Only BidirectionalCollections can have end come before start")
// FIXME: swift-3-indexing-model: perform a range check properly.
if start != endIndex {
_failEarlyRangeCheck(start, bounds: startIndex..<endIndex)
}
if end != endIndex {
_failEarlyRangeCheck(end, bounds: startIndex..<endIndex)
}
return end.position - start.position
}
public func index(_ i: Index, offsetBy n: Int) -> Index {
precondition(n >= 0,
"Only BidirectionalCollections can be advanced by a negative amount")
// FIXME: swift-3-indexing-model: perform a range check properly.
if i != endIndex {
_failEarlyRangeCheck(i, bounds: startIndex..<endIndex)
}
return _index(forPosition: i.position + n)
}
public subscript(i: MinimalIndex) -> T {
get {
_failEarlyRangeCheck(i, bounds: startIndex..<endIndex)
return _elements[i.position]
}
}
public subscript(bounds: Range<MinimalIndex>) -> Slice<MinimalCollection<T>> {
get {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
return Slice(base: self, bounds: bounds)
}
}
public var underestimatedCount: Int
internal var _elements: [T]
internal let _collectionState: _CollectionState
}
/// A minimal implementation of `Collection` with extra checks.
public struct MinimalRangeReplaceableCollection<T> : Collection, RangeReplaceableCollection {
/// Creates a collection with given contents, but a unique modification
/// history. No other instance has the same modification history.
public init<S : Sequence>(
elements: S,
underestimatedCount: UnderestimatedCountBehavior = .value(0)
) where S.Element == T {
self._elements = Array(elements)
self._collectionState = _CollectionState(
newRootStateForElementCount: self._elements.count)
switch underestimatedCount {
case .precise:
self.underestimatedCount = _elements.count
case .half:
self.underestimatedCount = _elements.count / 2
case .overestimate:
self.underestimatedCount = _elements.count * 3 + 5
case .value(let count):
self.underestimatedCount = count
}
}
public init() {
self.underestimatedCount = 0
self._elements = []
self._collectionState =
_CollectionState(name: "\(type(of: self))", elementCount: 0)
}
public init<S : Sequence>(_ elements: S) where S.Element == T {
self.underestimatedCount = 0
self._elements = Array(elements)
self._collectionState =
_CollectionState(newRootStateForElementCount: self._elements.count)
}
public let timesMakeIteratorCalled = ResettableValue(0)
public func makeIterator() -> MinimalIterator<T> {
timesMakeIteratorCalled.value += 1
return MinimalIterator(_elements)
}
public typealias Index = MinimalIndex
internal func _index(forPosition i: Int) -> MinimalIndex {
return MinimalIndex(
collectionState: _collectionState,
position: i,
startIndex: _elements.startIndex,
endIndex: _elements.endIndex)
}
internal func _uncheckedIndex(forPosition i: Int) -> MinimalIndex {
return MinimalIndex(
_collectionState: _collectionState,
uncheckedPosition: i)
}
public let timesStartIndexCalled = ResettableValue(0)
public var startIndex: MinimalIndex {
timesStartIndexCalled.value += 1
return _uncheckedIndex(forPosition: _elements.startIndex)
}
public let timesEndIndexCalled = ResettableValue(0)
public var endIndex: MinimalIndex {
timesEndIndexCalled.value += 1
return _uncheckedIndex(forPosition: _elements.endIndex)
}
public func _failEarlyRangeCheck(
_ index: MinimalIndex,
bounds: Range<MinimalIndex>
) {
_expectCompatibleIndices(
_uncheckedIndex(forPosition: index.position),
index)
_expectCompatibleIndices(
_uncheckedIndex(forPosition: bounds.lowerBound.position),
bounds.lowerBound)
_expectCompatibleIndices(
_uncheckedIndex(forPosition: bounds.upperBound.position),
bounds.upperBound)
expectTrapping(
index.position,
in: bounds.lowerBound.position..<bounds.upperBound.position)
}
public func _failEarlyRangeCheck(
_ range: Range<MinimalIndex>,
bounds: Range<MinimalIndex>
) {
_expectCompatibleIndices(
_uncheckedIndex(forPosition: range.lowerBound.position),
range.lowerBound)
_expectCompatibleIndices(
_uncheckedIndex(forPosition: range.upperBound.position),
range.upperBound)
_expectCompatibleIndices(
_uncheckedIndex(forPosition: bounds.lowerBound.position),
bounds.lowerBound)
_expectCompatibleIndices(
_uncheckedIndex(forPosition: bounds.upperBound.position),
bounds.upperBound)
expectTrapping(
range.lowerBound.position..<range.upperBound.position,
in: bounds.lowerBound.position..<bounds.upperBound.position)
}
public func index(after i: MinimalIndex) -> MinimalIndex {
_failEarlyRangeCheck(i, bounds: startIndex..<endIndex)
return _uncheckedIndex(forPosition: i.position + 1)
}
public func distance(from start: MinimalIndex, to end: MinimalIndex)
-> Int {
precondition(start <= end,
"Only BidirectionalCollections can have end come before start")
// FIXME: swift-3-indexing-model: perform a range check properly.
if start != endIndex {
_failEarlyRangeCheck(start, bounds: startIndex..<endIndex)
}
if end != endIndex {
_failEarlyRangeCheck(end, bounds: startIndex..<endIndex)
}
return end.position - start.position
}
public func index(_ i: Index, offsetBy n: Int) -> Index {
precondition(n >= 0,
"Only BidirectionalCollections can be advanced by a negative amount")
// FIXME: swift-3-indexing-model: perform a range check properly.
if i != endIndex {
_failEarlyRangeCheck(i, bounds: startIndex..<endIndex)
}
return _index(forPosition: i.position + n)
}
public subscript(i: MinimalIndex) -> T {
get {
_failEarlyRangeCheck(i, bounds: startIndex..<endIndex)
return _elements[i.position]
}
}
public subscript(bounds: Range<MinimalIndex>) -> Slice<MinimalRangeReplaceableCollection<T>> {
get {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
return Slice(base: self, bounds: bounds)
}
}
public mutating func reserveCapacity(_ n: Int) {
_willMutate(.reserveCapacity(capacity: n))
_elements.reserveCapacity(n)
reservedCapacity = Swift.max(reservedCapacity, n)
}
public mutating func append(_ x: T) {
_willMutate(.append)
_elements.append(x)
}
public mutating func append<S : Sequence>(contentsOf newElements: S)
where S.Element == T {
let oldCount = count
_elements.append(contentsOf: newElements)
let newCount = count
_willMutate(.appendContentsOf(count: newCount - oldCount))
}
public mutating func replaceSubrange<C>(
_ subRange: Range<MinimalIndex>,
with newElements: C
) where C : Collection, C.Element == T {
let oldCount = count
_elements.replaceSubrange(
subRange.lowerBound.position..<subRange.upperBound.position,
with: newElements)
let newCount = count
_willMutate(.replaceRange(
subRange: subRange.lowerBound.position..<subRange.upperBound.position,
replacementCount:
subRange.upperBound.position - subRange.lowerBound.position
+ newCount - oldCount))
}
public mutating func insert(_ newElement: T, at i: MinimalIndex) {
_willMutate(.insert(atIndex: i.position))
_elements.insert(newElement, at: i.position)
}
public mutating func insert<S : Collection>(
contentsOf newElements: S, at i: MinimalIndex
) where S.Element == T {
let oldCount = count
_elements.insert(contentsOf: newElements, at: i.position)
let newCount = count
if newCount - oldCount != 0 {
_willMutate(.insertContentsOf(
atIndex: i.position,
count: newCount - oldCount))
}
}
@discardableResult
public mutating func remove(at i: MinimalIndex) -> T {
_willMutate(.removeAtIndex(index: i.position))
return _elements.remove(at: i.position)
}
@discardableResult
public mutating func removeLast() -> T {
_willMutate(.removeLast)
return _elements.removeLast()
}
public mutating func removeSubrange(_ subRange: Range<MinimalIndex>) {
if !subRange.isEmpty {
_willMutate(.removeRange(
subRange: subRange.lowerBound.position..<subRange.upperBound.position))
}
_elements.removeSubrange(
subRange.lowerBound.position..<subRange.upperBound.position
)
}
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
_willMutate(.removeAll(keepCapacity: keepCapacity))
// Ignore the value of `keepCapacity`.
_elements.removeAll(keepingCapacity: false)
}