Model: IP address can be specified without '/cidr'

Signed-off-by: Roopesh Chander <roop@roopc.net>
This commit is contained in:
Roopesh Chander 2018-10-30 13:45:16 +05:30
parent 535f0e1e4a
commit 7e4597e0d7
1 changed files with 15 additions and 15 deletions

View File

@ -15,29 +15,29 @@ struct IPAddressRange {
extension IPAddressRange { extension IPAddressRange {
init?(from string: String) { init?(from string: String) {
guard let indexOfSlash = string.lastIndex(of: "/") else { return nil } let endOfIPAddress = string.lastIndex(of: "/") ?? string.endIndex
let indexOfNetworkPrefixLength = string.index(after: indexOfSlash) let addressString = String(string[string.startIndex ..< endOfIPAddress])
guard (indexOfNetworkPrefixLength < string.endIndex) else { return nil } let address: IPAddress
let addressString = String(string[string.startIndex ..< indexOfSlash])
if let addr = IPv4Address(addressString) { if let addr = IPv4Address(addressString) {
address = addr address = addr
} else if let addr = IPv6Address(addressString) { } else if let addr = IPv6Address(addressString) {
address = addr address = addr
} else { } else {
return nil return nil
} }
let networkPrefixLengthSubstring = string[indexOfNetworkPrefixLength ..< string.endIndex] let maxNetworkPrefixLength: UInt8 = (address is IPv4Address) ? 32 : 128
if let npl = UInt8(networkPrefixLengthSubstring) { var networkPrefixLength: UInt8
if (address is IPv4Address) { if (endOfIPAddress < string.endIndex) { // "/" was located
networkPrefixLength = min(npl, 32) let indexOfNetworkPrefixLength = string.index(after: endOfIPAddress)
} else if (address is IPv6Address) { guard (indexOfNetworkPrefixLength < string.endIndex) else { return nil }
networkPrefixLength = min(npl, 128) let networkPrefixLengthSubstring = string[indexOfNetworkPrefixLength ..< string.endIndex]
} else { guard let npl = UInt8(networkPrefixLengthSubstring) else { return nil }
fatalError() networkPrefixLength = min(npl, maxNetworkPrefixLength)
}
} else { } else {
return nil networkPrefixLength = maxNetworkPrefixLength
} }
self.address = address
self.networkPrefixLength = networkPrefixLength
} }
func stringRepresentation() -> String { func stringRepresentation() -> String {
return "\(address)/\(networkPrefixLength)" return "\(address)/\(networkPrefixLength)"