diff options
Diffstat (limited to 'WireGuard/Shared/Model')
-rw-r--r-- | WireGuard/Shared/Model/Data+KeyEncoding.swift | 38 |
1 files changed, 32 insertions, 6 deletions
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<R>(_ body: (UnsafePointer<UInt8>) -> 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<R>(_ body: (UnsafeMutablePointer<UInt8>) -> 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<R>(_ body: (UnsafeMutablePointer<Int8>) -> 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 + } + } +} |