Skip to content

Commit f4829f9

Browse files
committed
Off-by-one error in precondition:
for index <= position, if bytes.count == 0 and index == position, then we don't want this condition to be true at all.
1 parent d76486d commit f4829f9

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

Sources/Foundation/DispatchData+DataProtocol.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ extension DispatchData : DataProtocol {
3434
}
3535

3636
public subscript(position: DispatchData.Index) -> UInt8 {
37-
precondition(index <= position && position <= index + bytes.count)
37+
precondition(index <= position && position < index + bytes.count)
3838
return bytes[position - index]
3939
}
4040

Tests/Foundation/TestNSData.swift

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4481,6 +4481,26 @@ extension TestNSData {
44814481
}
44824482
}
44834483

4484+
func test_dispatchDataRegionSubscriptBounds() {
4485+
if #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) {
4486+
let bytes: [UInt8] = [0xAA, 0xBB, 0xCC]
4487+
var data = DispatchData.empty
4488+
bytes.withUnsafeBytes { data.append($0) }
4489+
4490+
guard let region = data.regions.first else {
4491+
XCTFail("Expected a single region")
4492+
return
4493+
}
4494+
4495+
XCTAssertEqual(region.startIndex, 0)
4496+
XCTAssertEqual(region.endIndex, bytes.count)
4497+
4498+
for (offset, expected) in bytes.enumerated() {
4499+
XCTAssertEqual(region[region.startIndex + offset], expected)
4500+
}
4501+
}
4502+
}
4503+
44844504
func test_Data_increaseCount() {
44854505
guard #available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) else { return }
44864506
let initials: [Range<UInt8>] = [

0 commit comments

Comments
 (0)