From eb482a4303e39ca00e6f87256e409d4748538c31 Mon Sep 17 00:00:00 2001 From: Him188 Date: Sat, 4 Apr 2020 14:50:53 +0800 Subject: [PATCH] Fix #187 --- .../net.mamoe.mirai/message/data/builder.kt | 39 +++++++++++++++---- 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/mirai-core/src/commonMain/kotlin/net.mamoe.mirai/message/data/builder.kt b/mirai-core/src/commonMain/kotlin/net.mamoe.mirai/message/data/builder.kt index 7739e4593..7e18318d9 100644 --- a/mirai-core/src/commonMain/kotlin/net.mamoe.mirai/message/data/builder.kt +++ b/mirai-core/src/commonMain/kotlin/net.mamoe.mirai/message/data/builder.kt @@ -9,6 +9,7 @@ @file:JvmMultifileClass @file:JvmName("MessageUtils") +@file:Suppress("unused") package net.mamoe.mirai.message.data @@ -44,7 +45,7 @@ inline fun buildMessageChain(initialSize: Int, block: MessageChainBuilder.() -> */ @JvmSynthetic inline fun buildMessageChain( - container: MutableCollection, + container: MutableCollection, block: MessageChainBuilder.() -> Unit ): MessageChain { return MessageChainBuilder(container).apply(block).asMessageChain() @@ -59,18 +60,34 @@ inline fun buildMessageChain( */ class MessageChainBuilder @JvmOverloads constructor( - private val container: MutableCollection = mutableListOf() -) : MutableCollection by container, Appendable { - constructor(initialSize: Int) : this(ArrayList(initialSize)) + private val container: MutableCollection = mutableListOf() +) : MutableCollection by container, Appendable { + constructor(initialSize: Int) : this(ArrayList(initialSize)) - override fun add(element: Message): Boolean { + override fun add(element: SingleMessage): Boolean { flushCache() return container.add(element) } - override fun addAll(elements: Collection): Boolean { + fun add(element: Message): Boolean { flushCache() - return container.addAll(elements) + @Suppress("UNCHECKED_CAST") + return when (element) { + is SingleMessage -> container.add(element) + is Iterable<*> -> this.addAll(element.flatten()) + else -> error("stub") + } + } + + override fun addAll(elements: Collection): Boolean { + flushCache() + return container.addAll(elements.flatten()) + } + + @JvmName("addAllFlatten") // erased generic type cause declaration clash + fun addAll(elements: Collection): Boolean { + flushCache() + return container.addAll(elements.flatten()) } operator fun Message.unaryPlus() { @@ -78,6 +95,7 @@ class MessageChainBuilder add(this) } + operator fun String.unaryPlus() { add(this) } @@ -91,6 +109,11 @@ class MessageChainBuilder this.add(message) } + operator fun plusAssign(message: SingleMessage) { // avoid resolution ambiguity + flushCache() + this.add(message) + } + fun add(plain: String) { withCache { append(plain) } } @@ -123,6 +146,6 @@ class MessageChainBuilder fun asMessageChain(): MessageChain { this.flushCache() - return (this as MutableCollection).asMessageChain() + return (this as MutableCollection).asMessageChain() } } \ No newline at end of file