Reduce duplication

This commit is contained in:
Him188 2020-04-05 17:48:15 +08:00
parent e454502ef8
commit ed5a52859a

View File

@ -439,52 +439,51 @@ object NullMessageChain : MessageChain {
// region implementations // region implementations
@Suppress("DuplicatedCode") // we don't have pattern matching
@OptIn(MiraiExperimentalAPI::class) @OptIn(MiraiExperimentalAPI::class)
internal fun Sequence<SingleMessage>.constrainSingleMessages(): List<SingleMessage> { internal fun Sequence<SingleMessage>.constrainSingleMessages(): List<SingleMessage> {
val list = ArrayList<SingleMessage>(4) val iterator = this.iterator()
val singleList = ArrayList<Message.Key<*>?>(4) return constrainSingleMessagesImpl supplier@{
if (iterator.hasNext()) {
for (singleMessage in this) { iterator.next()
if (singleMessage is ConstrainSingle<*>) { } else null
val key = singleMessage.key
val index = singleList.indexOf(key)
if (index != -1) {
list[index] = singleMessage
continue
} else {
singleList.add(list.size, key)
}
}
list.add(singleMessage)
} }
return list
} }
@Suppress("DuplicatedCode") // we don't have pattern matching @MiraiExperimentalAPI
@OptIn(MiraiExperimentalAPI::class) internal inline fun constrainSingleMessagesImpl(iterator: () -> SingleMessage?): ArrayList<SingleMessage> {
internal fun Iterable<SingleMessage>.constrainSingleMessages(): List<SingleMessage> {
val list = ArrayList<SingleMessage>() val list = ArrayList<SingleMessage>()
var firstConstrainIndex = -1 var firstConstrainIndex = -1
for (singleMessage in this) { var next: SingleMessage?
if (singleMessage is ConstrainSingle<*>) { do {
if (firstConstrainIndex == -1) { next = iterator()
firstConstrainIndex = list.size // we are going to add one next?.let { singleMessage ->
} else { if (singleMessage is ConstrainSingle<*>) {
val key = singleMessage.key if (firstConstrainIndex == -1) {
val index = list.indexOfFirst(firstConstrainIndex) { it is ConstrainSingle<*> && it.key == key } firstConstrainIndex = list.size // we are going to add one
if (index != -1) { } else {
list[index] = singleMessage val key = singleMessage.key
continue val index = list.indexOfFirst(firstConstrainIndex) { it is ConstrainSingle<*> && it.key == key }
if (index != -1) {
list[index] = singleMessage
return@let
}
} }
} }
}
list.add(singleMessage) list.add(singleMessage)
} ?: return list
} while (true)
}
@OptIn(MiraiExperimentalAPI::class)
internal fun Iterable<SingleMessage>.constrainSingleMessages(): List<SingleMessage> {
val iterator = this.iterator()
return constrainSingleMessagesImpl supplier@{
if (iterator.hasNext()) {
iterator.next()
} else null
} }
return list
} }
internal inline fun <T> List<T>.indexOfFirst(offset: Int, predicate: (T) -> Boolean): Int { internal inline fun <T> List<T>.indexOfFirst(offset: Int, predicate: (T) -> Boolean): Int {