Append from another Data, given an offset and size
I would do this as follows:
mutating func append(data: Data, offset: Int, size: Int) {
let start = data.startIndex + offset
let end = start + size
self.append(data[start..<end])
}
There’s no point monkeying around with unsafe pointers if you don’t have to (-:
Also, with your current code you should watch out for size being 0, in which case baseAddress might be nil.
Perform an operation on a portion of Data (e.g. SHA1 or compress)
Your current code is definitely not safe. It effectively transports buf outside of the withUnsafeBytes(_:) closure, which is not allowed.
My recommended solution would be as above, that is, use a range to work on a subdata.
Copy from another Data
My first thought was to reach for subscript notation again:
mutating func copy(data: Data, size: Int) {
let srcStart = data.startIndex
let srcEnd = srcStart + size
let dstStart = self.startIndex
let dstEnd = dstStart + size
self[dstStart..<dstEnd] = data[srcStart..<srcEnd]
}
but, depending on your exact needs, you might be better off calling replaceSubrange(_:with:).
Truncate to size
Setting data.count does this.
Move bytes to the front
You can do this with self.removeFirst(_:).
If there’s one thing that the Swift 5 changes to Data have revealed is that there’s lots of folks using unsafe pointers when they don’t need to be )-: Data has a pretty solid API, helped by the fact it’s a collection of bytes and thus has all of the standard collection constructs available to it.
Share and Enjoy
Quinn “The Eskimo!” @ DTS @ Apple