EndInflate() public method

Ends an inflation session.
Call this after successively calling Inflate(). This will cause all buffers to be flushed. After calling this you cannot call Inflate() without a intervening call to one of the InitializeInflate() overloads.
public EndInflate ( ) : int
return int
Exemplo n.º 1
0
        public override void Close()
        {
            z.EndInflate();
            z = null;

            if (!_leaveOpen)
            {
                _stream.Dispose();
            }
            _stream = null;
        }
        public void Dispose()
        {
            z.EndInflate();
            z = null;

            if (!_leaveOpen)
            {
                _stream.Dispose();
            }
            _stream = null;
        }
Exemplo n.º 3
0
 private void end()
 {
     if (z != null)
     {
         if (_wantCompress)
         {
             _z.EndDeflate();
         }
         else
         {
             _z.EndInflate();
         }
         _z = null;
     }
 }
Exemplo n.º 4
0
 private void End()
 {
     if (ZlibCodec == null)
     {
         return;
     }
     if (_wantCompress)
     {
         _zlibCodec?.EndDeflate();
     }
     else
     {
         _zlibCodec?.EndInflate();
     }
     _zlibCodec = null;
 }
Exemplo n.º 5
0
 private void end()
 {
     if (_z == null)
     {
         return;
     }
     if (_wantCompress)
     {
         //_z.EndDeflate();
     }
     else
     {
         _z.EndInflate();
     }
     _z = null;
 }
Exemplo n.º 6
0
        private void End()
        {
            if (Z == null)
            {
                return;
            }

            if (WantCompress)
            {
                _z.EndDeflate();
            }
            else
            {
                _z.EndInflate();
            }

            _z = null !;
        }
Exemplo n.º 7
0
        public static byte[] ZLibDecompress(byte[] compressed, bool mode, int outputSize)
        {
            byte[] output = new Byte[outputSize];

            bool expectRfc1950Header = mode;

            using (MemoryStream ms = new MemoryStream())
            {
                ZlibCodec compressor = new ZlibCodec();
                compressor.InitializeInflate(expectRfc1950Header);

                compressor.InputBuffer = compressed;
                compressor.AvailableBytesIn = compressed.Length;
                compressor.NextIn = 0;
                compressor.OutputBuffer = output;

                foreach (var f in new FlushType[] { FlushType.None, FlushType.Finish })
                {
                    int bytesToWrite = 0;
                    do
                    {
                        compressor.AvailableBytesOut = outputSize;
                        compressor.NextOut = 0;
                        compressor.Inflate(f);

                        bytesToWrite = outputSize - compressor.AvailableBytesOut;
                        if (bytesToWrite > 0)
                            ms.Write(output, 0, bytesToWrite);
                    }
                    while ((f == FlushType.None && (compressor.AvailableBytesIn != 0 || compressor.AvailableBytesOut == 0)) ||
                           (f == FlushType.Finish && bytesToWrite != 0));
                }

                compressor.EndInflate();

                return (ms.ToArray());
            }
        }
        private string ZlibCodecDecompress(byte[] compressed)
        {
            int outputSize = 2048;
            byte[] output = new Byte[ outputSize ];
            
            // If you have a ZLIB stream, set this to true.  If you have
            // a bare DEFLATE stream, set this to false.
            bool expectRfc1950Header = false;
            
            using ( MemoryStream ms = new MemoryStream())
            {
                ZlibCodec compressor = new ZlibCodec();
                compressor.InitializeInflate(expectRfc1950Header);
            
                compressor.InputBuffer = compressed;
                compressor.AvailableBytesIn = compressed.Length;
                compressor.NextIn = 0;
                compressor.OutputBuffer = output;

                foreach (var f in new FlushType[] { FlushType.None, FlushType.Finish } )
                {
                    int bytesToWrite = 0;
                    do
                    {
                        compressor.AvailableBytesOut = outputSize;
                        compressor.NextOut = 0;
                        compressor.Inflate(f);

                        bytesToWrite = outputSize - compressor.AvailableBytesOut ;
                        if (bytesToWrite > 0)
                            ms.Write(output, 0, bytesToWrite);
                    }
                    while (( f == FlushType.None && (compressor.AvailableBytesIn != 0 || compressor.AvailableBytesOut == 0)) ||
                           ( f == FlushType.Finish && bytesToWrite != 0));
                }

                compressor.EndInflate();

                return UTF8Encoding.UTF8.GetString( ms.ToArray() );
            }
        }
