Skip to content

Commit 6819ce7

Browse files
committed
add precondition to index(before:) and index(after:)
1 parent f57b72a commit 6819ce7

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

Sources/Algorithms/Stride.swift

+4-1
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,8 @@ extension Stride: Collection {
6666
}
6767

6868
public func index(after i: Index) -> Index {
69-
base.index(i.base, offsetBy: stride, limitedBy: base.endIndex)
69+
precondition(i.base < base.endIndex, "Advancing past end index")
70+
return base.index(i.base, offsetBy: stride, limitedBy: base.endIndex)
7071
.map(Index.init) ?? endIndex
7172
}
7273

@@ -87,8 +88,10 @@ extension Stride: BidirectionalCollection
8788
where Base: RandomAccessCollection {
8889

8990
public func index(before i: Index) -> Index {
91+
precondition(i.base > base.startIndex, "Advancing past start index")
9092
if i == endIndex {
9193
let count = base.count
94+
precondition(count > 0, "Advancing index when count is zero")
9295
return Index(
9396
base.index(
9497
base.endIndex,

Tests/SwiftAlgorithmsTests/StrideTests.swift

+5
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,10 @@ final class StridingTests: XCTestCase {
4646
XCTAssertEqual(a[i], 4)
4747
a.formIndex(before: &i)
4848
XCTAssertEqual(a[i], 2)
49+
a.formIndex(before: &i)
50+
XCTAssertEqual(a[i], 0)
51+
// a.formIndex(before: &i) // Precondition failed: Advancing past start index
52+
// a.index(after: a.endIndex) // Precondition failed: Advancing past end index
4953
}
5054

5155
func testStrideCompositionEquivalence() {
@@ -60,5 +64,6 @@ final class StridingTests: XCTestCase {
6064
XCTAssertEqual((1...10).stride(by: 5).last, 6) // 1, 6
6165
XCTAssertEqual((1...100).stride(by: 50).last, 51) // 1, 51
6266
XCTAssertEqual((1...5).stride(by: 2).last, 5) // 1, 3, 5
67+
XCTAssertEqual([Int]().stride(by: 2).last, nil) // 1, 3, 5
6368
}
6469
}

0 commit comments

Comments
 (0)