Skip to content

Make firstRange and lastRange mirror macOS Foundation more #2992

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Sources/Foundation/DataProtocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,9 @@ extension DataProtocol {
}

public func firstRange<D: DataProtocol, R: RangeExpression>(of data: D, in range: R) -> Range<Index>? 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 {
Expand Down Expand Up @@ -166,6 +169,9 @@ extension DataProtocol {
}

public func lastRange<D: DataProtocol, R: RangeExpression>(of data: D, in range: R) -> Range<Index>? 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 {
Expand Down
12 changes: 12 additions & 0 deletions Tests/Foundation/Tests/TestNSData.swift
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,8 @@ class TestNSData: LoopbackServerTest {
("testCopyBytes", testCopyBytes),
("testCustomDeallocator", testCustomDeallocator),
("testDataInSet", testDataInSet),
("testFirstRangeEmptyData", testFirstRangeEmptyData),
("testLastRangeEmptyData", testLastRangeEmptyData),
("testEquality", testEquality),
("testGenericAlgorithms", testGenericAlgorithms),
("testInitializationWithArray", testInitializationWithArray),
Expand Down Expand Up @@ -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")
Expand Down