Skip to content

Commit 3923fb2

Browse files
committed
[String] String.Index.init(_:within:) bounds checks
Bounds check the given index for String.Index's generic initializer that makes sure a passed index is a valid one for the given StringProtocol.
1 parent 0ece62d commit 3923fb2

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

stdlib/public/core/StringIndexConversions.swift

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,15 @@
1212

1313
extension String.Index {
1414
private init?<S: StringProtocol>(
15-
_ sourcePosition: String.Index, _genericWithin target: S
15+
_ idx: String.Index, _genericWithin target: S
1616
) {
17-
guard target._wholeGuts.isOnGraphemeClusterBoundary(sourcePosition) else {
17+
guard target._wholeGuts.isOnGraphemeClusterBoundary(idx),
18+
idx >= target.startIndex && idx <= target.endIndex
19+
else {
1820
return nil
1921
}
20-
self = sourcePosition
22+
23+
self = idx
2124
}
2225

2326
/// Creates an index in the given string that corresponds exactly to the

test/stdlib/StringIndex.swift

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,11 @@ StringIndexTests.test("String.Index(_:within) / Range<String.Index>(_:in:)") {
215215
String.Index(idx, within: str), String.Index(idx, within: substr))
216216
}
217217

218+
expectNil(String.Index(str.startIndex, within: str.dropFirst()))
219+
expectNil(String.Index(str.endIndex, within: str.dropLast()))
220+
expectNotNil(String.Index(str.startIndex, within: str))
221+
expectNotNil(String.Index(str.endIndex, within: str))
222+
218223
let utf16Count = str.utf16.count
219224
let utf16Indices = Array(str.utf16.indices) + [str.utf16.endIndex]
220225
for location in 0..<utf16Count {

0 commit comments

Comments
 (0)