diff options
author | Andrej Mihajlov <and@mullvad.net> | 2022-09-26 16:43:17 +0200 |
---|---|---|
committer | Andrej Mihajlov <and@mullvad.net> | 2022-09-26 16:43:17 +0200 |
commit | 977ec25e79e8e4e667d82dd79e3df63bde849103 (patch) | |
tree | 6b52c99c678985741f5330069b8e3b85dbcbde2b | |
parent | UI: When saving on-demand rules, deactivate if reqd and then save (diff) | |
download | wireguard-apple-am/codable-ipaddress-range.tar.xz wireguard-apple-am/codable-ipaddress-range.zip |
Kit: implement Codable for IPAddressRangeam/codable-ipaddress-range
Signed-off-by: Andrej Mihajlov <and@mullvad.net>
-rw-r--r-- | Sources/WireGuardKit/IPAddressRange.swift | 23 |
1 files changed, 23 insertions, 0 deletions
diff --git a/Sources/WireGuardKit/IPAddressRange.swift b/Sources/WireGuardKit/IPAddressRange.swift index 28a95d8..20e0da9 100644 --- a/Sources/WireGuardKit/IPAddressRange.swift +++ b/Sources/WireGuardKit/IPAddressRange.swift @@ -27,6 +27,29 @@ extension IPAddressRange: Hashable { } } +extension IPAddressRange: Codable { + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + try container.encode(self.stringRepresentation) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + let value = try container.decode(String.self) + + if let ipAddressRange = IPAddressRange(from: value) { + self = ipAddressRange + } else { + let context = DecodingError.Context( + codingPath: container.codingPath, + debugDescription: "Invalid IPAddressRange representation" + ) + throw DecodingError.dataCorrupted(context) + } + } +} + extension IPAddressRange { public var stringRepresentation: String { return "\(address)/\(networkPrefixLength)" |