From cef3957875230874e5c45442b01ca295d373ac41 Mon Sep 17 00:00:00 2001 From: Roopesh Chander Date: Tue, 9 Apr 2019 11:11:28 +0530 Subject: Swift 5 migration: Handle changes in Data's pointer interface Signed-off-by: Roopesh Chander --- WireGuard/Shared/Model/Data+KeyEncoding.swift | 38 ++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 6 deletions(-) (limited to 'WireGuard/Shared/Model/Data+KeyEncoding.swift') diff --git a/WireGuard/Shared/Model/Data+KeyEncoding.swift b/WireGuard/Shared/Model/Data+KeyEncoding.swift index a1abdd7..5c7aee9 100644 --- a/WireGuard/Shared/Model/Data+KeyEncoding.swift +++ b/WireGuard/Shared/Model/Data+KeyEncoding.swift @@ -13,8 +13,8 @@ extension Data { return nil } var out = Data(repeating: 0, count: Int(WG_KEY_LEN_HEX)) - out.withUnsafeMutableBytes { outBytes in - self.withUnsafeBytes { inBytes in + out.withUnsafeMutableInt8Bytes { outBytes in + self.withUnsafeUInt8Bytes { inBytes in key_to_hex(outBytes, inBytes) } } @@ -25,7 +25,7 @@ extension Data { init?(hexKey hexString: String) { self.init(repeating: 0, count: Int(WG_KEY_LEN)) - if !self.withUnsafeMutableBytes { key_from_hex($0, hexString) } { + if !self.withUnsafeMutableUInt8Bytes { key_from_hex($0, hexString) } { return nil } } @@ -35,8 +35,8 @@ extension Data { return nil } var out = Data(repeating: 0, count: Int(WG_KEY_LEN_BASE64)) - out.withUnsafeMutableBytes { outBytes in - self.withUnsafeBytes { inBytes in + out.withUnsafeMutableInt8Bytes { outBytes in + self.withUnsafeUInt8Bytes { inBytes in key_to_base64(outBytes, inBytes) } } @@ -47,8 +47,34 @@ extension Data { init?(base64Key base64String: String) { self.init(repeating: 0, count: Int(WG_KEY_LEN)) - if !self.withUnsafeMutableBytes { key_from_base64($0, base64String) } { + if !self.withUnsafeMutableUInt8Bytes { key_from_base64($0, base64String) } { return nil } } } + +extension Data { + func withUnsafeUInt8Bytes(_ body: (UnsafePointer) -> R) -> R { + assert(!isEmpty) + return self.withUnsafeBytes { (ptr: UnsafeRawBufferPointer) -> R in + let bytes = ptr.bindMemory(to: UInt8.self) + return body(bytes.baseAddress!) // might crash if self.count == 0 + } + } + + mutating func withUnsafeMutableUInt8Bytes(_ body: (UnsafeMutablePointer) -> R) -> R { + assert(!isEmpty) + return self.withUnsafeMutableBytes { (ptr: UnsafeMutableRawBufferPointer) -> R in + let bytes = ptr.bindMemory(to: UInt8.self) + return body(bytes.baseAddress!) // might crash if self.count == 0 + } + } + + mutating func withUnsafeMutableInt8Bytes(_ body: (UnsafeMutablePointer) -> R) -> R { + assert(!isEmpty) + return self.withUnsafeMutableBytes { (ptr: UnsafeMutableRawBufferPointer) -> R in + let bytes = ptr.bindMemory(to: Int8.self) + return body(bytes.baseAddress!) // might crash if self.count == 0 + } + } +} -- cgit v1.2.3-59-g8ed1b