aboutsummaryrefslogtreecommitdiffstats
path: root/WireGuard/Shared/Model/ActivationType.swift
blob: ea5927d6f08a5aae654743854b96974ade42a571 (plain) (blame)
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// SPDX-License-Identifier: MIT
// Copyright © 2018 WireGuard LLC. All Rights Reserved.

enum ActivationType {
    case activateManually
    case useOnDemandOverWifiAndCellular
    case useOnDemandOverWifiOnly
    case useOnDemandOverCellularOnly
}

extension ActivationType: Codable {
    // We use separate coding keys in case we might have a enum with associated values in the future
    enum CodingKeys: CodingKey {
        case activateManually
        case useOnDemandOverWifiAndCellular
        case useOnDemandOverWifiOnly
        case useOnDemandOverCellularOnly
    }

    // Decoding error
    enum DecodingError: Error {
        case invalidInput
    }

    // Encoding
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        switch self {
        case .activateManually:
            try container.encode(true, forKey: CodingKeys.activateManually)
        case .useOnDemandOverWifiAndCellular:
            try container.encode(true, forKey: CodingKeys.useOnDemandOverWifiAndCellular)
        case .useOnDemandOverWifiOnly:
            try container.encode(true, forKey: CodingKeys.useOnDemandOverWifiOnly)
        case .useOnDemandOverCellularOnly:
            try container.encode(true, forKey: CodingKeys.useOnDemandOverCellularOnly)
        }
    }

    // Decoding
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        if let isValid = try? container.decode(Bool.self, forKey: CodingKeys.activateManually), isValid {
            self = .activateManually
            return
        }

        if let isValid = try? container.decode(Bool.self, forKey: CodingKeys.useOnDemandOverWifiAndCellular), isValid {
            self = .useOnDemandOverWifiAndCellular
            return
        }

        if let isValid = try? container.decode(Bool.self, forKey: CodingKeys.useOnDemandOverWifiOnly), isValid {
            self = .useOnDemandOverWifiOnly
            return
        }

        if let isValid = try? container.decode(Bool.self, forKey: CodingKeys.useOnDemandOverCellularOnly), isValid {
            self = .useOnDemandOverCellularOnly
            return
        }

        throw DecodingError.invalidInput
    }
}