From 4ba36051fd06a920aedd51c93a15703d4b152332 Mon Sep 17 00:00:00 2001 From: Frizlab Date: Sun, 28 Mar 2021 19:28:51 +0200 Subject: [PATCH 1/2] Make firstRange and lastRange methods of the DataProtocol mirror macOS foundation when data is empty --- Sources/Foundation/DataProtocol.swift | 6 ++++++ 1 file changed, 6 insertions(+) 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 { From 090eb4bc2a3e21afad7bfe79a03816e9039172b9 Mon Sep 17 00:00:00 2001 From: Frizlab Date: Mon, 29 Mar 2021 09:19:26 +0200 Subject: [PATCH 2/2] Add tests for first and last range w/ empty data searched --- Tests/Foundation/Tests/TestNSData.swift | 12 ++++++++++++ 1 file changed, 12 insertions(+) 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")