How about this?
func md5DigestA(of data: Data) -> Data {
precondition(!data.isEmpty)
var result = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
data.withUnsafeBytes { buffer in
_ = CC_MD5(buffer.baseAddress!, CC_LONG(buffer.count), &result)
}
return Data(result)
}
If you want to handle the empty data case [1], remove the precondition check on line 2 and the force unwrap on line 5. This works because CC_MD5
will handle a NULL
parameter if the count is 0.
If you want to handle the empty data case and you’re dealing with a C function that doesn’t allow a NULL
pointer when the count is 0, things get more complex (-:
Share and Enjoy
Quinn “The Eskimo!” @ DTS @ Apple
[1] A question that deserves serious consideration, at least in a crypto context.