Kaynağa Gözat

Fix zip and unzip

Him188 6 yıl önce
ebeveyn
işleme
21abfe4a64

+ 5 - 11
mirai-core/src/androidMain/kotlin/net/mamoe/mirai/utils/platformAndroid.kt

@@ -54,18 +54,12 @@ actual object MiraiPlatformUtils {
         data.checkOffsetAndLength(offset, length)
         data.checkOffsetAndLength(offset, length)
         if (length == 0) return ByteArray(0)
         if (length == 0) return ByteArray(0)
 
 
-        val inflater = Deflater()
-        inflater.reset()
-        ByteArrayOutputStream().use { output ->
-            inflater.setInput(data, offset, length)
-            ByteArrayPool.useInstance {
-                while (!inflater.finished()) {
-                    output.write(it, 0, inflater.deflate(it))
-                }
-            }
+        val deflater = Deflater()
+        deflater.setInput(data, offset, length)
+        deflater.finish()
 
 
-            inflater.end()
-            return output.toByteArray()
+        ByteArrayPool.useInstance {
+            return it.take(deflater.deflate(it)).toByteArray().also { deflater.end() }
         }
         }
     }
     }
 
 

+ 24 - 0
mirai-core/src/commonTest/kotlin/net.mamoe.mirai.utils/PlatformUtilsTest.kt

@@ -0,0 +1,24 @@
+/*
+ * Copyright 2020 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.
+ *
+ * https://github.com/mamoe/mirai/blob/master/LICENSE
+ */
+
+package net.mamoe.mirai.utils
+
+import kotlinx.io.core.toByteArray
+import net.mamoe.mirai.utils.io.encodeToString
+import kotlin.test.Test
+import kotlin.test.assertEquals
+
+internal class PlatformUtilsTest {
+
+    @OptIn(MiraiInternalAPI::class)
+    @Test
+    fun testZip() {
+        assertEquals("test", MiraiPlatformUtils.unzip(MiraiPlatformUtils.zip("test".toByteArray())).encodeToString())
+    }
+}

+ 5 - 11
mirai-core/src/jvmMain/kotlin/net/mamoe/mirai/utils/PlatformUtilsJvm.kt

@@ -55,18 +55,12 @@ actual object MiraiPlatformUtils {
         data.checkOffsetAndLength(offset, length)
         data.checkOffsetAndLength(offset, length)
         if (length == 0) return ByteArray(0)
         if (length == 0) return ByteArray(0)
 
 
-        val inflater = Deflater()
-        inflater.reset()
-        ByteArrayOutputStream().use { output ->
-            inflater.setInput(data, offset, length)
-            ByteArrayPool.useInstance {
-                while (!inflater.finished()) {
-                    output.write(it, 0, inflater.deflate(it))
-                }
-            }
+        val deflater = Deflater()
+        deflater.setInput(data, offset, length)
+        deflater.finish()
 
 
-            inflater.end()
-            return output.toByteArray()
+        ByteArrayPool.useInstance {
+            return it.take(deflater.deflate(it)).toByteArray().also { deflater.end() }
         }
         }
     }
     }