Exemplo n.º 9
0
        private byte[] InflateBuffer(byte[] b, int length)
        {
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            ZlibCodec decompressor = new ZlibCodec();
            byte[] DecompressedBytes = new byte[length];
            TestContext.WriteLine("\n============================================");
            TestContext.WriteLine("Size of Buffer to Inflate: {0} bytes.", b.Length);
            MemoryStream ms = new MemoryStream(DecompressedBytes);

            int rc = decompressor.InitializeInflate();

            decompressor.InputBuffer = b;
            decompressor.NextIn = 0;
            decompressor.AvailableBytesIn = b.Length;

            decompressor.OutputBuffer = buffer;

            for (int pass = 0; pass < 2; pass++)
            {
                FlushType flush = (pass==0)
                    ? FlushType.None
                    : FlushType.Finish;
                do
                {
                    decompressor.NextOut = 0;
                    decompressor.AvailableBytesOut = buffer.Length;
                    rc = decompressor.Inflate(flush);

                    if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
                        throw new Exception("inflating: " + decompressor.Message);

                    if (buffer.Length - decompressor.AvailableBytesOut > 0)
                        ms.Write(decompressor.OutputBuffer, 0, buffer.Length - decompressor.AvailableBytesOut);
                }
                while (decompressor.AvailableBytesIn > 0 || decompressor.AvailableBytesOut == 0);
            }

            decompressor.EndInflate();
            TestContext.WriteLine("TBO({0}).", decompressor.TotalBytesOut);
            return DecompressedBytes;
        }
Exemplo n.º 10
0
        public void Zlib_Codec_TestLargeDeflateInflate()
        {
            int rc;
            int j;
            int bufferSize = 80000;
            byte[] compressedBytes = new byte[bufferSize];
            byte[] workBuffer = new byte[bufferSize / 4];

            ZlibCodec compressingStream = new ZlibCodec();

            rc = compressingStream.InitializeDeflate(CompressionLevel.Level1);
            Assert.AreEqual<int>(ZlibConstants.Z_OK, rc, String.Format("at InitializeDeflate() [{0}]", compressingStream.Message));

            compressingStream.OutputBuffer = compressedBytes;
            compressingStream.AvailableBytesOut = compressedBytes.Length;
            compressingStream.NextOut = 0;
            System.Random rnd = new Random();

            for (int k = 0; k < 4; k++)
            {
                switch (k)
                {
                    case 0:
                        // At this point, workBuffer is all zeroes, so it should compress very well.
                        break;

                    case 1:
                        // switch to no compression, keep same workBuffer (all zeroes):
                        compressingStream.SetDeflateParams(CompressionLevel.None, CompressionStrategy.Default);
                        break;

                    case 2:
                        // Insert data into workBuffer, and switch back to compressing mode.
                        // we'll use lengths of the same random byte:
                        for (int i = 0; i < workBuffer.Length / 1000; i++)
                        {
                            byte b = (byte)rnd.Next();
                            int n = 500 + rnd.Next(500);
                            for (j = 0; j < n; j++)
                                workBuffer[j + i] = b;
                            i += j - 1;
                        }
                        compressingStream.SetDeflateParams(CompressionLevel.BestCompression, CompressionStrategy.Filtered);
                        break;

                    case 3:
                        // insert totally random data into the workBuffer
                        rnd.NextBytes(workBuffer);
                        break;
                }

                compressingStream.InputBuffer = workBuffer;
                compressingStream.NextIn = 0;
                compressingStream.AvailableBytesIn = workBuffer.Length;
                rc = compressingStream.Deflate(FlushType.None);
                Assert.AreEqual<int>(ZlibConstants.Z_OK, rc, String.Format("at Deflate({0}) [{1}]", k, compressingStream.Message));

                if (k == 0)
                    Assert.AreEqual<int>(0, compressingStream.AvailableBytesIn, "Deflate should be greedy.");

                TestContext.WriteLine("Stage {0}: uncompressed/compresssed bytes so far:  ({1,6}/{2,6})",
                      k, compressingStream.TotalBytesIn, compressingStream.TotalBytesOut);
            }

            rc = compressingStream.Deflate(FlushType.Finish);
            Assert.AreEqual<int>(ZlibConstants.Z_STREAM_END, rc, String.Format("at Deflate() [{0}]", compressingStream.Message));

            rc = compressingStream.EndDeflate();
            Assert.AreEqual<int>(ZlibConstants.Z_OK, rc, String.Format("at EndDeflate() [{0}]", compressingStream.Message));

            TestContext.WriteLine("Final: uncompressed/compressed bytes: ({0,6},{1,6})",
                  compressingStream.TotalBytesIn, compressingStream.TotalBytesOut);

            ZlibCodec decompressingStream = new ZlibCodec(CompressionMode.Decompress);

            decompressingStream.InputBuffer = compressedBytes;
            decompressingStream.NextIn = 0;
            decompressingStream.AvailableBytesIn = bufferSize;

            // upon inflating, we overwrite the decompressedBytes buffer repeatedly
            int nCycles = 0;
            while (true)
            {
                decompressingStream.OutputBuffer = workBuffer;
                decompressingStream.NextOut = 0;
                decompressingStream.AvailableBytesOut = workBuffer.Length;
                rc = decompressingStream.Inflate(FlushType.None);

                nCycles++;

                if (rc == ZlibConstants.Z_STREAM_END)
                    break;

                Assert.AreEqual<int>(ZlibConstants.Z_OK, rc, String.Format("at Inflate() [{0}] TotalBytesOut={1}",
                                       decompressingStream.Message, decompressingStream.TotalBytesOut));
            }

            rc = decompressingStream.EndInflate();
            Assert.AreEqual<int>(ZlibConstants.Z_OK, rc, String.Format("at EndInflate() [{0}]", decompressingStream.Message));

            Assert.AreEqual<int>(4 * workBuffer.Length, (int)decompressingStream.TotalBytesOut);

            TestContext.WriteLine("compressed length: {0}", compressingStream.TotalBytesOut);
            TestContext.WriteLine("decompressed length (expected): {0}", 4 * workBuffer.Length);
            TestContext.WriteLine("decompressed length (actual)  : {0}", decompressingStream.TotalBytesOut);
            TestContext.WriteLine("decompression cycles: {0}", nCycles);
        }
