UnsafePointer in Swift

Issue #130

Code is in Swift 4

Constructing UnsafeMutablePointer

1
2
let byteCount = 32
let result = UnsafeMutablePointer<UInt8>.allocate(capacity: byteCount)

Data to UnsafePointer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

1
2
3
4
5
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

1
2
3
4
5
6
7
8
9
10
11
12
13
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()
}
}

Read more

Comments