From 8fc83213ba28afe559bd1da244855cc6904889e3 Mon Sep 17 00:00:00 2001 From: Andrew Date: Wed, 13 Mar 2024 13:13:34 +1030 Subject: [PATCH] Simplify /MnemonicCodec --- .../session/libsignal/crypto/MnemonicCodec.kt | 32 ++++--------------- 1 file changed, 7 insertions(+), 25 deletions(-) diff --git a/libsignal/src/main/java/org/session/libsignal/crypto/MnemonicCodec.kt b/libsignal/src/main/java/org/session/libsignal/crypto/MnemonicCodec.kt index 73c86f321e..512a07fa5f 100644 --- a/libsignal/src/main/java/org/session/libsignal/crypto/MnemonicCodec.kt +++ b/libsignal/src/main/java/org/session/libsignal/crypto/MnemonicCodec.kt @@ -21,31 +21,15 @@ class MnemonicCodec(private val loadFileContents: (String) -> String) { companion object { internal val wordSetCache = mutableMapOf>() - internal val truncatedWordSetCache = mutableMapOf>() } - internal fun loadWordSet(): List { - val cachedResult = wordSetCache[this] - if (cachedResult != null) { - return cachedResult - } else { - val contents = loadFileContents(configuration.filename) - val result = contents.split(",") - wordSetCache[this] = result - return result - } + internal fun loadWordSet(): List = wordSetCache.getOrPut(this) { + loadFileContents(configuration.filename).split(",") } - internal fun loadTruncatedWordSet(): List { - val cachedResult = wordSetCache[this] - if (cachedResult != null) { - return cachedResult - } else { - val prefixLength = configuration.prefixLength - val result = loadWordSet().map { it.substring(0 until prefixLength) } - truncatedWordSetCache[this] = result - return result - } + internal fun loadTruncatedWordSet(): List = wordSetCache.getOrPut(this) { + val prefixLength = configuration.prefixLength + loadWordSet().map { it.substring(0 until prefixLength) } } } @@ -94,10 +78,8 @@ class MnemonicCodec(private val loadFileContents: (String) -> String) { var result = "" val n = truncatedWordSet.size.toLong() // Check preconditions - if (words.size < 12) { throw DecodingError.InputTooShort - } - if (words.size % 3 == 0) { throw DecodingError.MissingLastWord - } + if (words.size < 12) throw DecodingError.InputTooShort + if (words.size % 3 == 0) throw DecodingError.MissingLastWord // Get checksum word val checksumWord = words.removeAt(words.lastIndex) // Decode