From 0db9990f2b69bde81a8c63774c6aeeaa5a3d83d0 Mon Sep 17 00:00:00 2001 From: Marcono1234 Date: Sun, 5 Nov 2023 13:20:21 +0100 Subject: [PATCH] Use reified type parameters for KeyIndexer --- .../lingua/internal/util/KeyIndexer.kt | 27 +++++++++---------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/src/main/kotlin/com/github/pemistahl/lingua/internal/util/KeyIndexer.kt b/src/main/kotlin/com/github/pemistahl/lingua/internal/util/KeyIndexer.kt index a548f074..7cdae816 100644 --- a/src/main/kotlin/com/github/pemistahl/lingua/internal/util/KeyIndexer.kt +++ b/src/main/kotlin/com/github/pemistahl/lingua/internal/util/KeyIndexer.kt @@ -24,13 +24,14 @@ internal interface KeyIndexer { const val NO_INDEX = -1 private fun Collection.asSet() = (this as? Set) ?: this.toSet() - fun > fromEnumConstants(constants: Collection) = fromEnumConstants(constants.asSet()) + inline fun > fromEnumConstants(constants: Collection) = + fromEnumConstants(constants.asSet()) /** Creates an indexer for a subset of all enum constants. */ - fun > fromEnumConstants(constants: Set): KeyIndexer { - val enumClass = constants.first().declaringJavaClass - val allConstants = enumClass.enumConstants - if (allConstants.size == constants.size) return forAllEnumConstants(enumClass) + inline fun > fromEnumConstants(constants: Set): KeyIndexer { + require(constants.isNotEmpty()) + val allConstants = E::class.java.enumConstants + if (allConstants.size == constants.size) return forAllEnumConstants() val ordinalToIndex = IntArray(allConstants.size) { NO_INDEX } @@ -40,26 +41,24 @@ internal interface KeyIndexer { index++ } - val indexToConstant = arrayOfNulls(index) + val indexToConstant = arrayOfNulls(index) constants.forEach { indexToConstant[ordinalToIndex[it.ordinal]] = it } + val indicesCount = index return object : KeyIndexer { - override fun indicesCount() = index + override fun indicesCount() = indicesCount override fun keyToIndex(key: E) = ordinalToIndex[key.ordinal] - @Suppress("UNCHECKED_CAST") - override fun indexToKey(index: Int) = indexToConstant[index] as E + // Using `!!` is fine here, assuming KeyIndexer is used correctly and only valid indices are used + override fun indexToKey(index: Int) = indexToConstant[index]!! } } - inline fun > forAllEnumConstants() = forAllEnumConstants(E::class.java) - - @JvmStatic - fun > forAllEnumConstants(enumClass: Class): KeyIndexer { - val enumConstants = enumClass.enumConstants + inline fun > forAllEnumConstants(): KeyIndexer { + val enumConstants = E::class.java.enumConstants return object : KeyIndexer { override fun indicesCount() = enumConstants.size