Model: IPAddressRange: Converting to and from String
Signed-off-by: Roopesh Chander <roop@roopc.net>
This commit is contained in:
parent
921b81e89b
commit
8ec73025f2
|
@ -15,6 +15,37 @@ struct IPAddressRange {
|
||||||
var networkPrefixLength: UInt8
|
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, *)
|
@available(OSX 10.14, iOS 12.0, *)
|
||||||
extension IPAddressRange: Codable {
|
extension IPAddressRange: Codable {
|
||||||
public func encode(to encoder: Encoder) throws {
|
public func encode(to encoder: Encoder) throws {
|
||||||
|
|
Loading…
Reference in New Issue