Skip to content

Commit f8dc398

Browse files
authored
Merge pull request #2992 from Frizlab/main
Make firstRange and lastRange mirror macOS Foundation more
2 parents 3cf6ce3 + 090eb4b commit f8dc398

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

Sources/Foundation/DataProtocol.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,9 @@ extension DataProtocol {
137137
}
138138

139139
public func firstRange<D: DataProtocol, R: RangeExpression>(of data: D, in range: R) -> Range<Index>? where R.Bound == Index {
140+
guard !data.isEmpty else {
141+
return nil
142+
}
140143
let r = range.relative(to: self)
141144
let rangeCount = distance(from: r.lowerBound, to: r.upperBound)
142145
if rangeCount < data.count {
@@ -166,6 +169,9 @@ extension DataProtocol {
166169
}
167170

168171
public func lastRange<D: DataProtocol, R: RangeExpression>(of data: D, in range: R) -> Range<Index>? where R.Bound == Index {
172+
guard !data.isEmpty else {
173+
return nil
174+
}
169175
let r = range.relative(to: self)
170176
let rangeCount = distance(from: r.lowerBound, to: r.upperBound)
171177
if rangeCount < data.count {

Tests/Foundation/Tests/TestNSData.swift

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,8 @@ class TestNSData: LoopbackServerTest {
212212
("testCopyBytes", testCopyBytes),
213213
("testCustomDeallocator", testCustomDeallocator),
214214
("testDataInSet", testDataInSet),
215+
("testFirstRangeEmptyData", testFirstRangeEmptyData),
216+
("testLastRangeEmptyData", testLastRangeEmptyData),
215217
("testEquality", testEquality),
216218
("testGenericAlgorithms", testGenericAlgorithms),
217219
("testInitializationWithArray", testInitializationWithArray),
@@ -1228,6 +1230,16 @@ extension TestNSData {
12281230
XCTAssertEqual(s.count, 2, "Expected only two entries in the Set")
12291231
}
12301232

1233+
func testFirstRangeEmptyData() {
1234+
let d = Data([1, 2, 3])
1235+
XCTAssertNil(d.firstRange(of: Data()))
1236+
}
1237+
1238+
func testLastRangeEmptyData() {
1239+
let d = Data([1, 2, 3])
1240+
XCTAssertNil(d.lastRange(of: Data()))
1241+
}
1242+
12311243
func testReplaceSubrange() {
12321244
var hello = dataFrom("Hello")
12331245
let world = dataFrom("World")

0 commit comments

Comments
 (0)