Issue #130
Code is in Swift 4
Constructing UnsafeMutablePointer
let byteCount = 32
let result = UnsafeMutablePointer<UInt8>.allocate(capacity: byteCount)
Data to UnsafePointer
extension Data {
func toPointer() -> UnsafePointer<UInt8>? {
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: count)
let stream = OutputStream(toBuffer: buffer, capacity: count)
stream.open()
withUnsafeBytes({ (p: UnsafePointer<UInt8>) -> Void in
stream.write(p, maxLength: count)
})
stream.close()
return UnsafePointer<UInt8>(buffer)
}
}
UnsafePointer to Data
extension UnsafePointer {
func toData() -> Data {
return Data(bytes: UnsafeRawPointer(self), count: 32)
}
}
Dealing with C API
This is how to do keccak hash using C API from https://github.com/ethereum/ethash/blob/master/src/libethash/sha3.c
class KeccakHash {
func hash(data: Data) throws -> Data {
guard let dataPointer = data.toPointer() else {
throw InteralError.invalid
}
let byteCount = 32
let result = UnsafeMutablePointer<UInt8>.allocate(capacity: byteCount)
sha3_256(result, byteCount, dataPointer, data.count)
return result.toData()
}
}