Move MAC utils to MacAddressCompat

This commit is contained in:
Mygod
2020-05-30 02:06:41 -04:00
parent d328215764
commit e8fb62a0b3
15 changed files with 97 additions and 61 deletions

View File

@@ -3,6 +3,7 @@ package be.mygod.vpnhotspot.room
import androidx.lifecycle.LiveData
import androidx.lifecycle.map
import androidx.room.*
import be.mygod.vpnhotspot.net.MacAddressCompat
@Entity
data class ClientRecord(@PrimaryKey
@@ -14,7 +15,7 @@ data class ClientRecord(@PrimaryKey
abstract class Dao {
@Query("SELECT * FROM `ClientRecord` WHERE `mac` = :mac")
protected abstract fun lookupBlocking(mac: Long): ClientRecord?
fun lookupOrDefaultBlocking(mac: Long) = lookupBlocking(mac) ?: ClientRecord(mac)
fun lookupOrDefaultBlocking(mac: MacAddressCompat) = lookupBlocking(mac.addr) ?: ClientRecord(mac.addr)
@Query("SELECT * FROM `ClientRecord` WHERE `mac` = :mac")
protected abstract suspend fun lookup(mac: Long): ClientRecord?
@@ -22,14 +23,15 @@ data class ClientRecord(@PrimaryKey
@Query("SELECT * FROM `ClientRecord` WHERE `mac` = :mac")
protected abstract fun lookupSync(mac: Long): LiveData<ClientRecord?>
fun lookupOrDefaultSync(mac: Long) = lookupSync(mac).map { it ?: ClientRecord(mac) }
fun lookupOrDefaultSync(mac: MacAddressCompat) = lookupSync(mac.addr).map { it ?: ClientRecord(mac.addr) }
@Insert(onConflict = OnConflictStrategy.REPLACE)
protected abstract suspend fun updateInternal(value: ClientRecord): Long
suspend fun update(value: ClientRecord) = check(updateInternal(value) == value.mac)
@Transaction
open suspend fun upsert(mac: Long, operation: suspend ClientRecord.() -> Unit) = lookupOrDefault(mac).apply {
open suspend fun upsert(mac: MacAddressCompat, operation: suspend ClientRecord.() -> Unit) = lookupOrDefault(
mac.addr).apply {
operation()
update(this)
}

View File

@@ -5,8 +5,6 @@ import androidx.room.TypeConverter
import be.mygod.vpnhotspot.util.useParcel
import timber.log.Timber
import java.net.InetAddress
import java.nio.ByteBuffer
import java.nio.ByteOrder
object Converters {
@JvmStatic
@@ -37,18 +35,3 @@ object Converters {
@TypeConverter
fun unpersistInetAddress(data: ByteArray): InetAddress = InetAddress.getByAddress(data)
}
fun String.macToLong(): Long = ByteBuffer.allocate(8).run {
order(ByteOrder.LITTLE_ENDIAN)
mark()
put(split(':').map { Integer.parseInt(it, 16).toByte() }.toByteArray())
reset()
long
}
fun Iterable<Byte>.macToString() = joinToString(":") { "%02x".format(it) }
fun Long.macToString(): String = ByteBuffer.allocate(8).run {
order(ByteOrder.LITTLE_ENDIAN)
putLong(this@macToString)
array().take(6).macToString()
}