Optimise Snode and Snode.Version

This commit is contained in:
bemusementpark
2024-08-02 12:22:25 +09:30
parent a56e1d0b91
commit b93ec3be04
4 changed files with 73 additions and 83 deletions

View File

@@ -1,9 +1,21 @@
package org.session.libsignal.utilities
class Snode(val address: String, val port: Int, val publicKeySet: KeySet?, val version: String) {
import android.annotation.SuppressLint
fun Snode(string: String): Snode? {
val components = string.split("-")
val address = components[0]
val port = components.getOrNull(1)?.toIntOrNull() ?: return null
val ed25519Key = components.getOrNull(2) ?: return null
val x25519Key = components.getOrNull(3) ?: return null
val version = components.getOrNull(4)?.let(Snode::Version) ?: Snode.Version.ZERO
return Snode(address, port, Snode.KeySet(ed25519Key, x25519Key), version)
}
class Snode(val address: String, val port: Int, val publicKeySet: KeySet?, val version: Version) {
val ip: String get() = address.removePrefix("https://")
public enum class Method(val rawValue: String) {
enum class Method(val rawValue: String) {
GetSwarm("get_snodes_for_pubkey"),
Retrieve("retrieve"),
SendMessage("store"),
@@ -32,4 +44,42 @@ class Snode(val address: String, val port: Int, val publicKeySet: KeySet?, val v
}
override fun toString(): String { return "$address:$port" }
companion object {
private val CACHE = mutableMapOf<String, Version>()
@SuppressLint("NotConstructor")
fun Version(value: String) = CACHE.getOrElse(value) {
Snode.Version(value)
}
}
@JvmInline
value class Version(val value: ULong) {
companion object {
val ZERO = Version(0UL)
private const val MASK_BITS = 16
private const val MASK = 0xFFFFUL
private fun Sequence<ULong>.foldToVersionAsULong() = take(4).foldIndexed(0UL) { i, acc, it ->
it and MASK shl (3 - i) * MASK_BITS or acc
}
}
constructor(parts: List<Int>): this(
parts.asSequence()
.map { it.toByte().toULong() }
.foldToVersionAsULong()
)
constructor(value: Int): this(value.toULong())
internal constructor(value: String): this(
value.splitToSequence(".")
.map { it.toULongOrNull() ?: 0UL }
.foldToVersionAsULong()
)
operator fun compareTo(other: Version): Int = value.compareTo(other.value)
}
}