From 7a209a852ca64e7c00b76bb3626cf3f8080f9061 Mon Sep 17 00:00:00 2001 From: ThomasSession Date: Tue, 20 Aug 2024 09:00:58 +1000 Subject: [PATCH] Avoiding memory allocation since this is used in laarge sets --- .../thoughtcrime/securesms/util/IP2Country.kt | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/org/thoughtcrime/securesms/util/IP2Country.kt b/app/src/main/java/org/thoughtcrime/securesms/util/IP2Country.kt index 6ddeaf9282..4ffe870a05 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/util/IP2Country.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/util/IP2Country.kt @@ -17,9 +17,26 @@ class IP2Country private constructor(private val context: Context) { private val pathsBuiltEventReceiver: BroadcastReceiver val countryNamesCache = mutableMapOf() - private fun Ipv4Int(ip:String) = ip.takeWhile { it != '/' }.split('.').foldIndexed(0L) { i, acc, s -> - val asInt = s.toLong() - acc + (asInt shl (8 * (3-i))) + private fun Ipv4Int(ip: String): Long { + var result = 0L + var currentValue = 0L + var octetIndex = 0 + + for (char in ip) { + if (char == '.' || char == '/') { + result = (result shl 8) or currentValue + currentValue = 0 + octetIndex++ + if (char == '/') break + } else { + currentValue = currentValue * 10 + (char - '0') + } + } + + // Handle the last octet + result = (result shl 8) or currentValue + + return result } private val ipv4ToCountry by lazy {