我有两个用C#和Scala编写的deflate函数,当使用相同的输入运行时,返回的字节数组在前导字节和尾随字节上有所不同(中间字节的差异由C#和Scala之间的无符号/有符号字节机制引起,这是预期的)。
Scala中的deflate函数:
import java.io.ByteArrayOutputStream
import java.util.zip.{Deflater, DeflaterOutputStream}
import zio._
object ZDeflater {
val deflater = ZManaged.makeEffectTotal(new Deflater(Deflater.DEFLATED, true))(_.end)
val buffer = ZManaged.fromAutoCloseable(ZIO.succeed(new ByteArrayOutputStream()))
val stream = for {
d <- deflater
b <- buffer
s <- ZManaged.fromAutoCloseable(ZIO.succeed(new DeflaterOutputStream(b, d, true)))
} yield (b, s)
def deflate(input: Array[Byte]): RIO[blocking.Blocking, Array[Byte]] = stream.use { case (buffer, stream) =>
for {
() <- blocking.effectBlocking(stream.write(input))
() <- blocking.effectBlocking(stream.flush())
result = buffer.toByteArray
} yield result
}
}
C#中的压缩函数Deflate:
private static byte[] Deflate(byte[] uncompressedBytes)
{
using (var output = new MemoryStream())
{
using (var zip = new DeflateStream(output, CompressionMode.Compress, true))
{
zip.Write(uncompressedBytes, 0, uncompressedBytes.Length);
}
return output.ToArray();
}
}
解压缩后的输出: Scala:
ZDeflater.deflate(data.getBytes(StandardCharsets.UTF_8))
124, -111, …, 126, 1, 0, 0, -1, -1
C#:
Deflate(Encoding.UTF8.GetBytes(data))
125, 145, …, 126, 1
有人知道是什么原因导致第一个字节和最后一个字节之间的差异吗?任何假设对我都非常有帮助。感谢!
附:我们遇到了一个问题,即C#的Deflate输出适用于特定的第三方,而Scala的输出不适用。因此,我正在尝试弄清楚如何使Scala的输出与C#的输出相同。