Skip to content

Commit 40d7da4

Browse files
authored
Merge pull request #32019 from NevinBR/patch-1
[SR-12881] DefaultIndices dynamic dispatch
2 parents e497089 + 4bb855b commit 40d7da4

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

stdlib/public/core/Indices.swift

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,23 @@ extension DefaultIndices: Collection {
8181
public var indices: Indices {
8282
return self
8383
}
84+
85+
@_alwaysEmitIntoClient
86+
public func index(_ i: Index, offsetBy distance: Int) -> Index {
87+
return _elements.index(i, offsetBy: distance)
88+
}
89+
90+
@_alwaysEmitIntoClient
91+
public func index(
92+
_ i: Index, offsetBy distance: Int, limitedBy limit: Index
93+
) -> Index? {
94+
return _elements.index(i, offsetBy: distance, limitedBy: limit)
95+
}
96+
97+
@_alwaysEmitIntoClient
98+
public func distance(from start: Index, to end: Index) -> Int {
99+
return _elements.distance(from: start, to: end)
100+
}
84101
}
85102

86103
extension DefaultIndices: BidirectionalCollection

test/stdlib/DefaultIndices.swift

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// RUN: %target-run-stdlib-swift
2+
// REQUIRES: executable_test
3+
4+
import StdlibUnittest
5+
6+
var suite = TestSuite("DefaultIndices")
7+
defer { runAllTests() }
8+
9+
extension Collection {
10+
func genericDistance(from start: Index, to end: Index) -> Int {
11+
return distance(from: start, to: end)
12+
}
13+
14+
func genericIndex(_ i: Index, offsetBy distance: Int) -> Index {
15+
return index(i, offsetBy: distance)
16+
}
17+
18+
func genericIndex(
19+
_ i: Index, offsetBy distance: Int, limitedBy limit: Index
20+
) -> Index? {
21+
return index(i, offsetBy: distance, limitedBy: limit)
22+
}
23+
}
24+
25+
suite.test("Bidirectional dispatch") {
26+
var r = (0...10).indices
27+
expectType(DefaultIndices<ClosedRange<Int>>.self, &r)
28+
29+
let d = r.distance(from: r.endIndex, to: r.startIndex)
30+
let d2 = r.genericDistance(from: r.endIndex, to: r.startIndex)
31+
expectEqual(d, d2)
32+
33+
let i = r.index(r.endIndex, offsetBy: -1)
34+
let i2 = r.genericIndex(r.endIndex, offsetBy: -1)
35+
expectEqual(i, i2)
36+
37+
let j = r.index(r.startIndex, offsetBy: -1, limitedBy: r.startIndex)
38+
let j2 = r.genericIndex(r.startIndex, offsetBy: -1, limitedBy: r.startIndex)
39+
expectEqual(j, j2)
40+
}

0 commit comments

Comments
 (0)