Exemplo n.º 11
0
        public void Zlib_TestFlushSync()
        {
            int rc;
            int bufferSize = 40000;
            byte[] CompressedBytes = new byte[bufferSize];
            byte[] DecompressedBytes = new byte[bufferSize];
            string TextToCompress = "This is the text that will be compressed.";
            byte[] BytesToCompress = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToCompress);

            ZlibCodec compressor = new ZlibCodec(CompressionMode.Compress);

            compressor.InputBuffer = BytesToCompress;
            compressor.NextIn = 0;
            compressor.AvailableBytesIn = 3;

            compressor.OutputBuffer = CompressedBytes;
            compressor.NextOut = 0;
            compressor.AvailableBytesOut = CompressedBytes.Length;

            rc = compressor.Deflate(FlushType.Full);

            CompressedBytes[3]++; // force an error in first compressed block // dinoch - ??
            compressor.AvailableBytesIn = TextToCompress.Length - 3;

            rc = compressor.Deflate(FlushType.Finish);
            Assert.AreEqual<int>(ZlibConstants.Z_STREAM_END, rc, String.Format("at Deflate() [{0}]", compressor.Message));

            rc = compressor.EndDeflate();
            bufferSize = (int)(compressor.TotalBytesOut);

            ZlibCodec decompressor = new ZlibCodec(CompressionMode.Decompress);

            decompressor.InputBuffer = CompressedBytes;
            decompressor.NextIn = 0;
            decompressor.AvailableBytesIn = 2;

            decompressor.OutputBuffer = DecompressedBytes;
            decompressor.NextOut = 0;
            decompressor.AvailableBytesOut = DecompressedBytes.Length;

            rc = decompressor.Inflate(FlushType.None);
            decompressor.AvailableBytesIn = bufferSize - 2;

            rc = decompressor.SyncInflate();

            bool gotException = false;
            try
            {
                rc = decompressor.Inflate(FlushType.Finish);
            }
            catch (ZlibException ex1)
            {
                TestContext.WriteLine("Got Expected Exception: " + ex1);
                gotException = true;
            }

            Assert.IsTrue(gotException, "inflate should report DATA_ERROR");

            rc = decompressor.EndInflate();
            Assert.AreEqual<int>(ZlibConstants.Z_OK, rc, String.Format("at EndInflate() [{0}]", decompressor.Message));

            int j = 0;
            for (; j < DecompressedBytes.Length; j++)
                if (DecompressedBytes[j] == 0)
                    break;

            var result = System.Text.ASCIIEncoding.ASCII.GetString(DecompressedBytes, 0, j);

            Assert.AreEqual<int>(TextToCompress.Length, result.Length + 3, "Strings are unequal lengths");

            Console.WriteLine("orig length: {0}", TextToCompress.Length);
            Console.WriteLine("compressed length: {0}", compressor.TotalBytesOut);
            Console.WriteLine("uncompressed length: {0}", decompressor.TotalBytesOut);
            Console.WriteLine("result length: {0}", result.Length);
            Console.WriteLine("result of inflate:\n(Thi){0}", result);
        }
