summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/IPAddressRange+Codable.swift
blob: 79f9e00a6595b9fb20c9f534f659697f269585de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//
//  IPAddressRange+Codable.swift
//  PacketTunnel
//
//  Created by pronebird on 05/01/2021.
//  Copyright © 2021 Mullvad VPN AB. All rights reserved.
//

import Foundation
import struct WireGuardKit.IPAddressRange

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)
        }
    }
}