diff options
author | Andrej Mihajlov <and@mullvad.net> | 2022-05-05 12:01:21 +0200 |
---|---|---|
committer | Andrej Mihajlov <and@mullvad.net> | 2022-05-06 13:31:36 +0200 |
commit | 296ec5b63e62d580cf9b172f709e65f0ea0f53b5 (patch) | |
tree | d72eb5110cf325ead03cc8865dd844da2e438a73 | |
parent | Kit: rework keys implementation (diff) | |
download | wireguard-apple-am/codable-key.tar.xz wireguard-apple-am/codable-key.zip |
Kit: implement Codableam/codable-key
Signed-off-by: Andrej Mihajlov <and@mullvad.net>
-rw-r--r-- | Sources/WireGuardKit/PrivateKey.swift | 24 |
1 files changed, 23 insertions, 1 deletions
diff --git a/Sources/WireGuardKit/PrivateKey.swift b/Sources/WireGuardKit/PrivateKey.swift index aa63e85..19e3f02 100644 --- a/Sources/WireGuardKit/PrivateKey.swift +++ b/Sources/WireGuardKit/PrivateKey.swift @@ -8,7 +8,7 @@ import WireGuardKitC #endif /// Umbrella protocol for all kinds of keys. -public protocol WireGuardKey: RawRepresentable, Hashable where RawValue == Data {} +public protocol WireGuardKey: RawRepresentable, Hashable, Codable where RawValue == Data {} /// Class describing a private key used by WireGuard. public final class PrivateKey: WireGuardKey { @@ -125,6 +125,28 @@ extension WireGuardKey { } } + // MARK: - Codable + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + let data = try container.decode(Data.self) + + if let instance = Self.init(rawValue: data) { + self = instance + } else { + throw DecodingError.dataCorruptedError( + in: container, + debugDescription: "Corrupt key data." + ) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + try container.encode(rawValue) + } + // MARK: - Equatable public static func == (lhs: Self, rhs: Self) -> Bool { |