Merge pull request #204 from ktopley-apple/corelibs-dispatch-data-copy
Fixes incorrect behavior of DispatchData.copyBytes() when the start …
diff --git a/src/swift/Data.swift b/src/swift/Data.swift
index d51205c..30a20b8 100644
--- a/src/swift/Data.swift
+++ b/src/swift/Data.swift
@@ -135,11 +135,16 @@
private func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: CountableRange<Index>) {
var copiedCount = 0
+ if range.isEmpty { return }
+ let rangeSize = range.count
_ = CDispatch.dispatch_data_apply(__wrapped.__wrapped) { (data: dispatch_data_t, offset: Int, ptr: UnsafeRawPointer, size: Int) in
- let limit = Swift.min((range.endIndex - range.startIndex) - copiedCount, size)
- memcpy(pointer + copiedCount, ptr, limit)
- copiedCount += limit
- return copiedCount < (range.endIndex - range.startIndex)
+ if offset >= range.endIndex { return false } // This region is after endIndex
+ let copyOffset = range.startIndex > offset ? range.startIndex - offset : 0 // offset of first byte, in this region
+ if copyOffset >= size { return true } // This region is before startIndex
+ let count = Swift.min(rangeSize - copiedCount, size - copyOffset)
+ memcpy(pointer + copiedCount, ptr + copyOffset, count)
+ copiedCount += count
+ return copiedCount < rangeSize
}
}