withUnsafeBytes Data API confusion

Data(result) here creates a copy, but it is possible to avoid this by creating a Data instead of an array (with the right count) and writing into its buffer directly:

import Foundation
import CommonCrypto

func digest(_ data: Data) -> Data {
    var md5 = Data(count: Int(CC_MD5_DIGEST_LENGTH))
    md5.withUnsafeMutableBytes { md5Buffer in
        data.withUnsafeBytes { buffer in
            let _ = CC_MD5(buffer.baseAddress!, CC_LONG(buffer.count), md5Buffer.bindMemory(to: UInt8.self).baseAddress)
        }
    }

    return md5
}
8 Likes