]> git.ipfire.org Git - thirdparty/wireguard-apple.git/commitdiff
Kit: implement Codable am/codable-key
authorAndrej Mihajlov <and@mullvad.net>
Thu, 5 May 2022 10:01:21 +0000 (12:01 +0200)
committerAndrej Mihajlov <and@mullvad.net>
Fri, 6 May 2022 11:31:36 +0000 (13:31 +0200)
Signed-off-by: Andrej Mihajlov <and@mullvad.net>
Sources/WireGuardKit/PrivateKey.swift

index aa63e851aec54f2fc03892c8a113e745d4e168ff..19e3f023e231031324804f72f422d2ad5d7e4851 100644 (file)
@@ -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 {