From cb4fb495a31653209a0c406c84bb3eb4f6fc68b9 Mon Sep 17 00:00:00 2001
From: Him188 <Him188@mamoe.net>
Date: Tue, 9 Nov 2021 21:43:10 +0000
Subject: [PATCH] Rename ByteArray.encodeToString to .decodeToString

---
 mirai-core-utils/src/commonMain/kotlin/Bytes.kt |  4 ----
 mirai-core/src/commonMain/kotlin/MiraiImpl.kt   |  4 ++--
 .../kotlin/message/ReceiveMessageHandler.kt     | 17 ++++++++++-------
 .../src/commonMain/kotlin/message/imagesImpl.kt |  2 +-
 .../kotlin/message/incomingSourceImpl.kt        |  3 +--
 .../src/commonMain/kotlin/network/keys.kt       |  4 ++--
 .../notice/group/GroupMessageProcessor.kt       |  6 +++---
 .../notice/group/GroupNotificationProcessor.kt  |  2 +-
 .../kotlin/network/protocol/packet/Tlv.kt       |  2 +-
 .../protocol/packet/chat/voice/PttStore.kt      |  7 +++----
 .../network/protocol/packet/login/StatSvc.kt    |  6 +++---
 .../network/protocol/packet/login/WtLogin.kt    |  6 +++---
 .../src/commonTest/kotlin/PlatformUtilsTest.kt  |  9 ++++++---
 .../kotlin/utils/codegen/ValueCodegen.kt        |  5 ++---
 14 files changed, 38 insertions(+), 39 deletions(-)

diff --git a/mirai-core-utils/src/commonMain/kotlin/Bytes.kt b/mirai-core-utils/src/commonMain/kotlin/Bytes.kt
index a3706d044..50bf4d1f0 100644
--- a/mirai-core-utils/src/commonMain/kotlin/Bytes.kt
+++ b/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
 
diff --git a/mirai-core/src/commonMain/kotlin/MiraiImpl.kt b/mirai-core/src/commonMain/kotlin/MiraiImpl.kt
index 9ee4957e6..1fe021056 100644
--- a/mirai-core/src/commonMain/kotlin/MiraiImpl.kt
+++ b/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()
diff --git a/mirai-core/src/commonMain/kotlin/message/ReceiveMessageHandler.kt b/mirai-core/src/commonMain/kotlin/message/ReceiveMessageHandler.kt
index 7578b254c..488edc3bc 100644
--- a/mirai-core/src/commonMain/kotlin/message/ReceiveMessageHandler.kt
+++ b/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,
     )
diff --git a/mirai-core/src/commonMain/kotlin/message/imagesImpl.kt b/mirai-core/src/commonMain/kotlin/message/imagesImpl.kt
index 5b29e9665..e84beff33 100644
--- a/mirai-core/src/commonMain/kotlin/message/imagesImpl.kt
+++ b/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
 }
diff --git a/mirai-core/src/commonMain/kotlin/message/incomingSourceImpl.kt b/mirai-core/src/commonMain/kotlin/message/incomingSourceImpl.kt
index 0a63c06ec..01a3ceee1 100644
--- a/mirai-core/src/commonMain/kotlin/message/incomingSourceImpl.kt
+++ b/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())
         }
     }
 
diff --git a/mirai-core/src/commonMain/kotlin/network/keys.kt b/mirai-core/src/commonMain/kotlin/network/keys.kt
index 24acd7f7d..058056053 100644
--- a/mirai-core/src/commonMain/kotlin/network/keys.kt
+++ b/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
diff --git a/mirai-core/src/commonMain/kotlin/network/notice/group/GroupMessageProcessor.kt b/mirai-core/src/commonMain/kotlin/network/notice/group/GroupMessageProcessor.kt
index 32f929f34..c61b902c8 100644
--- a/mirai-core/src/commonMain/kotlin/network/notice/group/GroupMessageProcessor.kt
+++ b/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()
 }
\ No newline at end of file
diff --git a/mirai-core/src/commonMain/kotlin/network/notice/group/GroupNotificationProcessor.kt b/mirai-core/src/commonMain/kotlin/network/notice/group/GroupNotificationProcessor.kt
index eae2cb606..5a47c27b5 100644
--- a/mirai-core/src/commonMain/kotlin/network/notice/group/GroupNotificationProcessor.kt
+++ b/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()
diff --git a/mirai-core/src/commonMain/kotlin/network/protocol/packet/Tlv.kt b/mirai-core/src/commonMain/kotlin/network/protocol/packet/Tlv.kt
index 1093e43b3..77567e934 100644
--- a/mirai-core/src/commonMain/kotlin/network/protocol/packet/Tlv.kt
+++ b/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()
     }
diff --git a/mirai-core/src/commonMain/kotlin/network/protocol/packet/chat/voice/PttStore.kt b/mirai-core/src/commonMain/kotlin/network/protocol/packet/chat/voice/PttStore.kt
index 99bc0dd8f..fa8448214 100644
--- a/mirai-core/src/commonMain/kotlin/network/protocol/packet/chat/voice/PttStore.kt
+++ b/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,
diff --git a/mirai-core/src/commonMain/kotlin/network/protocol/packet/login/StatSvc.kt b/mirai-core/src/commonMain/kotlin/network/protocol/packet/login/StatSvc.kt
index 30e30eb6f..955aae08e 100644
--- a/mirai-core/src/commonMain/kotlin/network/protocol/packet/login/StatSvc.kt
+++ b/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;
diff --git a/mirai-core/src/commonMain/kotlin/network/protocol/packet/login/WtLogin.kt b/mirai-core/src/commonMain/kotlin/network/protocol/packet/login/WtLogin.kt
index dcb04f24c..c7c4aa861 100644
--- a/mirai-core/src/commonMain/kotlin/network/protocol/packet/login/WtLogin.kt
+++ b/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) }
diff --git a/mirai-core/src/commonTest/kotlin/PlatformUtilsTest.kt b/mirai-core/src/commonTest/kotlin/PlatformUtilsTest.kt
index 042bbb61e..30ba0065d 100644
--- a/mirai-core/src/commonTest/kotlin/PlatformUtilsTest.kt
+++ b/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())
     }
 }
\ No newline at end of file
diff --git a/mirai-core/src/commonTest/kotlin/utils/codegen/ValueCodegen.kt b/mirai-core/src/commonTest/kotlin/utils/codegen/ValueCodegen.kt
index f8365ae9a..6954d9120 100644
--- a/mirai-core/src/commonTest/kotlin/utils/codegen/ValueCodegen.kt
+++ b/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 {