Sfoglia il codice sorgente

Rename ByteArray.encodeToString to .decodeToString

Him188 4 anni fa
parent
commit
cb4fb495a3

+ 0 - 4
mirai-core-utils/src/commonMain/kotlin/Bytes.kt

@@ -13,7 +13,6 @@
 
 package net.mamoe.mirai.utils
 
-import kotlinx.io.charsets.Charset
 import kotlinx.io.core.ByteReadPacket
 import kotlin.contracts.InvocationKind
 import kotlin.contracts.contract
@@ -175,9 +174,6 @@ public fun UByteArray.toUHexString(separator: String = " ", offset: Int = 0, len
     }
 }
 
-public inline fun ByteArray.encodeToString(offset: Int = 0, charset: Charset = Charsets.UTF_8): String =
-    String(this, charset = charset, offset = offset, length = this.size - offset)
-
 public expect fun ByteArray.encodeBase64(): String
 public expect fun String.decodeBase64(): ByteArray
 

+ 2 - 2
mirai-core/src/commonMain/kotlin/MiraiImpl.kt

@@ -770,7 +770,7 @@ internal open class MiraiImpl : IMirai, LowLevelApiAccessor {
     ): String {
         bot.asQQAndroidBot().network.run {
             val response = PttStore.GroupPttDown(bot.client, groupId, dstUin, md5).sendAndExpect()
-            return "http://${response.strDomain}${response.downPara.encodeToString()}"
+            return "http://${response.strDomain}${response.downPara.decodeToString()}"
         }
     }
 
