Refine code

This commit is contained in:
Mygod
2018-10-04 16:45:44 +08:00
parent 89234b37a4
commit 722855caf7
2 changed files with 26 additions and 27 deletions

View File

@@ -23,6 +23,7 @@ data class IpNeighbour(val ip: InetAddress, val dev: String, val lladdr: String,
private fun checkLladdrNotLoopback(lladdr: String) = if (lladdr == "00:00:00:00:00:00") "" else lladdr
fun parse(line: String): IpNeighbour? {
return try {
val match = parser.matchEntire(line)!!
val ip = parseNumericAddress(match.groupValues[2])
val dev = match.groupValues[4]
@@ -41,14 +42,12 @@ data class IpNeighbour(val ip: InetAddress, val dev: String, val lladdr: String,
"NOARP" -> return null // skip
else -> throw IllegalArgumentException("Unknown state encountered: ${match.groupValues[10]}")
}
return IpNeighbour(ip, dev, lladdr, state)
}
fun parseNoThrow(line: String): IpNeighbour? = try {
parse(line)
IpNeighbour(ip, dev, lladdr, state)
} catch (e: Exception) {
Timber.w(IllegalArgumentException("Unable to parse line: $line", e))
null
}
}
private val spaces = " +".toPattern()
private val mac = "^([0-9a-f]{2}:){5}[0-9a-f]{2}$".toPattern()

View File

@@ -38,7 +38,7 @@ class IpNeighbourMonitor private constructor() : IpMonitor() {
override fun processLine(line: String) {
synchronized(neighbours) {
val neighbour = IpNeighbour.parseNoThrow(line) ?: return
val neighbour = IpNeighbour.parse(line) ?: return
val changed = if (neighbour.state == IpNeighbour.State.DELETING)
neighbours.remove(neighbour.ip) != null
else neighbours.put(neighbour.ip, neighbour) != neighbour
@@ -50,7 +50,7 @@ class IpNeighbourMonitor private constructor() : IpMonitor() {
synchronized(neighbours) {
neighbours.clear()
neighbours.putAll(lines
.map(IpNeighbour.Companion::parseNoThrow)
.map(IpNeighbour.Companion::parse)
.filterNotNull()
.filter { it.state != IpNeighbour.State.DELETING } // skip entries without lladdr
.associateBy { it.ip })