diff --git a/WireGuard/WireGuard/Model/IPAddressRange.swift b/WireGuard/WireGuard/Model/IPAddressRange.swift index 4498b58..ca4a7b9 100644 --- a/WireGuard/WireGuard/Model/IPAddressRange.swift +++ b/WireGuard/WireGuard/Model/IPAddressRange.swift @@ -15,6 +15,37 @@ struct IPAddressRange { var networkPrefixLength: UInt8 } +// MARK: Converting to and from String +// For use in the UI + +extension IPAddressRange { + init?(from string: String) { + guard let indexOfSlash = string.lastIndex(of: "/") else { return nil } + let indexOfNetworkPrefixLength = string.index(after: indexOfSlash) + guard (indexOfNetworkPrefixLength < string.endIndex) else { return nil } + let addressString = String(string[string.startIndex ..< indexOfSlash]) + if let addr = IPv4Address(addressString) { + address = addr + } else if let addr = IPv6Address(addressString) { + address = addr + } else { + return nil + } + let networkPrefixLengthSubstring = string[indexOfNetworkPrefixLength ..< string.endIndex] + if let npl = UInt8(networkPrefixLengthSubstring) { + networkPrefixLength = npl + } else { + return nil + } + } + func stringRepresentation() -> String { + return "\(address)/\(networkPrefixLength)" + } +} + +// MARK: Codable +// For serializing to disk + @available(OSX 10.14, iOS 12.0, *) extension IPAddressRange: Codable { public func encode(to encoder: Encoder) throws {