using System; using System.Collections.Generic; using System.Linq; using System.Text; using Ionic.Zlib; namespace MinecraftClient.Protocol.Handlers { /// /// Quick Zlib compression handling for network packet compression. /// Note: Underlying compression handling is taken from the DotNetZip Library. /// This library is open source and provided under the Microsoft Public License. /// More info about DotNetZip at dotnetzip.codeplex.com. /// public static class ZlibUtils { /// /// Compress a byte array into another bytes array using Zlib compression /// /// Data to compress /// Compressed data as a byte array public static byte[] Compress(byte[] to_compress) { ZlibStream stream = new ZlibStream(new System.IO.MemoryStream(to_compress, false), CompressionMode.Compress); List temp_compression_list = new List(); byte[] b = new byte[1]; while (true) { int read = stream.Read(b, 0, 1); if (read > 0) { temp_compression_list.Add(b[0]); } else break; } stream.Close(); return temp_compression_list.ToArray(); } /// /// Decompress a byte array into another byte array of the specified size /// /// Data to decompress /// Size of the data once decompressed /// Decompressed data as a byte array public static byte[] Decompress(byte[] to_decompress, int size_uncompressed) { ZlibStream stream = new ZlibStream(new System.IO.MemoryStream(to_decompress, false), CompressionMode.Decompress); byte[] packetData_decompressed = new byte[size_uncompressed]; stream.Read(packetData_decompressed, 0, size_uncompressed); stream.Close(); return packetData_decompressed; } /// /// Decompress a byte array into another byte array of a potentially unlimited size (!) /// /// Data to decompress /// Decompressed data as byte array public static byte[] Decompress(byte[] to_decompress) { ZlibStream stream = new ZlibStream(new System.IO.MemoryStream(to_decompress, false), CompressionMode.Decompress); byte[] buffer = new byte[16 * 1024]; using (System.IO.MemoryStream decompressedBuffer = new System.IO.MemoryStream()) { int read; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) decompressedBuffer.Write(buffer, 0, read); return decompressedBuffer.ToArray(); } } } }