Commit 99ca0dec authored by Him188's avatar Him188

Introduce cache for MessageChainBuilder

parent 0a6b39e6
...@@ -53,47 +53,66 @@ class MessageChainBuilder ...@@ -53,47 +53,66 @@ class MessageChainBuilder
) : MutableCollection<Message> by container, Appendable { ) : MutableCollection<Message> by container, Appendable {
constructor(initialSize: Int) : this(ArrayList<Message>(initialSize)) constructor(initialSize: Int) : this(ArrayList<Message>(initialSize))
override fun add(element: Message): Boolean {
flushCache()
return container.add(element)
}
override fun addAll(elements: Collection<Message>): Boolean {
flushCache()
return container.addAll(elements)
}
operator fun Message.unaryPlus() { operator fun Message.unaryPlus() {
flushCache()
add(this) add(this)
} }
operator fun String.unaryPlus() { operator fun String.unaryPlus() {
add(this.toMessage()) add(this)
} }
operator fun plusAssign(plain: String) { operator fun plusAssign(plain: String) {
this.add(plain.toMessage()) withCache { append(plain) }
} }
operator fun plusAssign(message: Message) { operator fun plusAssign(message: Message) {
flushCache()
this.add(message) this.add(message)
} }
fun add(plain: String) { fun add(plain: String) {
this.add(plain.toMessage()) withCache { append(plain) }
} }
operator fun plusAssign(charSequence: CharSequence) { var cache: StringBuilder? = null
this.add(PlainText(charSequence)) private fun flushCache() {
cache?.let {
container.add(it.toString().toMessage())
} }
cache = null
override fun append(value: Char): Appendable = apply {
this.add(PlainText(value.toString()))
} }
override fun append(value: CharSequence?): Appendable = apply { private inline fun withCache(block: StringBuilder.() -> Unit): MessageChainBuilder {
when { if (cache == null) {
value == null -> this.add(PlainText.Null) cache = StringBuilder().apply(block)
value.isEmpty() -> this.add(PlainText.Empty) } else {
else -> this.add(PlainText(value)) cache!!.apply(block)
} }
return this
} }
override fun append(value: CharSequence?, startIndex: Int, endIndex: Int): Appendable = apply { operator fun plusAssign(charSequence: CharSequence) {
when { withCache { append(charSequence) }
value == null -> this.add(PlainText.Null)
value.isEmpty() -> this.add(PlainText.Empty)
else -> this.add(PlainText(value.substring(startIndex, endIndex)))
} }
override fun append(value: Char): Appendable = withCache { append(value) }
override fun append(value: CharSequence?): Appendable = withCache { append(value) }
override fun append(value: CharSequence?, startIndex: Int, endIndex: Int) =
withCache { append(value, startIndex, endIndex) }
fun asMessageChain(): MessageChain {
this.flushCache()
return (this as MutableCollection<Message>).asMessageChain()
} }
} }
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment