FragmentedMsgParsingCache

This commit is contained in:
Karlatemp 2021-01-10 23:20:15 +08:00
parent 268dcc7039
commit 01c050d0b6
No known key found for this signature in database
GPG Key ID: 21FBDDF664FF06F8

View File

@ -1,5 +1,5 @@
/*
* Copyright 2019-2020 Mamoe Technologies and contributors.
* Copyright 2019-2021 Mamoe Technologies and contributors.
*
* 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
* Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
@ -10,6 +10,7 @@
package net.mamoe.mirai.internal.utils
import kotlinx.atomicfu.locks.withLock
import net.mamoe.mirai.internal.network.protocol.data.proto.MsgComm
import net.mamoe.mirai.internal.network.protocol.data.proto.MsgOnlinePush
import net.mamoe.mirai.utils.currentTimeMillis
import java.util.concurrent.locks.ReentrantLock
@ -17,16 +18,16 @@ import java.util.concurrent.locks.ReentrantLock
/**
* fragmented message
*/
internal class GroupPkgMsgParsingCache {
class PkgMsg(
internal abstract class FragmentedMsgParsingCache<T> {
class PkgMsg<T>(
val size: Int,
val divSeq: Int,
val data: MutableMap<Int, MsgOnlinePush.PbPushMsg>,
val data: MutableMap<Int, T>,
) {
val createTime = currentTimeMillis()
}
private val deque = ArrayList<PkgMsg>(16)
private val deque = ArrayList<PkgMsg<T>>(16)
private val accessLock = ReentrantLock()
private fun clearInvalid() {
deque.removeIf {
@ -34,8 +35,10 @@ internal class GroupPkgMsgParsingCache {
}
}
fun tryMerge(msg: MsgOnlinePush.PbPushMsg): List<MsgOnlinePush.PbPushMsg> {
val head = msg.msg.contentHead ?: return listOf(msg)
internal abstract val T.contentHead: MsgComm.ContentHead?
fun tryMerge(msg: T): List<T> {
val head = msg.contentHead ?: return listOf(msg)
val size = head.pkgNum
if (size < 2) return listOf(msg)
accessLock.withLock {
@ -44,7 +47,7 @@ internal class GroupPkgMsgParsingCache {
val index = head.pkgIndex
val pkgMsg = deque.find {
it.divSeq == seq
} ?: PkgMsg(size, seq, mutableMapOf()).also { deque.add(it) }
} ?: PkgMsg<T>(size, seq, mutableMapOf()).also { deque.add(it) }
pkgMsg.data[index] = msg
if (pkgMsg.data.size == pkgMsg.size) {
deque.removeIf { it.divSeq == seq }
@ -56,4 +59,12 @@ internal class GroupPkgMsgParsingCache {
return emptyList()
}
}
}
}
/**
* fragmented message
*/
internal class GroupPkgMsgParsingCache : FragmentedMsgParsingCache<MsgOnlinePush.PbPushMsg>() {
override val MsgOnlinePush.PbPushMsg.contentHead: MsgComm.ContentHead?
get() = this.msg.contentHead
}