Reduce duplication

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

View File

@ -439,36 +439,25 @@ 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?
do {
next = iterator()
next?.let { singleMessage ->
if (singleMessage is ConstrainSingle<*>) { if (singleMessage is ConstrainSingle<*>) {
if (firstConstrainIndex == -1) { if (firstConstrainIndex == -1) {
firstConstrainIndex = list.size // we are going to add one firstConstrainIndex = list.size // we are going to add one
@ -477,14 +466,24 @@ internal fun Iterable<SingleMessage>.constrainSingleMessages(): List<SingleMessa
val index = list.indexOfFirst(firstConstrainIndex) { it is ConstrainSingle<*> && it.key == key } val index = list.indexOfFirst(firstConstrainIndex) { it is ConstrainSingle<*> && it.key == key }
if (index != -1) { if (index != -1) {
list[index] = singleMessage list[index] = singleMessage
continue 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 {