Exemplo n.º 12
0
    private void Run()
    {
        int rc;
        int comprLen = 40000;
        int uncomprLen = comprLen;
        byte[] CompressedBytes = new byte[comprLen];
        byte[] DecompressedBytes = new byte[uncomprLen];
        string TextToCompress = "This is the text that will be compressed.";
        byte[] BytesToCompress = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToCompress);

        ZlibCodec compressor = new ZlibCodec(CompressionMode.Compress);

        compressor.InputBuffer = BytesToCompress;
        compressor.NextIn = 0;
        compressor.OutputBuffer = CompressedBytes;
        compressor.NextOut = 0;
        compressor.AvailableBytesIn = 3;
        compressor.AvailableBytesOut = CompressedBytes.Length;
                
        rc = compressor.Deflate(ZlibConstants.Z_FULL_FLUSH);
        CheckForError(compressor, rc, "Deflate");
                
        CompressedBytes[3]++; // force an error in first compressed block // dinoch 
        compressor.AvailableBytesIn = TextToCompress.Length - 3;

        rc = compressor.Deflate(ZlibConstants.Z_FINISH);
        if (rc != ZlibConstants.Z_STREAM_END)
        {
            CheckForError(compressor, rc, "Deflate");
        }
        rc = compressor.EndDeflate();
        CheckForError(compressor, rc, "EndDeflate");
        comprLen = (int) (compressor.TotalBytesOut);
                
        ZlibCodec decompressor = new ZlibCodec(CompressionMode.Decompress);
                
        decompressor.InputBuffer = CompressedBytes;
        decompressor.NextIn = 0;
        decompressor.AvailableBytesIn = 2;

        decompressor.OutputBuffer = DecompressedBytes;
        decompressor.NextOut = 0;
        decompressor.AvailableBytesOut = DecompressedBytes.Length;

        rc = decompressor.Inflate(ZlibConstants.Z_NO_FLUSH);
        CheckForError(decompressor, rc, "Inflate");
                
        decompressor.AvailableBytesIn = CompressedBytes.Length - 2;

        rc = decompressor.SyncInflate();
        CheckForError(decompressor, rc, "SyncInflate");

        bool gotException = false;
        try
        {
            rc = decompressor.Inflate(ZlibConstants.Z_FINISH);
        }
        catch (ZlibException ex1)
        {
            Console.WriteLine("Got Expected Exception: " + ex1);
            gotException = true;
        }

        if (!gotException)
        {
            System.Console.Out.WriteLine("inflate should report DATA_ERROR");
            /* Because of incorrect adler32 */
            System.Environment.Exit(1);
        }
                
        rc = decompressor.EndInflate();
        CheckForError(decompressor, rc, "EndInflate");
                
        int j = 0;
        for (; j < DecompressedBytes.Length; j++)
            if (DecompressedBytes[j] == 0)
                break;

        var result = System.Text.ASCIIEncoding.ASCII.GetString(DecompressedBytes, 0, j);

        Console.WriteLine("orig length: {0}", TextToCompress.Length);
        Console.WriteLine("compressed length: {0}", compressor.TotalBytesOut);
        Console.WriteLine("uncompressed length: {0}", decompressor.TotalBytesOut);
        Console.WriteLine("result length: {0}", result.Length);
        Console.WriteLine("result of inflate:\n(Thi){0}", result);
    }
Exemplo n.º 13
0
        public byte[] ExtractBytes(MAS2File f)
        {
            var reader = new BinaryReader(System.IO.File.OpenRead(this._File));
            reader.BaseStream.Seek(f.FileOffset, SeekOrigin.Begin);
            var rawData = reader.ReadBytes((int)f.CompressedSize);
            reader.Close();

            if (f.IsCompressed)
            {
                var outputData = new byte[f.UncompressedSize];

                // MAS2 compression consists of a simple inflate/deflate action.
                var codec = new ZlibCodec(CompressionMode.Decompress);
                codec.InitializeInflate();
                codec.InputBuffer = rawData;
                codec.NextIn = 0;
                codec.AvailableBytesIn = rawData.Length;

                codec.OutputBuffer = outputData;
                codec.NextOut = 0;
                codec.AvailableBytesOut = outputData.Length;

                codec.Inflate(FlushType.None);
                codec.EndInflate();

                return outputData;
            }
            else
            {
                return rawData;
            }
        }
Exemplo n.º 14
0
        public Packet Inflate(int inflatedSize, bool keepStream = true)
        {
            var arr = ReadToEnd();
            var newarr = new byte[inflatedSize];

            if (ClientVersion.RemovedInVersion(ClientVersionBuild.V4_3_0_15005))
                keepStream = false;

            if (keepStream)
            {
                int idx = ConnectionIndex;
                while (!TryInflate(inflatedSize, idx, arr, ref newarr))
                    idx += 1;
            }
            else
            {
                /*try
                {
                    var inflater = new Inflater(true);
                    inflater.SetInput(arr, 0, arr.Length);
                    inflater.Inflate(newarr, 0, inflatedSize);
                }
                catch (ICSharpCode.SharpZipLib.SharpZipBaseException)
                {
                    var inflater = new Inflater(true);
                    inflater.SetInput(arr, 0, arr.Length);
                    inflater.Inflate(newarr, 0, inflatedSize);
                }*/
                var stream = new ZlibCodec(CompressionMode.Decompress)
                {
                    InputBuffer = arr,
                    NextIn = 0,
                    AvailableBytesIn = arr.Length,
                    OutputBuffer = newarr,
                    NextOut = 0,
                    AvailableBytesOut = inflatedSize
                };

                stream.Inflate(FlushType.None);
                stream.Inflate(FlushType.Finish);
                stream.EndInflate();
            }

            // Cannot use "using" here
            var pkt = new Packet(newarr, Opcode, Time, Direction, Number, Writer, FileName);
            pkt.ConnectionIndex = ConnectionIndex;
            return pkt;
        }
