Convert ComponentKey.componentName and .smartToString to extension

This commit is contained in:
Him188 2021-07-28 11:04:32 +08:00
parent 2d5c434146
commit 24d52bbe90
3 changed files with 20 additions and 16 deletions

View File

@ -18,23 +18,24 @@ import kotlin.reflect.full.allSupertypes
* @param T is a type hint.
*/
internal interface ComponentKey<T : Any> {
/**
* Get name of `T`.
*
* - If [qualified] is `false`, example: `PacketCodec`.
* - If [qualified] is `true`, example: `net.mamoe.mirai.internal.network.components.PacketCodec`.
*/
fun componentName(qualified: Boolean = false): String {
val argument = getComponentTypeArgument()
argument?.render(qualified)?.let { return it }
return argument?.type?.classifier.renderClassifier(qualified)
}
fun smartToString(qualified: Boolean = false): String {
return "ComponentKey<${componentName(qualified)}>"
}
companion object {
/**
* Get name of `T`.
*
* - If [qualified] is `false`, example: `PacketCodec`.
* - If [qualified] is `true`, example: `net.mamoe.mirai.internal.network.components.PacketCodec`.
*/
fun <T : Any> ComponentKey<T>.componentName(qualified: Boolean = false): String {
val argument = getComponentTypeArgument()
argument?.render(qualified)?.let { return it }
return argument?.type?.classifier.renderClassifier(qualified)
}
fun <T : Any> ComponentKey<T>.smartToString(qualified: Boolean = false): String {
return "ComponentKey<${componentName(qualified)}>"
}
// reflection is slow, but it is initialized once only (if memory sufficient).
private fun KTypeProjection.render(
@ -84,4 +85,4 @@ internal interface ComponentKey<T : Any> {
private val COMPONENT_KEY_K_CLASS = ComponentKey::class
}
}
}

View File

@ -9,6 +9,7 @@
package net.mamoe.mirai.internal.network.component
import net.mamoe.mirai.internal.network.component.ComponentKey.Companion.componentName
import net.mamoe.mirai.utils.systemProp
import java.util.concurrent.ConcurrentHashMap
import kotlin.LazyThreadSafetyMode.NONE

View File

@ -9,6 +9,8 @@
package net.mamoe.mirai.internal.network.component
import net.mamoe.mirai.internal.network.component.ComponentKey.Companion.componentName
import net.mamoe.mirai.internal.network.component.ComponentKey.Companion.smartToString
import net.mamoe.mirai.internal.test.AbstractTest
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals