wireguard-apple/WireGuard/Shared/Model/DNSServer.swift

56 lines
1.4 KiB
Swift
Raw Normal View History

2018-10-24 01:37:28 +00:00
// SPDX-License-Identifier: MIT
// Copyright © 2018 WireGuard LLC. All Rights Reserved.
2018-10-23 10:53:27 +00:00
import Foundation
import Network
@available(OSX 10.14, iOS 12.0, *)
struct DNSServer {
let address: IPAddress
}
// MARK: Converting to and from String
extension DNSServer {
init?(from addressString: String) {
if let addr = IPv4Address(addressString) {
address = addr
} else if let addr = IPv6Address(addressString) {
address = addr
} else {
return nil
}
}
func stringRepresentation() -> String {
return "\(address)"
}
}
// MARK: Codable
@available(OSX 10.14, iOS 12.0, *)
extension DNSServer: Codable {
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(address.rawValue)
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
var data = try container.decode(Data.self)
let ipAddressFromData: IPAddress? = {
switch data.count {
2018-10-23 10:53:27 +00:00
case 4: return IPv4Address(data)
case 16: return IPv6Address(data)
default: return nil
}
}()
guard let ipAddress = ipAddressFromData else {
throw DecodingError.invalidData
}
address = ipAddress
}
enum DecodingError: Error {
case invalidData
}
}