diff --git a/mirai-core-utils/src/commonMain/kotlin/TypeSafeMap.kt b/mirai-core-utils/src/commonMain/kotlin/TypeSafeMap.kt index ff519c116..863d2c028 100644 --- a/mirai-core-utils/src/commonMain/kotlin/TypeSafeMap.kt +++ b/mirai-core-utils/src/commonMain/kotlin/TypeSafeMap.kt @@ -15,6 +15,9 @@ import kotlinx.serialization.Serializable import java.util.concurrent.ConcurrentHashMap import kotlin.contracts.InvocationKind import kotlin.contracts.contract +import kotlin.properties.ReadOnlyProperty +import kotlin.properties.ReadWriteProperty +import kotlin.reflect.KProperty @Serializable @JvmInline @@ -37,11 +40,24 @@ public sealed interface TypeSafeMap { public fun toMapBoxed(): Map, Any> public fun toMap(): Map + public operator fun provideDelegate(thisRef: Any?, property: KProperty<*>): ReadOnlyProperty { + val typeKey = TypeKey(property.name) + return ReadOnlyProperty { _, _ -> get(typeKey) } + } + public companion object { public val EMPTY: TypeSafeMap = TypeSafeMapImpl(emptyMap()) } } +public fun TypeSafeMap.property(name: String): ReadOnlyProperty { + return property(TypeKey(name)) +} + +public fun TypeSafeMap.property(typeKey: TypeKey): ReadOnlyProperty { + return ReadOnlyProperty { _, _ -> get(typeKey) } +} + public operator fun TypeSafeMap.plus(other: TypeSafeMap): TypeSafeMap { return when { other.size == 0 -> this @@ -57,6 +73,24 @@ public sealed interface MutableTypeSafeMap : TypeSafeMap { public operator fun set(key: TypeKey, value: T) public fun remove(key: TypeKey): T? public fun setAll(other: TypeSafeMap) + + + public override operator fun provideDelegate( + thisRef: Any?, + property: KProperty<*> + ): ReadWriteProperty { + val typeKey = TypeKey(property.name) + return object : ReadWriteProperty { + override fun getValue(thisRef: Any?, property: KProperty<*>): T { + return get(typeKey) + } + + override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { + set(typeKey, value) + } + } + } + } private val NULL: Any = Symbol("NULL")!!