Skip to content

Commit 4a023ec

Browse files
committed
Fixes inccorrect behavior of DispatchData.copyBytes() when the start index is not 0 and adds a test for that method.
Please enter the commit message for your changes. Lines starting
1 parent c95febb commit 4a023ec

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

src/swift/Data.swift

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -135,11 +135,16 @@ public struct DispatchData : RandomAccessCollection {
135135

136136
private func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: CountableRange<Index>) {
137137
var copiedCount = 0
138+
if range.isEmpty { return }
139+
let rangeSize = range.count
138140
_ = CDispatch.dispatch_data_apply(__wrapped.__wrapped) { (data: dispatch_data_t, offset: Int, ptr: UnsafeRawPointer, size: Int) in
139-
let limit = Swift.min((range.endIndex - range.startIndex) - copiedCount, size)
140-
memcpy(pointer + copiedCount, ptr, limit)
141-
copiedCount += limit
142-
return copiedCount < (range.endIndex - range.startIndex)
141+
if offset >= range.endIndex { return false } // This region is after endIndex
142+
let copyOffset = range.startIndex > offset ? range.startIndex - offset : 0 // offset of first byte, in this region
143+
if copyOffset >= size { return true } // This region is before startIndex
144+
let count = Swift.min(rangeSize - copiedCount, size - copyOffset)
145+
memcpy(pointer + copiedCount, ptr + copyOffset, count)
146+
copiedCount += count
147+
return copiedCount < rangeSize
143148
}
144149
}
145150

0 commit comments

Comments
 (0)