Skip to content

Commit 84ba611

Browse files
committed
Add tests and validate Data and DispatchData as sequences
1 parent b1ef771 commit 84ba611

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

Darwin/Foundation-swiftoverlay-Tests/TestData.swift

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3807,6 +3807,34 @@ class TestData : TestDataSuper {
38073807
let range = slice.range(of: "a".data(using: .ascii)!)
38083808
expectEqual(range, Range<Data.Index>(4..<5))
38093809
}
3810+
3811+
func test_nsdataSequence() {
3812+
let bytes: [UInt8] = Array(0x00...0xFF)
3813+
let data = bytes.withUnsafeBytes { NSData(bytes: $0.baseAddress, length: $0.count) }
3814+
3815+
for byte in bytes {
3816+
expectEqual(data[Int(byte)], byte)
3817+
}
3818+
}
3819+
3820+
func test_dispatchSequence() {
3821+
let bytes1: [UInt8] = Array(0x00..<0xF0)
3822+
let bytes2: [UInt8] = Array(0xF0..<0xFF)
3823+
var data = DispatchData.empty
3824+
bytes1.withUnsafeBytes {
3825+
data.append($0)
3826+
}
3827+
bytes2.withUnsafeBytes {
3828+
data.append($0)
3829+
}
3830+
3831+
for byte in bytes1 {
3832+
expectEqual(data[Int(byte)], byte)
3833+
}
3834+
for byte in bytes2 {
3835+
expectEqual(data[Int(byte)], byte)
3836+
}
3837+
}
38103838
}
38113839

38123840
#if !FOUNDATION_XCTEST
@@ -4126,6 +4154,9 @@ DataTests.test("test_validateMutation_slice_customBacking_withUnsafeMutableBytes
41264154
DataTests.test("test_validateMutation_slice_customMutableBacking_withUnsafeMutableBytes_lengthLessThanLowerBound") { TestData().test_validateMutation_slice_customMutableBacking_withUnsafeMutableBytes_lengthLessThanLowerBound() }
41274155
DataTests.test("test_byte_access_of_discontiguousData") { TestData().test_byte_access_of_discontiguousData() }
41284156
DataTests.test("test_rangeOfSlice") { TestData().test_rangeOfSlice() }
4157+
DataTests.test("test_nsdataSequence") { TestData().test_nsdataSequence() }
4158+
DataTests.test("test_dispatchSequence") { TestData().test_dispatchSequence() }
4159+
41294160

41304161
// XCTest does not have a crash detection, whereas lit does
41314162
DataTests.test("bounding failure subdata") {

Darwin/Foundation-swiftoverlay/NSData+DataProtocol.swift

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,11 @@ extension NSData : DataProtocol {
4343
@nonobjc
4444
public subscript(position: Int) -> UInt8 {
4545
var byte = UInt8(0)
46+
var offset = position
4647
enumerateBytes { (ptr, range, stop) in
47-
if range.location <= position && position < range.upperBound {
48-
byte = ptr.load(fromByteOffset: range.location - position, as: UInt8.self)
48+
offset -= range.lowerBound
49+
if range.contains(position) {
50+
byte = ptr.load(fromByteOffset: offset, as: UInt8.self)
4951
stop.pointee = true
5052
}
5153
}

0 commit comments

Comments
 (0)