diff --git a/Sources/Foundation/DataProtocol.swift b/Sources/Foundation/DataProtocol.swift index 3e9f88cf22..d0ed2c0a6a 100644 --- a/Sources/Foundation/DataProtocol.swift +++ b/Sources/Foundation/DataProtocol.swift @@ -137,6 +137,9 @@ extension DataProtocol { } public func firstRange(of data: D, in range: R) -> Range? where R.Bound == Index { + guard !data.isEmpty else { + return nil + } let r = range.relative(to: self) let rangeCount = distance(from: r.lowerBound, to: r.upperBound) if rangeCount < data.count { @@ -166,6 +169,9 @@ extension DataProtocol { } public func lastRange(of data: D, in range: R) -> Range? where R.Bound == Index { + guard !data.isEmpty else { + return nil + } let r = range.relative(to: self) let rangeCount = distance(from: r.lowerBound, to: r.upperBound) if rangeCount < data.count { diff --git a/Tests/Foundation/Tests/TestNSData.swift b/Tests/Foundation/Tests/TestNSData.swift index 5e77aee13f..ec36a00a5c 100644 --- a/Tests/Foundation/Tests/TestNSData.swift +++ b/Tests/Foundation/Tests/TestNSData.swift @@ -212,6 +212,8 @@ class TestNSData: LoopbackServerTest { ("testCopyBytes", testCopyBytes), ("testCustomDeallocator", testCustomDeallocator), ("testDataInSet", testDataInSet), + ("testFirstRangeEmptyData", testFirstRangeEmptyData), + ("testLastRangeEmptyData", testLastRangeEmptyData), ("testEquality", testEquality), ("testGenericAlgorithms", testGenericAlgorithms), ("testInitializationWithArray", testInitializationWithArray), @@ -1194,6 +1196,16 @@ extension TestNSData { XCTAssertEqual(s.count, 2, "Expected only two entries in the Set") } + func testFirstRangeEmptyData() { + let d = Data([1, 2, 3]) + XCTAssertNil(d.firstRange(of: Data())) + } + + func testLastRangeEmptyData() { + let d = Data([1, 2, 3]) + XCTAssertNil(d.lastRange(of: Data())) + } + func testReplaceSubrange() { var hello = dataFrom("Hello") let world = dataFrom("World")