Truncate 1 or more bytes with GZip round-trip

I do not understand. I have used the same approach for many years and have never experienced this.

For some reason that I have not collected until today, a round trip of GZip results in truncation of 1 or more bytes or data corruption.

I wrote a simple test to verify that something else is not affecting it.

It always fails with a "length mismatch".

Can someone match me that I'm not crazy? :)

thanks

leppie

TEST

using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;

class Program
{
  const int BUFFER_SIZE = 8192;

  static void Main(string[] args)
  {
    var filename = args[0];
    var filedata = File.ReadAllBytes(filename);
    var cmp = Compress(filedata);
    var dec = Decompress(cmp);

    Assert(filedata, dec);

    Console.ReadLine();
  }

  static void Assert(byte[] orig, byte[] data)
  {
    if (orig.Length != data.Length)
    {
      Debug.Fail("length mismatch");
    }
    for (int i = 0; i < orig.Length; i++)
    {
      Debug.Assert(orig[i] == data[i], "data mismatch");
    }
  }

  static byte[] Compress(byte[] data)
  {
    var input = new MemoryStream(data);
    var output = new MemoryStream();

    var s = new GZipStream(output, CompressionMode.Compress);
    byte[] buffer = new byte[BUFFER_SIZE];
    int read = 0;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
      s.Write(buffer, 0, read);
    }

    return output.ToArray();
  }

  static byte[] Decompress(byte[] data)
  {
    var input = new MemoryStream(data);
    var s = new GZipStream(input, CompressionMode.Decompress);

    var output = new MemoryStream();
    byte[] buffer = new byte[BUFFER_SIZE];
    int read = 0;
    while ((read = s.Read(buffer, 0, buffer.Length)) > 0)
    {
      output.Write(buffer, 0, read);
    }

    return output.ToArray();
  }
}

I also tried closing the threads correctly, with different buffer sizes, all the same result.

+3
source share
1 answer

OK, I found the problem.

.

:

s.Close();
return output.ToArray();
+3

Source: https://habr.com/ru/post/1708244/


All Articles