Exemplo n.º 15
0
        public void ExtractFile(MAS2File f, string target)
        {
            BinaryReader reader = new BinaryReader(System.IO.File.OpenRead(this.mas2_file));
            reader.BaseStream.Seek(f.FileOffset, SeekOrigin.Begin);
            byte[] RawData = reader.ReadBytes((int)f.CompressedSize);

            if (f.IsCompressed)
            {
                byte[] OutputData = new byte[f.UncompressedSize];

                // MAS2 compression consists of a simple inflate/deflate process.
                ZlibCodec codec = new ZlibCodec(CompressionMode.Decompress);
                codec.InitializeInflate();
                codec.InputBuffer = RawData;
                codec.NextIn = 0;
                codec.AvailableBytesIn = RawData.Length;

                codec.OutputBuffer = OutputData;
                codec.NextOut = 0;
                codec.AvailableBytesOut = OutputData.Length;

                codec.Inflate(FlushType.None);
                codec.EndInflate();

                System.IO.File.WriteAllBytes(target, OutputData);
            }
            else
            {
                System.IO.File.WriteAllBytes(target, RawData);
            }
        }
Exemplo n.º 16
0
        public void Zlib_BasicDeflateAndInflate()
        {
            string TextToCompress = LoremIpsum;

            int rc;
            int bufferSize = 40000;
            byte[] compressedBytes = new byte[bufferSize];
            byte[] decompressedBytes = new byte[bufferSize];

            ZlibCodec compressingStream = new ZlibCodec();

            rc = compressingStream.InitializeDeflate(CompressionLevel.Default);
            Assert.AreEqual<int>(ZlibConstants.Z_OK, rc, String.Format("at InitializeDeflate() [{0}]", compressingStream.Message));

            compressingStream.InputBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToCompress);
            compressingStream.NextIn = 0;

            compressingStream.OutputBuffer = compressedBytes;
            compressingStream.NextOut = 0;

            while (compressingStream.TotalBytesIn != TextToCompress.Length && compressingStream.TotalBytesOut < bufferSize)
            {
                compressingStream.AvailableBytesIn = compressingStream.AvailableBytesOut = 1; // force small buffers
                rc = compressingStream.Deflate(FlushType.None);
                Assert.AreEqual<int>(ZlibConstants.Z_OK, rc, String.Format("at Deflate(1) [{0}]", compressingStream.Message));
            }

            while (true)
            {
                compressingStream.AvailableBytesOut = 1;
                rc = compressingStream.Deflate(FlushType.Finish);
                if (rc == ZlibConstants.Z_STREAM_END)
                    break;
                Assert.AreEqual<int>(ZlibConstants.Z_OK, rc, String.Format("at Deflate(2) [{0}]", compressingStream.Message));
            }

            rc = compressingStream.EndDeflate();
            Assert.AreEqual<int>(ZlibConstants.Z_OK, rc, String.Format("at EndDeflate() [{0}]", compressingStream.Message));

            ZlibCodec decompressingStream = new ZlibCodec();

            decompressingStream.InputBuffer = compressedBytes;
            decompressingStream.NextIn = 0;
            decompressingStream.OutputBuffer = decompressedBytes;
            decompressingStream.NextOut = 0;

            rc = decompressingStream.InitializeInflate();
            Assert.AreEqual<int>(ZlibConstants.Z_OK, rc, String.Format("at InitializeInflate() [{0}]", decompressingStream.Message));
            //CheckForError(decompressingStream, rc, "inflateInit");

            while (decompressingStream.TotalBytesOut < decompressedBytes.Length && decompressingStream.TotalBytesIn < bufferSize)
            {
                decompressingStream.AvailableBytesIn = decompressingStream.AvailableBytesOut = 1; /* force small buffers */
                rc = decompressingStream.Inflate(FlushType.None);
                if (rc == ZlibConstants.Z_STREAM_END)
                    break;
                Assert.AreEqual<int>(ZlibConstants.Z_OK, rc, String.Format("at Inflate() [{0}]", decompressingStream.Message));
                //CheckForError(decompressingStream, rc, "inflate");
            }

            rc = decompressingStream.EndInflate();
            Assert.AreEqual<int>(ZlibConstants.Z_OK, rc, String.Format("at EndInflate() [{0}]", decompressingStream.Message));
            //CheckForError(decompressingStream, rc, "inflateEnd");

            int j = 0;
            for (; j < decompressedBytes.Length; j++)
                if (decompressedBytes[j] == 0)
                    break;

            Assert.AreEqual<int>(TextToCompress.Length, j, String.Format("Unequal lengths"));

            int i = 0;
            for (i = 0; i < j; i++)
                if (TextToCompress[i] != decompressedBytes[i])
                    break;

            Assert.AreEqual<int>(j, i, String.Format("Non-identical content"));

            var result = System.Text.ASCIIEncoding.ASCII.GetString(decompressedBytes, 0, j);

            TestContext.WriteLine("orig length: {0}", TextToCompress.Length);
            TestContext.WriteLine("compressed length: {0}", compressingStream.TotalBytesOut);
            TestContext.WriteLine("decompressed length: {0}", decompressingStream.TotalBytesOut);
            TestContext.WriteLine("result length: {0}", result.Length);
            TestContext.WriteLine("result of inflate:\n{0}", result);
            return;
        }
    private void Run()
    {
        int rc;
        int j;
        int bufferSize = 40000;
        byte[] compressedBytes = new byte[bufferSize];
        byte[] bufferToCompress= new byte[bufferSize];
        byte[] decompressedBytes = new byte[bufferSize];

        ZlibCodec compressingStream= new ZlibCodec();

        rc = compressingStream.InitializeDeflate(CompressionLevel.BestSpeed);
        CheckForError(compressingStream, rc, "InitializeDeflate");

        compressingStream.OutputBuffer = compressedBytes;
        compressingStream.NextOut = 0;
        compressingStream.AvailableBytesOut = compressedBytes.Length;

        // At this point, bufferToCompress is all zeroes, so it should compress
        // very well:
        compressingStream.InputBuffer = bufferToCompress;
        compressingStream.AvailableBytesIn = bufferToCompress.Length;
        rc = compressingStream.Deflate(FlushType.None);
        CheckForError(compressingStream, rc, "deflate");
        if (compressingStream.AvailableBytesIn != 0)
        {
            System.Console.Out.WriteLine("deflate not greedy");
            System.Environment.Exit(1);
        }

        Console.WriteLine("Stage 1: uncompressed bytes in so far:  {0,6}", compressingStream.TotalBytesIn);
        Console.WriteLine("          compressed bytes out so far:  {0,6}", compressingStream.TotalBytesOut);            


        // Feed in already compressed data and switch to no compression:
        compressingStream.SetDeflateParams(CompressionLevel.None, CompressionStrategy.Default);
        compressingStream.InputBuffer = compressedBytes;
        compressingStream.NextIn = 0;
        compressingStream.AvailableBytesIn = bufferSize / 2; // why? - for fun
        rc = compressingStream.Deflate(FlushType.None);
        CheckForError(compressingStream, rc, "Deflate");

        Console.WriteLine("Stage 2: uncompressed bytes in so far:  {0,6}", compressingStream.TotalBytesIn);
        Console.WriteLine("          compressed bytes out so far:  {0,6}", compressingStream.TotalBytesOut);

        // Insert data into bufferToCompress, and Switch back to compressing mode:
        System.Random rnd = new Random();

        for (int i = 0; i < bufferToCompress.Length / 1000; i++)
        {
            byte b = (byte) rnd.Next();
            int n = 500 + rnd.Next(500);
            for (j = 0; j < n; j++)
                bufferToCompress[j + i] = b;
            i += j-1;
        }

        compressingStream.SetDeflateParams(CompressionLevel.BestCompression, CompressionStrategy.Filtered);
        compressingStream.InputBuffer = bufferToCompress;
        compressingStream.NextIn = 0;
        compressingStream.AvailableBytesIn = bufferToCompress.Length;
        rc = compressingStream.Deflate(FlushType.None);
        CheckForError(compressingStream, rc, "Deflate");

        Console.WriteLine("Stage 3: uncompressed bytes in so far:  {0,6}", compressingStream.TotalBytesIn);
        Console.WriteLine("          compressed bytes out so far:  {0,6}", compressingStream.TotalBytesOut);

        rc = compressingStream.Deflate(FlushType.Finish);
        if (rc != ZlibConstants.Z_STREAM_END)
        {
            Console.WriteLine("deflate reported {0}, should report Z_STREAM_END", rc);
            Environment.Exit(1);
        }
        rc = compressingStream.EndDeflate();
        CheckForError(compressingStream, rc, "EndDeflate");

        Console.WriteLine("Stage 4: uncompressed bytes in (final): {0,6}", compressingStream.TotalBytesIn);
        Console.WriteLine("          compressed bytes out (final): {0,6}", compressingStream.TotalBytesOut);

        ZlibCodec decompressingStream = new ZlibCodec(CompressionMode.Decompress);
                
        decompressingStream.InputBuffer = compressedBytes;
        decompressingStream.NextIn = 0;
        decompressingStream.AvailableBytesIn = bufferSize;
                                
        // upon inflating, we overwrite the decompressedBytes buffer repeatedly
        while (true)
        {
            decompressingStream.OutputBuffer = decompressedBytes;
            decompressingStream.NextOut = 0;
            decompressingStream.AvailableBytesOut = decompressedBytes.Length;
            rc = decompressingStream.Inflate(FlushType.None);
            if (rc == ZlibConstants.Z_STREAM_END)
                break;
            CheckForError(decompressingStream, rc, "inflate large");
        }
                
        rc = decompressingStream.EndInflate();
        CheckForError(decompressingStream, rc, "EndInflate");

        if (decompressingStream.TotalBytesOut != 2 * decompressedBytes.Length + bufferSize / 2)
        {
            System.Console.WriteLine("bad large inflate: " + decompressingStream.TotalBytesOut);
            System.Environment.Exit(1);
        }

        for (j = 0; j < decompressedBytes.Length; j++)
            if (decompressedBytes[j] == 0)
                break;

        Console.WriteLine("compressed length: {0}", compressingStream.TotalBytesOut);
        Console.WriteLine("decompressed length (expected): {0}", 2 * decompressedBytes.Length + bufferSize / 2);
        Console.WriteLine("decompressed length (actual)  : {0}", decompressingStream.TotalBytesOut);
    }
