Simplify /MnemonicCodec

This commit is contained in:
Andrew 2024-03-13 13:13:34 +10:30
parent 0dde7297b8
commit 8fc83213ba

View File

@ -21,31 +21,15 @@ class MnemonicCodec(private val loadFileContents: (String) -> String) {
companion object { companion object {
internal val wordSetCache = mutableMapOf<Language, List<String>>() internal val wordSetCache = mutableMapOf<Language, List<String>>()
internal val truncatedWordSetCache = mutableMapOf<Language, List<String>>()
} }
internal fun loadWordSet(): List<String> { internal fun loadWordSet(): List<String> = wordSetCache.getOrPut(this) {
val cachedResult = wordSetCache[this] loadFileContents(configuration.filename).split(",")
if (cachedResult != null) {
return cachedResult
} else {
val contents = loadFileContents(configuration.filename)
val result = contents.split(",")
wordSetCache[this] = result
return result
}
} }
internal fun loadTruncatedWordSet(): List<String> { internal fun loadTruncatedWordSet(): List<String> = wordSetCache.getOrPut(this) {
val cachedResult = wordSetCache[this] val prefixLength = configuration.prefixLength
if (cachedResult != null) { loadWordSet().map { it.substring(0 until prefixLength) }
return cachedResult
} else {
val prefixLength = configuration.prefixLength
val result = loadWordSet().map { it.substring(0 until prefixLength) }
truncatedWordSetCache[this] = result
return result
}
} }
} }
@ -94,10 +78,8 @@ class MnemonicCodec(private val loadFileContents: (String) -> String) {
var result = "" var result = ""
val n = truncatedWordSet.size.toLong() val n = truncatedWordSet.size.toLong()
// Check preconditions // Check preconditions
if (words.size < 12) { throw DecodingError.InputTooShort if (words.size < 12) throw DecodingError.InputTooShort
} if (words.size % 3 == 0) throw DecodingError.MissingLastWord
if (words.size % 3 == 0) { throw DecodingError.MissingLastWord
}
// Get checksum word // Get checksum word
val checksumWord = words.removeAt(words.lastIndex) val checksumWord = words.removeAt(words.lastIndex)
// Decode // Decode