Meshtastic-Android/app/src/main/java/com/geeksville/mesh/model/DeviceVersion.kt

34 lines
1.1 KiB
Kotlin
Raw Normal View History

2021-03-02 15:12:57 +08:00
package com.geeksville.mesh.model
2020-12-10 09:23:02 +08:00
2022-09-04 22:52:40 -03:00
import com.geeksville.mesh.android.Logging
2020-12-10 09:23:02 +08:00
/**
* Provide structured access to parse and compare device version strings
*/
2021-03-29 20:33:06 +08:00
data class DeviceVersion(val asString: String) : Comparable<DeviceVersion>, Logging {
2020-12-10 09:23:02 +08:00
2021-03-29 20:33:06 +08:00
val asInt
get() = try {
verStringToInt(asString)
} catch (e: Exception) {
warn("Exception while parsing version '$asString', assuming version 0")
0
}
2020-12-10 09:23:02 +08:00
/**
* Convert a version string of the form 1.23.57 to a comparable integer of
* the form 12357.
*
* Or throw an exception if the string can not be parsed
*/
private fun verStringToInt(s: String): Int {
// Allow 1 to two digits per match
val match =
Regex("(\\d{1,2}).(\\d{1,2}).(\\d{1,2})").find(s)
?: throw Exception("Can't parse version $s")
val (major, minor, build) = match.destructured
return major.toInt() * 10000 + minor.toInt() * 100 + build.toInt()
2020-12-10 09:23:02 +08:00
}
override fun compareTo(other: DeviceVersion): Int = asInt - other.asInt
}