Exemplo n.º 18
0
        public void Zlib_BasicDictionaryDeflateInflate()
        {
            int rc;
            int comprLen = 40000;
            int uncomprLen = comprLen;
            byte[] uncompr = new byte[uncomprLen];
            byte[] compr = new byte[comprLen];
            //long dictId;

            ZlibCodec compressor = new ZlibCodec();
            rc = compressor.InitializeDeflate(CompressionLevel.BestCompression);
            Assert.AreEqual<int>(ZlibConstants.Z_OK, rc, String.Format("at InitializeDeflate() [{0}]", compressor.Message));

            string dictionaryWord = "hello ";
            byte[] dictionary = System.Text.ASCIIEncoding.ASCII.GetBytes(dictionaryWord);
            string TextToCompress = "hello, hello!  How are you, Joe? I said hello. ";
            byte[] BytesToCompress = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToCompress);

            rc = compressor.SetDictionary(dictionary);
            Assert.AreEqual<int>(ZlibConstants.Z_OK, rc, String.Format("at SetDeflateDictionary() [{0}]", compressor.Message));

            int dictId = compressor.Adler32;

            compressor.OutputBuffer = compr;
            compressor.NextOut = 0;
            compressor.AvailableBytesOut = comprLen;

            compressor.InputBuffer = BytesToCompress;
            compressor.NextIn = 0;
            compressor.AvailableBytesIn = BytesToCompress.Length;

            rc = compressor.Deflate(FlushType.Finish);
            Assert.AreEqual<int>(ZlibConstants.Z_STREAM_END, rc, String.Format("at Deflate() [{0}]", compressor.Message));

            rc = compressor.EndDeflate();
            Assert.AreEqual<int>(ZlibConstants.Z_OK, rc, String.Format("at EndDeflate() [{0}]", compressor.Message));


            ZlibCodec decompressor = new ZlibCodec();

            decompressor.InputBuffer = compr;
            decompressor.NextIn = 0;
            decompressor.AvailableBytesIn = comprLen;

            rc = decompressor.InitializeInflate();
            Assert.AreEqual<int>(ZlibConstants.Z_OK, rc, String.Format("at InitializeInflate() [{0}]", decompressor.Message));

            decompressor.OutputBuffer = uncompr;
            decompressor.NextOut = 0;
            decompressor.AvailableBytesOut = uncomprLen;

            while (true)
            {
                rc = decompressor.Inflate(FlushType.None);
                if (rc == ZlibConstants.Z_STREAM_END)
                {
                    break;
                }
                if (rc == ZlibConstants.Z_NEED_DICT)
                {
                    Assert.AreEqual<long>(dictId, decompressor.Adler32, "Unexpected Dictionary");
                    rc = decompressor.SetDictionary(dictionary);
                }
                Assert.AreEqual<int>(ZlibConstants.Z_OK, rc, String.Format("at Inflate/SetInflateDictionary() [{0}]", decompressor.Message));
            }

            rc = decompressor.EndInflate();
            Assert.AreEqual<int>(ZlibConstants.Z_OK, rc, String.Format("at EndInflate() [{0}]", decompressor.Message));

            int j = 0;
            for (; j < uncompr.Length; j++)
                if (uncompr[j] == 0)
                    break;

            Assert.AreEqual<int>(TextToCompress.Length, j, String.Format("Unequal lengths"));

            int i = 0;
            for (i = 0; i < j; i++)
                if (TextToCompress[i] != uncompr[i])
                    break;

            Assert.AreEqual<int>(j, i, String.Format("Non-identical content"));

            var result = System.Text.ASCIIEncoding.ASCII.GetString(uncompr, 0, j);

            TestContext.WriteLine("orig length: {0}", TextToCompress.Length);
            TestContext.WriteLine("compressed length: {0}", compressor.TotalBytesOut);
            TestContext.WriteLine("uncompressed length: {0}", decompressor.TotalBytesOut);
            TestContext.WriteLine("result length: {0}", result.Length);
            TestContext.WriteLine("result of inflate:\n{0}", result);
        }