@@ -980,7 +980,7 @@ internal open class MiraiImpl : IMirai, LowLevelApiAccessor {
 
                 val down = longResp.msgDownRsp.single()
                 check(down.result == 0) {
-                    "Message download failed, result=${down.result}, resId=${down.msgResid.encodeToString()}, msgContent=${down.msgContent.toUHexString()}"
+                    "Message download failed, result=${down.result}, resId=${down.msgResid.decodeToString()}, msgContent=${down.msgContent.toUHexString()}"
                 }
 
                 val content = down.msgContent.ungzip()

+ 10 - 7
mirai-core/src/commonMain/kotlin/message/ReceiveMessageHandler.kt

@@ -23,7 +23,10 @@ import net.mamoe.mirai.internal.network.protocol.data.proto.*
 import net.mamoe.mirai.internal.utils.io.serialization.loadAs
 import net.mamoe.mirai.internal.utils.io.serialization.readProtoBuf
 import net.mamoe.mirai.message.data.*
-import net.mamoe.mirai.utils.*
+import net.mamoe.mirai.utils.read
+import net.mamoe.mirai.utils.toLongUnsigned
+import net.mamoe.mirai.utils.toUHexString
+import net.mamoe.mirai.utils.unzip
 
 /**
  * 只在手动构造 [OfflineMessageSource] 时调用
@@ -342,8 +345,8 @@ internal object ReceiveMessageTransformer {
         val content = runWithBugReport("解析 lightApp",
             { "resId=" + lightApp.msgResid + "data=" + lightApp.data.toUHexString() }) {
             when (lightApp.data[0].toInt()) {
-                0 -> lightApp.data.encodeToString(offset = 1)
-                1 -> lightApp.data.unzip(1).encodeToString()
+                0 -> lightApp.data.decodeToString(startIndex = 1)
+                1 -> lightApp.data.unzip(1).decodeToString()
                 else -> error("unknown compression flag=${lightApp.data[0]}")
             }
         }
@@ -481,8 +484,8 @@ internal object ReceiveMessageTransformer {
     ) {
         val content = runWithBugReport("解析 richMsg", { richMsg.template1.toUHexString() }) {
             when (richMsg.template1[0].toInt()) {
-                0 -> richMsg.template1.encodeToString(offset = 1)
-                1 -> richMsg.template1.unzip(1).encodeToString()
+                0 -> richMsg.template1.decodeToString(startIndex = 1)
+                1 -> richMsg.template1.unzip(1).decodeToString()
                 else -> error("unknown compression flag=${richMsg.template1[0]}")
             }
         }
@@ -542,11 +545,11 @@ internal object ReceiveMessageTransformer {
     }
 
     fun ImMsgBody.Ptt.toAudio() = OnlineAudioImpl(
-        filename = fileName.encodeToString(),
+        filename = fileName.decodeToString(),
         fileMd5 = fileMd5,
         fileSize = fileSize.toLongUnsigned(),
         codec = AudioCodec.fromId(format),
-        url = downPara.encodeToString(),
+        url = downPara.decodeToString(),
         length = time.toLongUnsigned(),
         originalPtt = this,
     )

+ 1 - 1
mirai-core/src/commonMain/kotlin/message/imagesImpl.kt

@@ -70,7 +70,7 @@ private fun <T : ImgExtPbResvAttrCommon> ByteArray.pbImageResv_checkIsEmoji(seri
     val data = this
     return kotlin.runCatching {
         data.takeIf { it.isNotEmpty() }?.loadAs(serializer)?.let { ext ->
-            ext.imageBizType == 1 || ext.textSummary.encodeToString() == "[动画表情]"
+            ext.imageBizType == 1 || ext.textSummary.decodeToString() == "[动画表情]"
         }
     }.getOrNull() ?: false
 }

+ 1 - 2
mirai-core/src/commonMain/kotlin/message/incomingSourceImpl.kt

@@ -31,7 +31,6 @@ import net.mamoe.mirai.message.data.MessageSourceKind
 import net.mamoe.mirai.message.data.OnlineMessageSource
 import net.mamoe.mirai.utils.EMPTY_BYTE_ARRAY
 import net.mamoe.mirai.utils.encodeBase64
-import net.mamoe.mirai.utils.encodeToString
 import net.mamoe.mirai.utils.mapToIntArray
 import java.util.concurrent.atomic.AtomicBoolean
 
@@ -189,7 +188,7 @@ internal class OnlineMessageSourceFromGroupImpl(
             ?: error("cannot find member for OnlineMessageSourceFromGroupImpl. msg=${msg._miraiContentToString()}")
 
         anonymousInfo.run {
-            group.newAnonymous(anonGroupMsg!!.anonNick.encodeToString(), anonGroupMsg.anonId.encodeBase64())
+            group.newAnonymous(anonGroupMsg!!.anonNick.decodeToString(), anonGroupMsg.anonId.encodeBase64())
         }
     }
 

+ 2 - 2
mirai-core/src/commonMain/kotlin/network/keys.kt

@@ -149,7 +149,7 @@ internal data class WLoginSigInfo(
     }
 
     fun getPsKey(name: String): String {
-        return psKeyMap[name]?.data?.encodeToString() ?: error("Cannot find PsKey $name")
+        return psKeyMap[name]?.data?.decodeToString() ?: error("Cannot find PsKey $name")
     }
 }
 
@@ -187,7 +187,7 @@ internal open class KeyWithExpiry(
     }
 }
 
-internal val KeyWithExpiry.str get() = data.encodeToString()
+internal val KeyWithExpiry.str get() = data.decodeToString()
 internal val AbstractBot.sKey get() = client.wLoginSigInfo.sKey.str
 internal fun AbstractBot.psKey(name: String) = client.wLoginSigInfo.getPsKey(name)
 internal val AbstractBot.client get() = components[BotClientHolder].client

+ 3 - 3
mirai-core/src/commonMain/kotlin/network/notice/group/GroupMessageProcessor.kt

@@ -114,7 +114,7 @@ internal class GroupMessageProcessor(
         val nameCard: MemberNick
 
         if (anonymous != null) { // anonymous member
-            sender = group.newAnonymous(anonymous.anonNick.encodeToString(), anonymous.anonId.encodeBase64())
+            sender = group.newAnonymous(anonymous.anonNick.decodeToString(), anonymous.anonId.encodeBase64())
             nameCard = sender.generateMemberNickFromMember()
         } else { // normal member chat
             sender = group[msgHead.fromUin] ?: kotlin.run {
@@ -200,9 +200,9 @@ internal class GroupMessageProcessor(
         if (this[0] == 0x0A.toByte()) {
             val nameBuf = loadAs(Oidb0x8fc.CommCardNameBuf.serializer())
             if (nameBuf.richCardName.isNotEmpty()) {
-                return@runCatching nameBuf.richCardName.joinToString("") { it.text.encodeToString() }
+                return@runCatching nameBuf.richCardName.joinToString("") { it.text.decodeToString() }
             }
         }
         return@runCatching null
-    }.getOrNull() ?: encodeToString()
+    }.getOrNull() ?: decodeToString()
 }

+ 1 - 1
mirai-core/src/commonMain/kotlin/network/notice/group/GroupNotificationProcessor.kt

@@ -63,7 +63,7 @@ internal class GroupNotificationProcessor(
             when (info.field) {
                 1 -> {
                     // 群名
-                    val new = info.value.encodeToString()
+                    val new = info.value.decodeToString()
 
                     val group = bot.getGroup(modGroupProfile.groupCode) ?: continue
                     group.checkIsGroupImpl()

+ 1 - 1
mirai-core/src/commonMain/kotlin/network/protocol/packet/Tlv.kt

@@ -26,7 +26,7 @@ private val Char.isHumanReadable get() = this in '0'..'9' || this in 'a'..'z' ||
 
 internal fun TlvMap.smartToString(leadingLineBreak: Boolean = true, sorted: Boolean = true): String {
     fun ByteArray.valueToString(): String {
-        val str = this.encodeToString()
+        val str = this.decodeToString()
         return if (str.all { it.isHumanReadable }) str
         else this.toUHexString()
     }

+ 3 - 4
mirai-core/src/commonMain/kotlin/network/protocol/packet/chat/voice/PttStore.kt

@@ -25,7 +25,6 @@ import net.mamoe.mirai.internal.utils.toIpV4AddressString
 import net.mamoe.mirai.message.data.AudioCodec
 import net.mamoe.mirai.utils.EMPTY_BYTE_ARRAY
 import net.mamoe.mirai.utils.ExternalResource
-import net.mamoe.mirai.utils.encodeToString
 import net.mamoe.mirai.utils.toUHexString
 
 internal inline val ExternalResource.voiceCodec: Int get() = audioCodec.id
@@ -118,7 +117,7 @@ internal class PttStore {
             val resp =
                 resp0.msgTryupPttRsp.firstOrNull() ?: error("cannot find `msgTryupPttRsp` from `Cmd0x388.RspBody`")
             if (resp.failMsg != null) {
-                throw IllegalStateException(resp.failMsg.encodeToString())
+                throw IllegalStateException(resp.failMsg.decodeToString())
             }
             return Response.RequireUpload(
                 fileId = resp.fileid,
@@ -143,7 +142,7 @@ internal class PttStore {
                 val uint32DownPort: List<Int>
             ) : GroupPttDown.Response() {
                 override fun toString(): String {
-                    return "GroupPttDown(downPara=${downPara.encodeToString()},strDomain=$strDomain})"
+                    return "GroupPttDown(downPara=${downPara.decodeToString()},strDomain=$strDomain})"
                 }
             }
 
@@ -183,7 +182,7 @@ internal class PttStore {
             val resp =
                 resp0.msgGetpttUrlRsp.firstOrNull() ?: error("cannot find `msgGetpttUrlRsp` from `Cmd0x388.RspBody`")
             if (!resp.failMsg.contentEquals(EMPTY_BYTE_ARRAY)) {
-                throw IllegalStateException(resp.failMsg.encodeToString())
+                throw IllegalStateException(resp.failMsg.decodeToString())
             }
             return Response.DownLoadInfo(
                 downDomain = resp.downDomain,

+ 3 - 3
mirai-core/src/commonMain/kotlin/network/protocol/packet/login/StatSvc.kt

@@ -239,9 +239,9 @@ internal class StatSvc {
                                 iOSVersion = client.device.version.sdk.toLong(),
                                 cNetType = if (client.networkType == NetworkType.WIFI) 1 else 0,
                                 vecGuid = client.device.guid,
-                                strDevName = client.device.model.encodeToString(),
-                                strDevType = client.device.model.encodeToString(),
-                                strOSVer = client.device.version.release.encodeToString(),
+                                strDevName = client.device.model.decodeToString(),
+                                strDevType = client.device.model.decodeToString(),
+                                strOSVer = client.device.version.release.decodeToString(),
                                 // register 时还需要
                                 /*
                                 var44.uNewSSOIp = field_127445;

+ 3 - 3
mirai-core/src/commonMain/kotlin/network/protocol/packet/login/WtLogin.kt

@@ -205,7 +205,7 @@ internal class WtLogin {
         }
 
         private fun onUnsafeDeviceLogin(tlvMap: TlvMap, bot: QQAndroidBot): LoginPacketResponse.UnsafeLogin {
-            return LoginPacketResponse.UnsafeLogin(bot, tlvMap.getOrFail(0x204).encodeToString())
+            return LoginPacketResponse.UnsafeLogin(bot, tlvMap.getOrFail(0x204).decodeToString())
         }
 
         private fun onSolveLoginCaptcha(tlvMap: TlvMap, bot: QQAndroidBot): LoginPacketResponse.Captcha {
@@ -222,7 +222,7 @@ internal class WtLogin {
             // val ret = tlvMap[0x104]?.let { println(it.toUHexString()) }
             bot.client.t104 = tlvMap.getOrFail(0x104)
             tlvMap[0x192]?.let {
-                return LoginPacketResponse.Captcha.Slider(bot, it.encodeToString())
+                return LoginPacketResponse.Captcha.Slider(bot, it.decodeToString())
             }
             tlvMap[0x165]?.let {
                 // if (question[18].toInt() == 0x36) {
@@ -275,7 +275,7 @@ internal class WtLogin {
                     tlvMap119[0x1c]?.read {
                         val bytes = readBytes()
                         bot.network.logger.debug("onLoginSuccess, tlvMap119[0x1c]: " + bytes.toUHexString())
-                        bot.network.logger.debug("onLoginSuccess, tlvMap119[0x1c]: " + bytes.encodeToString())
+                        bot.network.logger.debug("onLoginSuccess, tlvMap119[0x1c]: " + bytes.decodeToString())
                     }
 
                     tlvMap119[0x130]?.let { client.analysisTlv130(it) }

+ 6 - 3
mirai-core/src/commonTest/kotlin/PlatformUtilsTest.kt

@@ -11,7 +11,10 @@ package net.mamoe.mirai.internal
 
 import kotlinx.io.core.toByteArray
 import net.mamoe.mirai.internal.test.AbstractTest
-import net.mamoe.mirai.utils.*
+import net.mamoe.mirai.utils.gzip
+import net.mamoe.mirai.utils.ungzip
+import net.mamoe.mirai.utils.unzip
+import net.mamoe.mirai.utils.zip
 import kotlin.test.Test
 import kotlin.test.assertEquals
 
@@ -19,11 +22,11 @@ internal class PlatformUtilsTest : AbstractTest() {
 
     @Test
     fun testZip() {
-        assertEquals("test", "test".toByteArray().zip().unzip().encodeToString())
+        assertEquals("test", "test".toByteArray().zip().unzip().decodeToString())
     }
 
     @Test
     fun testGZip() {
-        assertEquals("test", "test".toByteArray().gzip().ungzip().encodeToString())
+        assertEquals("test", "test".toByteArray().gzip().ungzip().decodeToString())
     }
 }

+ 2 - 3
mirai-core/src/commonTest/kotlin/utils/codegen/ValueCodegen.kt

@@ -9,7 +9,6 @@
 
 package net.mamoe.mirai.internal.utils.codegen
 
-import net.mamoe.mirai.utils.encodeToString
 import net.mamoe.mirai.utils.toUHexString
 
 class ValueCodegen(
@@ -80,11 +79,11 @@ class ValueCodegen(
                     context.append("net.mamoe.mirai.utils.EMPTY_BYTE_ARRAY") // let IDE to shorten references.
                     return
                 } else {
-                    if (array.encodeToString().all { Character.isUnicodeIdentifierPart(it) || it.isWhitespace() }) {
+                    if (array.decodeToString().all { Character.isUnicodeIdentifierPart(it) || it.isWhitespace() }) {
                         // prefers to show readable string
                         context.append(
                             "\"${
-                                array.encodeToString().escapeQuotation()
+                                array.decodeToString().escapeQuotation()
                             }\".toByteArray() /* ${array.toUHexString()} */"
                         )
                     } else {