Reputation: 78
I am attempting to retrieve a subset of data from a Data object. When I attempt to get the data using subdata(in:) I get the mentioned error. I cannot figure out what I am doing wrong as all values appear correct. The code in question is:
let tempData = incomingDataBuffer.subdata(in: 0..<headerSizeInBytes)
using the lldb i've investigated and found that everything looks correct.
(lldb) po incomingDataBuffer.count
8
(lldb) po headerSizeInBytes
6
(lldb) po incomingDataBuffer
▿ 8 bytes
- count : 8
▿ pointer : 0x0000600000002a42
- pointerValue : 105553116277314
▿ bytes : 8 elements
- 0 : 17
- 1 : 6
- 2 : 29
- 3 : 49
- 4 : 2
- 5 : 0
- 6 : 1
- 7 : 6
(lldb) po incomingDataBuffer.subdata(in: 0..<headerSizeInBytes)
error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
The process has been returned to the state before expression evaluation.
This Doesn't make any sense to me. All the values appear correct. Nothing is nil. Why would I get this failure? Thanks for help. :)
Upvotes: 3
Views: 654
Reputation: 539915
The indices of a Data
value (or of collections in general) are not necessarily zero-based. A slice shares the indices with the originating data. Example:
let buffer = Data(bytes: [1, 2, 3, 4, 5, 6])[2..<4]
print(buffer.count) // 2
print(buffer.indices) // 2..<4
let tmpData = buffer.subdata(in: 0..<2)
// 💣 Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
Therefore you have to take the start index into account:
let tmpData = buffer[buffer.startIndex ..< buffer.startIndex + 2]
print(tmpData as NSData) // <0304>
or simply use the prefix:
let tmpData = buffer.prefix(2)
print(tmpData as NSData) // <0304>
Applied to your case:
let tempData = incomingDataBuffer.prefix(headerSizeInBytes)
Upvotes: 9