Exemplo n.º 19
0
        public Packet Inflate(int inflatedSize, bool keepStream = true)
        {
            var arr = ReadToEnd();
            var newarr = new byte[inflatedSize];

            if (ClientVersion.RemovedInVersion(ClientVersionBuild.V4_3_0_15005))
                keepStream = false;

            if (keepStream)
            {
                if (!SessionHandler.z_streams.ContainsKey(ConnectionIndex))
                    SessionHandler.z_streams[ConnectionIndex] = new ZlibCodec(CompressionMode.Decompress);
                SessionHandler.z_streams[ConnectionIndex].InputBuffer = arr;
                SessionHandler.z_streams[ConnectionIndex].NextIn = 0;
                SessionHandler.z_streams[ConnectionIndex].AvailableBytesIn = arr.Length;
                SessionHandler.z_streams[ConnectionIndex].OutputBuffer = newarr;
                SessionHandler.z_streams[ConnectionIndex].NextOut = 0;
                SessionHandler.z_streams[ConnectionIndex].AvailableBytesOut = inflatedSize;
                SessionHandler.z_streams[ConnectionIndex].Inflate(FlushType.Sync);
            }
            else
            {
                /*try
                {
                    var inflater = new Inflater(true);
                    inflater.SetInput(arr, 0, arr.Length);
                    inflater.Inflate(newarr, 0, inflatedSize);
                }
                catch (ICSharpCode.SharpZipLib.SharpZipBaseException)
                {
                    var inflater = new Inflater(true);
                    inflater.SetInput(arr, 0, arr.Length);
                    inflater.Inflate(newarr, 0, inflatedSize);
                }*/
                ZlibCodec stream = new ZlibCodec(CompressionMode.Decompress);
                stream.InputBuffer = arr;
                stream.NextIn = 0;
                stream.AvailableBytesIn = arr.Length;
                stream.OutputBuffer = newarr;
                stream.NextOut = 0;
                stream.AvailableBytesOut = inflatedSize;
                stream.Inflate(FlushType.None);
                stream.Inflate(FlushType.Finish);
                stream.EndInflate();
            }

            // Cannot use "using" here
            var pkt = new Packet(newarr, Opcode, Time, Direction, Number, Writer, FileName);
            pkt.ConnectionIndex = ConnectionIndex;
            return pkt;
        }
    private void Run()
    {
        int rc;
        int bufferSize = 40000;
        byte[] compressedBytes = new byte[bufferSize];
        byte[] decompressedBytes = new byte[bufferSize];
        
        ZlibCodec compressingStream = new ZlibCodec();
        rc = compressingStream.InitializeDeflate(CompressionLevel.LEVEL9_BEST_COMPRESSION);
        CheckForError(compressingStream, rc, "InitializeDeflate");

        string dictionaryWord = "hello ";
        byte[] dictionary = System.Text.ASCIIEncoding.ASCII.GetBytes(dictionaryWord);
        string TextToCompress = "hello, hello!  How are you, Joe? ";
        byte[] BytesToCompress = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToCompress);

        rc = compressingStream.SetDictionary(dictionary);
        CheckForError(compressingStream, rc, "SetDeflateDictionary");

        long dictId = compressingStream.Adler32;

        compressingStream.OutputBuffer = compressedBytes;
        compressingStream.NextOut = 0;
        compressingStream.AvailableBytesOut = bufferSize;

        compressingStream.InputBuffer = BytesToCompress;
        compressingStream.NextIn = 0;
        compressingStream.AvailableBytesIn = BytesToCompress.Length;

        rc = compressingStream.Deflate(ZlibConstants.Z_FINISH);
        if (rc != ZlibConstants.Z_STREAM_END)
        {
            System.Console.Out.WriteLine("deflate should report Z_STREAM_END");
            System.Environment.Exit(1);
        }
        rc = compressingStream.EndDeflate();
        CheckForError(compressingStream, rc, "deflateEnd");

        ZlibCodec decompressingStream = new ZlibCodec();

        decompressingStream.InputBuffer = compressedBytes;
        decompressingStream.NextIn = 0;
        decompressingStream.AvailableBytesIn = bufferSize;

        rc = decompressingStream.InitializeInflate();
        CheckForError(decompressingStream, rc, "inflateInit");
        decompressingStream.OutputBuffer = decompressedBytes;
        decompressingStream.NextOut = 0;
        decompressingStream.AvailableBytesOut = decompressedBytes.Length;

        while (true)
        {
            rc = decompressingStream.Inflate(ZlibConstants.Z_NO_FLUSH);
            if (rc == ZlibConstants.Z_STREAM_END)
            {
                break;
            }
            if (rc == ZlibConstants.Z_NEED_DICT)
            {
                if ((int)decompressingStream.Adler32 != (int)dictId)
                {
                    System.Console.Out.WriteLine("unexpected dictionary");
                    System.Environment.Exit(1);
                }
                rc = decompressingStream.SetDictionary(dictionary);
            }
            CheckForError(decompressingStream, rc, "inflate with dict");
        }

        rc = decompressingStream.EndInflate();
        CheckForError(decompressingStream, rc, "EndInflate");

        int j = 0;
        for (; j < decompressedBytes.Length; j++)
            if (decompressedBytes[j] == 0)
                break;

        var result = System.Text.ASCIIEncoding.ASCII.GetString(decompressedBytes, 0, j);

        Console.WriteLine("orig length: {0}", TextToCompress.Length);
        Console.WriteLine("compressed length: {0}", compressingStream.TotalBytesOut);
        Console.WriteLine("decompressed length: {0}", decompressingStream.TotalBytesOut);
        Console.WriteLine("result length: {0}", result.Length);
        Console.WriteLine("result of inflate:\n{0}", result);
    }