From f7affdd2ae2c738197aa0ce7dfeb56991ba92c63 Mon Sep 17 00:00:00 2001 From: "jiahua.liu" Date: Mon, 30 Mar 2020 23:00:47 +0800 Subject: [PATCH] add ConfigSection API --- .../mirai/console/plugins/ConfigSection.kt | 37 +++++++++++++++---- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/mirai-console/src/main/kotlin/net/mamoe/mirai/console/plugins/ConfigSection.kt b/mirai-console/src/main/kotlin/net/mamoe/mirai/console/plugins/ConfigSection.kt index 963f8eaed..74948a9d5 100644 --- a/mirai-console/src/main/kotlin/net/mamoe/mirai/console/plugins/ConfigSection.kt +++ b/mirai-console/src/main/kotlin/net/mamoe/mirai/console/plugins/ConfigSection.kt @@ -18,7 +18,6 @@ import com.moandjiezana.toml.TomlWriter import kotlinx.serialization.Serializable import kotlinx.serialization.UnstableDefault import net.mamoe.mirai.utils.MiraiInternalAPI -import net.mamoe.mirai.utils._miraiContentToString import net.mamoe.mirai.utils.io.encodeToString import org.yaml.snakeyaml.Yaml import java.io.File @@ -57,7 +56,13 @@ interface Config { operator fun get(key: String): Any? operator fun contains(key: String): Boolean fun exist(key: String): Boolean - fun setIfAbsent(key: String, value: Any) + /** + * 设置 key = value (如果value不存在则valueInitializer会被调用) + * 之后返回当前key对应的值 + * */ + fun setIfAbsent(key: String, value: T) + fun setIfAbsent(key: String, valueInitializer: Config.() -> T) + fun asMap(): Map fun save() @@ -256,6 +261,16 @@ internal fun Config.smartCastInternal(propertyName: String, _class: KC interface ConfigSection : Config, MutableMap { + companion object{ + fun create():ConfigSection{ + return ConfigSectionImpl() + } + + fun new():ConfigSection{ + return this.create() + } + } + override fun getConfigSection(key: String): ConfigSection { val content = get(key) ?: throw NoSuchElementException(key) if (content is ConfigSection) { @@ -336,9 +351,19 @@ interface ConfigSection : Config, MutableMap { return get(key) != null } - override fun setIfAbsent(key: String, value: Any) { - if (!exist(key)) set(key, value) + override fun setIfAbsent(key: String, value: T) { + putIfAbsent(key, value) } + + override fun setIfAbsent(key: String, valueInitializer: Config.() -> T) { + if(this.exist(key)){ + put(key,valueInitializer.invoke(this)) + } + } +} + +internal inline fun ConfigSection.smartGet(key:String):T{ + return this.smartCastInternal(key,T::class) } @Serializable @@ -368,10 +393,6 @@ open class ConfigSectionImpl : ConcurrentHashMap(), override fun save() { } - - override fun setIfAbsent(key: String, value: Any) { - this.putIfAbsent(key, value)//atomic - } } open class ConfigSectionDelegation(