Better handling of CIDR values.

This commit is contained in:
Jeroen Leenarts 2018-10-03 21:34:51 +02:00
parent f27b4483da
commit 94afded0d2
2 changed files with 40 additions and 11 deletions

View File

@ -122,26 +122,43 @@ struct CIDRAddress {
var addressType: AddressType
init?(stringRepresentation: String) throws {
guard let range = stringRepresentation.range(of: "/", options: .backwards, range: nil, locale: nil) else {
throw CIDRAddressValidationError.noIpAndSubnet(stringRepresentation)
}
let subnetString: String.SubSequence
if let range = stringRepresentation.range(of: "/", options: .backwards, range: nil, locale: nil) {
let ipString = stringRepresentation[..<range.lowerBound].replacingOccurrences(of: "[", with: "").replacingOccurrences(of: "]", with: "")
let subnetString = stringRepresentation[range.upperBound...]
guard let subnet = Int32(subnetString) else {
throw CIDRAddressValidationError.invalidSubnet(String(subnetString))
ipAddress = String(ipString)
subnetString = stringRepresentation[range.upperBound...]
} else {
let ipString = stringRepresentation
ipAddress = String(ipString)
subnetString = ""
}
ipAddress = String(ipString)
let addressType = validateIpAddress(ipToValidate: ipAddress)
guard addressType == .IPv4 || addressType == .IPv6 else {
throw CIDRAddressValidationError.invalidIP(ipAddress)
}
self.addressType = addressType
if let subnet = Int32(subnetString) {
switch addressType {
case .IPv6:
self.subnet = subnet > 128 ? 128 : subnet
case .IPv4:
self.subnet = subnet > 32 ? 32 : subnet
case .other:
self.subnet = subnet
}
} else {
switch addressType {
case .IPv4:
subnet = 32
case .IPv6:
subnet = 128
case .other:
throw CIDRAddressValidationError.invalidSubnet(String(subnetString))
}
}
}
var subnetString: String {
// We could calculate these.
@ -156,4 +173,8 @@ struct CIDRAddress {
return "\(first).\(second).\(third).\(fourth)"
}
var stringRepresentation: String {
return "\(ipAddress)/\(subnet)"
}
}

View File

@ -224,6 +224,14 @@ extension InterfaceTableViewCell: UITextFieldDelegate {
}
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField == addressesField {
if let addresses = model.addresses?.commaSeparatedToArray() {
textField.text = addresses.compactMap { try? CIDRAddress(stringRepresentation: $0 ) }.compactMap { $0?.stringRepresentation }.joined(separator: ", ")
}
}
}
}
protocol PeerTableViewCellDelegate: class {