protected override void Dispose(bool disposing) { try { base.Dispose(disposing); } finally { deflateStream.Dispose(); } }
protected override void Dispose(bool disposing) { if (disposing) { deflateStream.Dispose(); } base.Dispose(disposing); }
public static void CompressCanWrite() { var ms = new MemoryStream(); var zip = new DeflateStream(ms, CompressionMode.Compress); Assert.True(zip.CanWrite); zip.Dispose(); Assert.False(zip.CanWrite); }
/// <summary> Copy the contents of a stored file into an opened stream. </summary> /// <param name="zfe"> Entry information of file to extract. </param> /// <param name="stream"> Stream to store the uncompressed data. </param> /// <returns> True if success, false if not. </returns> /// <remarks> Unique compression methods are Store and Deflate. </remarks> public bool ExtractFile(ZipFileEntry zfe, [NotNull] Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } if (!stream.CanWrite) { throw new InvalidOperationException("Stream cannot be written"); } // check signature byte[] signature = new byte[4]; zipFileStream.Seek(zfe.HeaderOffset, SeekOrigin.Begin); zipFileStream.Read(signature, 0, 4); if (BitConverter.ToUInt32(signature, 0) != 0x04034b50) { return(false); } // Select input stream for inflating or just reading Stream inStream; switch (zfe.Method) { case Compression.Store: inStream = zipFileStream; break; case Compression.Deflate: inStream = new DeflateStream(zipFileStream, CompressionMode.Decompress, true); break; default: return(false); } // Buffered copy byte[] buffer = new byte[16384]; zipFileStream.Seek(zfe.FileOffset, SeekOrigin.Begin); uint bytesPending = zfe.FileSize; while (bytesPending > 0) { int bytesRead = inStream.Read(buffer, 0, (int)Math.Min(bytesPending, buffer.Length)); stream.Write(buffer, 0, bytesRead); bytesPending -= (uint)bytesRead; } stream.Flush(); if (zfe.Method == Compression.Deflate) { inStream.Dispose(); } return(true); }
protected override void Dispose(bool disposing) { if (disposing) { if (deflateStream != null) { deflateStream.Dispose(); deflateStream = null; } } base.Dispose(disposing); }
/// <summary> /// Copy the contents of a stored file into an opened stream /// </summary> /// <param name="_zfe">Entry information of file to extract</param> /// <param name="_stream">Stream to store the uncompressed data</param> /// <returns>True if success, false if not.</returns> /// <remarks>Unique compression methods are Store and Deflate</remarks> public Boolean ExtractFile(ZipFileEntry _zfe, Stream _stream) { if (!_stream.CanWrite) { throw new InvalidOperationException("Stream cannot be written"); } // check signature Byte[] signature = new Byte[4]; ZipFileStream.Seek(_zfe.HeaderOffset, SeekOrigin.Begin); ZipFileStream.Read(signature, 0, 4); if (BitConverter.ToUInt32(signature, 0) != 0x04034b50) { return(false); } // Select input stream for inflating or just reading Stream inStream; switch (_zfe.Method) { case Compression.Store: inStream = ZipFileStream; break; case Compression.Deflate: inStream = new DeflateStream(ZipFileStream, CompressionMode.Decompress, true); break; default: return(false); } // Buffered copy Byte[] buffer = new Byte[16384]; ZipFileStream.Seek(_zfe.FileOffset, SeekOrigin.Begin); UInt32 bytesPending = _zfe.FileSize; while (bytesPending > 0) { Int32 bytesRead = inStream.Read(buffer, 0, (Int32)Math.Min(bytesPending, buffer.Length)); _stream.Write(buffer, 0, bytesRead); bytesPending -= (UInt32)bytesRead; } _stream.Flush(); if (_zfe.Method == Compression.Deflate) { inStream.Dispose(); } return(true); }
public static byte[] DeflateCompress(byte[] DATA) { MemoryStream ms = new MemoryStream(); DeflateStream stream = new DeflateStream(ms, CompressionMode.Compress, true); stream.Write(DATA, 0, DATA.Length); stream.Close(); stream.Dispose(); stream = null; byte[] buffer = StreamDataHelper.ReadDataToBytes(ms); ms.Close(); ms.Dispose(); ms = null; return buffer; }
public static int CompressTileBlock(int xStart, int yStart, short width, short height, byte[] buffer, int bufferStart) { int result; using (MemoryStream memoryStream = new MemoryStream()) { using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream)) { binaryWriter.Write(xStart); binaryWriter.Write(yStart); binaryWriter.Write(width); binaryWriter.Write(height); NetMessage.CompressTileBlock_Inner(binaryWriter, xStart, yStart, (int)width, (int)height); int num = buffer.Length; if ((long)bufferStart + memoryStream.Length > (long)num) { result = (int)((long)(num - bufferStart) + memoryStream.Length); } else { memoryStream.Position = 0L; MemoryStream memoryStream2 = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(memoryStream2, CompressionMode.Compress, true)) { memoryStream.CopyTo(deflateStream); deflateStream.Flush(); deflateStream.Close(); deflateStream.Dispose(); } if (memoryStream.Length <= memoryStream2.Length) { memoryStream.Position = 0L; buffer[bufferStart] = 0; bufferStart++; memoryStream.Read(buffer, bufferStart, (int)memoryStream.Length); result = (int)memoryStream.Length + 1; } else { memoryStream2.Position = 0L; buffer[bufferStart] = 1; bufferStart++; memoryStream2.Read(buffer, bufferStart, (int)memoryStream2.Length); result = (int)memoryStream2.Length + 1; } } } } return result; }
protected override void Dispose(bool disposing) { try { if (disposing && _deflateStream != null) { _deflateStream.Dispose(); } _deflateStream = null; } finally { base.Dispose(disposing); } }
public static Stream CompressStream(Stream instream) { MemoryStream outstream = new MemoryStream((int)instream.Length); DeflateStream comp = new DeflateStream(outstream, CompressionMode.Compress, true); int numBytes; byte[] buffer = new byte[4096]; while ((numBytes = instream.Read(buffer, 0, 4096)) != 0) { comp.Write(buffer, 0, numBytes); } comp.Flush(); comp.Dispose(); // return to the beginning of the stream outstream.Position = 0; //Debug.WriteLine("Compression: " + instream.Length.ToString() + " to " + outstream.Length.ToString()); return outstream; }
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { Stream compressedStream = null; switch (_contentEncoding) { case "gzip": compressedStream = new GZipStream(stream, CompressionMode.Compress, leaveOpen: true); break; case "deflate": compressedStream = new DeflateStream(stream, CompressionMode.Compress, leaveOpen: true); break; } return _initialContent.CopyToAsync(compressedStream).ContinueWith(tsk => { if (compressedStream != null) { compressedStream.Dispose(); } }); }
public void CompressorNotClosed_DecompressorStillSuccessful(bool closeCompressorBeforeDecompression) { const string Input = "example"; var ms = new MemoryStream(); using (var compressor = new DeflateStream(ms, CompressionLevel.Optimal, leaveOpen: closeCompressorBeforeDecompression)) { compressor.Write(Encoding.ASCII.GetBytes(Input)); compressor.Flush(); if (closeCompressorBeforeDecompression) { compressor.Dispose(); } ms.Position = 0; using (var decompressor = new DeflateStream(ms, CompressionMode.Decompress, leaveOpen: true)) { var decompressed = new MemoryStream(); decompressor.CopyTo(decompressed); Assert.Equal(Input, Encoding.ASCII.GetString(decompressed.ToArray())); } } }
public static void CanDisposeDeflateStream() { var ms = new MemoryStream(); var zip = new DeflateStream(ms, CompressionMode.Compress); zip.Dispose(); // Base Stream should be null after dispose Assert.Null(zip.BaseStream); zip.Dispose(); // Should be a no-op }
public static async Task CanReadBaseStreamAfterDispose() { var ms = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz")); var newMs = StripHeaderAndFooter.Strip(ms); var zip = new DeflateStream(newMs, CompressionMode.Decompress, true); var baseStream = zip.BaseStream; zip.Dispose(); int size = 1024; Byte[] bytes = new Byte[size]; baseStream.Read(bytes, 0, size); // This will throw if the underlying stream is not writeable as expected baseStream.Position = 0; await baseStream.ReadAsync(bytes, 0, size); }
public static Stream DeflateCompress(Stream DATA) { byte[] buffer = StreamDataHelper.ReadDataToBytes(DATA); MemoryStream ms = new MemoryStream(); DeflateStream stream = new DeflateStream(ms, CompressionMode.Compress, true); stream.Write(buffer, 0, buffer.Length); stream.Close(); stream.Dispose(); stream = null; if (ms.CanSeek) { ms.Position = 0; } return ms; }
public void DisposeTest () { MemoryStream backing = new MemoryStream (compressed_data); DeflateStream decompress = new DeflateStream (backing, CompressionMode.Decompress); decompress.Dispose (); decompress.Dispose (); }
// ********************************************************************** public static Stream GetDataStream(FileStream fs) { byte[] buffer = new byte[prefix.Length]; if(CheckPrefix(fs, buffer)) return fs; Stream stream = null; try { fs.Position = 0; stream = new GZipStream(fs, CompressionMode.Decompress, true); if(CheckPrefix(stream, buffer)) return stream; } catch { } if(stream != null) { stream.Dispose(); stream = null; } try { fs.Position = 0; stream = new DeflateStream(fs, CompressionMode.Decompress, true); if(CheckPrefix(stream, buffer)) return stream; } catch { } if(stream != null) { stream.Dispose(); stream = null; } throw new FormatException("Неверный формат файла"); }
public static int CompressTileBlock(int xStart, int yStart, short width, short height, byte[] buffer, int bufferStart) { using (MemoryStream memoryStream1 = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter((Stream)memoryStream1)) { writer.Write(xStart); writer.Write(yStart); writer.Write(width); writer.Write(height); NetMessage.CompressTileBlock_Inner(writer, xStart, yStart, (int)width, (int)height); int length = buffer.Length; if ((long)bufferStart + memoryStream1.Length > (long)length) return (int)((long)(length - bufferStart) + memoryStream1.Length); memoryStream1.Position = 0L; MemoryStream memoryStream2 = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream((Stream)memoryStream2, CompressionMode.Compress, true)) { memoryStream1.CopyTo((Stream)deflateStream); deflateStream.Flush(); deflateStream.Close(); deflateStream.Dispose(); } if (memoryStream1.Length <= memoryStream2.Length) { memoryStream1.Position = 0L; buffer[bufferStart] = (byte)0; ++bufferStart; memoryStream1.Read(buffer, bufferStart, (int)memoryStream1.Length); return (int)memoryStream1.Length + 1; } memoryStream2.Position = 0L; buffer[bufferStart] = (byte)1; ++bufferStart; memoryStream2.Read(buffer, bufferStart, (int)memoryStream2.Length); return (int)memoryStream2.Length + 1; } } }
internal byte[] Compress(byte[] decompressedBuffer) { MemoryStream memStream = new MemoryStream(); DeflateStream zip = new DeflateStream(memStream, CompressionMode.Compress, true); zip.Write(decompressedBuffer, 0, decompressedBuffer.Length); zip.Close(); memStream.Position = 0; byte[] buffer = new byte[memStream.Length + 2]; //Console.WriteLine(BitConverter.ToString(memStream.ToArray())); memStream.Read(buffer, 2, buffer.Length - 2); memStream.Close(); memStream.Dispose(); zip.Dispose(); System.Buffer.BlockCopy(new byte[] { 0x78, 0x9C }, 0, buffer, 0, 2); return buffer; }
byte[] DecompressEntry( BinaryReader reader, ushort compressionMethod, int compressedSize, int uncompressedSize ) { if( compressionMethod == 0 ) { // Store/Raw return reader.ReadBytes( uncompressedSize ); } else if( compressionMethod == 8 ) { // Deflate byte[] data = new byte[uncompressedSize]; byte[] compressedData = reader.ReadBytes( compressedSize ); MemoryStream stream = new MemoryStream( compressedData ); int index = 0, read = 0; DeflateStream deflater = new DeflateStream( stream, CompressionMode.Decompress ); while( index < uncompressedSize && ( read = deflater.Read( data, index, data.Length - index ) ) > 0 ) { index += read; } deflater.Dispose(); return data; } else { Utils.LogDebug( "Unsupported .zip entry compression method: " + compressionMethod ); reader.ReadBytes( compressedSize ); return null; } }
public void Zlib_Streams_VariousSizes() { byte[] working = new byte[WORKING_BUFFER_SIZE]; int n = -1; Int32[] Sizes = { 8000, 88000, 188000, 388000, 580000, 1580000 }; for (int p = 0; p < Sizes.Length; p++) { // both binary and text files for (int m = 0; m < 2; m++) { int sz = this.rnd.Next(Sizes[p]) + Sizes[p]; string FileToCompress = System.IO.Path.Combine(TopLevelDir, String.Format("Zlib_Streams.{0}.{1}", sz, (m == 0) ? "txt" : "bin")); Assert.IsFalse(System.IO.File.Exists(FileToCompress), "The temporary file '{0}' already exists.", FileToCompress); TestContext.WriteLine("Creating file {0} {1} bytes", FileToCompress, sz); if (m == 0) CreateAndFillFileText(FileToCompress, sz); else _CreateAndFillBinary(FileToCompress, sz, false); int crc1 = DoCrc(FileToCompress); TestContext.WriteLine("Initial CRC: 0x{0:X8}", crc1); // try both GZipStream and DeflateStream for (int k = 0; k < 2; k++) { // compress with Ionic and System.IO.Compression for (int i = 0; i < 2; i++) { string CompressedFileRoot = String.Format("{0}.{1}.{2}.compressed", FileToCompress, (k == 0) ? "GZIP" : "DEFLATE", (i == 0) ? "Ionic" : "BCL"); int x = k + i * 2; int z = (x == 0) ? 4 : 1; // why 4 trials?? (only for GZIP and Ionic) for (int h = 0; h < z; h++) { string CompressedFile = (x == 0) ? CompressedFileRoot + ".trial" + h : CompressedFileRoot; using (var input = System.IO.File.OpenRead(FileToCompress)) { using (var raw = System.IO.File.Create(CompressedFile)) { Stream compressor = null; try { switch (x) { case 0: // k == 0, i == 0 compressor = new Ionic.Zlib.GZipStream(raw, CompressionMode.Compress, true); break; case 1: // k == 1, i == 0 compressor = new Ionic.Zlib.DeflateStream(raw, CompressionMode.Compress, true); break; case 2: // k == 0, i == 1 compressor = new System.IO.Compression.GZipStream(raw, System.IO.Compression.CompressionMode.Compress, true); break; case 3: // k == 1, i == 1 compressor = new System.IO.Compression.DeflateStream(raw, System.IO.Compression.CompressionMode.Compress, true); break; } //TestContext.WriteLine("Compress with: {0} ..", compressor.GetType().FullName); TestContext.WriteLine("........{0} ...", System.IO.Path2.GetFileName(CompressedFile)); if (x == 0) { if (h != 0) { Ionic.Zlib.GZipStream gzip = compressor as Ionic.Zlib.GZipStream; if (h % 2 == 1) gzip.FileName = FileToCompress; if (h > 2) gzip.Comment = "Compressing: " + FileToCompress; } } n = -1; while ((n = input.Read(working, 0, working.Length)) != 0) { compressor.Write(working, 0, n); } } finally { if (compressor != null) compressor.Dispose(); } } } // now, decompress with Ionic and System.IO.Compression // for (int j = 0; j < 2; j++) for (int j = 1; j >= 0; j--) { using (var input = System.IO.File.OpenRead(CompressedFile)) { Stream decompressor = null; try { int w = k + j * 2; switch (w) { case 0: // k == 0, j == 0 decompressor = new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true); break; case 1: // k == 1, j == 0 decompressor = new Ionic.Zlib.DeflateStream(input, CompressionMode.Decompress, true); break; case 2: // k == 0, j == 1 decompressor = new System.IO.Compression.GZipStream(input, System.IO.Compression.CompressionMode.Decompress, true); break; case 3: // k == 1, j == 1 decompressor = new System.IO.Compression.DeflateStream(input, System.IO.Compression.CompressionMode.Decompress, true); break; } //TestContext.WriteLine("Decompress: {0} ...", decompressor.GetType().FullName); string DecompressedFile = String.Format("{0}.{1}.decompressed", CompressedFile, (j == 0) ? "Ionic" : "BCL"); TestContext.WriteLine("........{0} ...", System.IO.Path2.GetFileName(DecompressedFile)); using (var s2 = System.IO.File.Create(DecompressedFile)) { n = -1; while (n != 0) { n = decompressor.Read(working, 0, working.Length); if (n > 0) s2.Write(working, 0, n); } } int crc2 = DoCrc(DecompressedFile); Assert.AreEqual<UInt32>((UInt32)crc1, (UInt32)crc2); } finally { if (decompressor != null) decompressor.Dispose(); } } } } } } } } TestContext.WriteLine("Done."); }
public static void SaveMap() { if (!Main.mapEnabled || MapHelper.saveLock) { return; } string text = Main.playerPathName.Substring(0, Main.playerPathName.Length - 4); lock (MapHelper.padlock) { try { MapHelper.saveLock = true; try { Directory.CreateDirectory(text); } catch { } text = string.Concat(new object[] { text, Path.DirectorySeparatorChar, Main.worldID, ".map" }); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); bool flag2 = false; if (!Main.gameMenu) { flag2 = true; } using (MemoryStream memoryStream = new MemoryStream(4000)) { using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream)) { using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress)) { int num = 0; byte[] array = new byte[16384]; binaryWriter.Write(Main.curRelease); Main.MapFileMetadata.IncrementAndWrite(binaryWriter); binaryWriter.Write(Main.worldName); binaryWriter.Write(Main.worldID); binaryWriter.Write(Main.maxTilesY); binaryWriter.Write(Main.maxTilesX); binaryWriter.Write(419); binaryWriter.Write(225); binaryWriter.Write(3); binaryWriter.Write(256); binaryWriter.Write(256); binaryWriter.Write(256); byte b = 1; byte b2 = 0; int i; for (i = 0; i < 419; i++) { if (MapHelper.tileOptionCounts[i] != 1) { b2 |= b; } if (b == 128) { binaryWriter.Write(b2); b2 = 0; b = 1; } else { b = (byte)(b << 1); } } if (b != 1) { binaryWriter.Write(b2); } i = 0; b = 1; b2 = 0; while (i < 225) { if (MapHelper.wallOptionCounts[i] != 1) { b2 |= b; } if (b == 128) { binaryWriter.Write(b2); b2 = 0; b = 1; } else { b = (byte)(b << 1); } i++; } if (b != 1) { binaryWriter.Write(b2); } for (i = 0; i < 419; i++) { if (MapHelper.tileOptionCounts[i] != 1) { binaryWriter.Write((byte)MapHelper.tileOptionCounts[i]); } } for (i = 0; i < 225; i++) { if (MapHelper.wallOptionCounts[i] != 1) { binaryWriter.Write((byte)MapHelper.wallOptionCounts[i]); } } binaryWriter.Flush(); for (int j = 0; j < Main.maxTilesY; j++) { if (!flag2) { float num2 = (float)j / (float)Main.maxTilesY; Main.statusText = string.Concat(new object[] { Lang.gen[66], " ", (int)(num2 * 100f + 1f), "%" }); } for (int k = 0; k < Main.maxTilesX; k++) { MapTile mapTile = Main.Map[k, j]; byte b4; byte b3 = b4 = 0; bool flag3 = true; bool flag4 = true; int num3 = 0; int num4 = 0; byte b5 = 0; int num5; ushort num6; int num7; if (mapTile.Light <= 18) { flag4 = false; flag3 = false; num5 = 0; num6 = 0; num7 = 0; int num8 = k + 1; int l = Main.maxTilesX - k - 1; while (l > 0) { if (Main.Map[num8, j].Light > 18) { break; } num7++; l--; num8++; } } else { b5 = mapTile.Color; num6 = mapTile.Type; if (num6 < MapHelper.wallPosition) { num5 = 1; num6 -= MapHelper.tilePosition; } else if (num6 < MapHelper.liquidPosition) { num5 = 2; num6 -= MapHelper.wallPosition; } else if (num6 < MapHelper.skyPosition) { num5 = (int)(3 + (num6 - MapHelper.liquidPosition)); flag3 = false; } else if (num6 < MapHelper.dirtPosition) { num5 = 6; flag4 = false; flag3 = false; } else if (num6 < MapHelper.hellPosition) { num5 = 7; if (num6 < MapHelper.rockPosition) { num6 -= MapHelper.dirtPosition; } else { num6 -= MapHelper.rockPosition; } } else { num5 = 6; flag3 = false; } if (mapTile.Light == 255) { flag4 = false; } if (flag4) { num7 = 0; int num8 = k + 1; int l = Main.maxTilesX - k - 1; num3 = num8; while (l > 0) { MapTile mapTile2 = Main.Map[num8, j]; if (!mapTile.EqualsWithoutLight(ref mapTile2)) { num4 = num8; break; } l--; num7++; num8++; } } else { num7 = 0; int num8 = k + 1; int l = Main.maxTilesX - k - 1; while (l > 0) { MapTile mapTile3 = Main.Map[num8, j]; if (!mapTile.Equals(ref mapTile3)) { break; } l--; num7++; num8++; } } } if (b5 > 0) { b3 |= (byte)(b5 << 1); } if (b3 != 0) { b4 |= 1; } b4 |= (byte)(num5 << 1); if (flag3 && num6 > 255) { b4 |= 16; } if (flag4) { b4 |= 32; } if (num7 > 0) { if (num7 > 255) { b4 |= 128; } else { b4 |= 64; } } array[num] = b4; num++; if (b3 != 0) { array[num] = b3; num++; } if (flag3) { array[num] = (byte)num6; num++; if (num6 > 255) { array[num] = (byte)(num6 >> 8); num++; } } if (flag4) { array[num] = mapTile.Light; num++; } if (num7 > 0) { array[num] = (byte)num7; num++; if (num7 > 255) { array[num] = (byte)(num7 >> 8); num++; } } for (int m = num3; m < num4; m++) { array[num] = Main.Map[m, j].Light; num++; } k += num7; if (num >= 4096) { deflateStream.Write(array, 0, num); num = 0; } } } if (num > 0) { deflateStream.Write(array, 0, num); } deflateStream.Dispose(); FileUtilities.WriteAllBytes(text, memoryStream.ToArray()); } } } } catch (Exception value) { using (StreamWriter streamWriter = new StreamWriter("client-crashlog.txt", true)) { streamWriter.WriteLine(DateTime.Now); streamWriter.WriteLine(value); streamWriter.WriteLine(""); } } MapHelper.saveLock = false; } }
internal override void Receive() { lock (TcpClient) { base.Receive(); if (DataLength == 0) return; var response = new byte[DataLength]; var bytesRead = 0; do { Settings.Launcher.UpdateProgressInvokable(string.Format("Downloading: {0}kb / {1}kb", bytesRead / 1024, DataLength / 1024), bytesRead / 1024, DataLength / 1024); bytesRead += TcpClient.GetStream().Read(response, bytesRead, Math.Min(DataLength - bytesRead, 4096)); //System.Threading.Thread.Sleep(50); //simulate remote connect } while (bytesRead < DataLength); var memstream = new MemoryStream(response); var gzstream = new DeflateStream(memstream, CompressionMode.Decompress); var worldSettingsSizeBytes = new byte[sizeof(int)]; bytesRead = 0; while (bytesRead < sizeof(int)) { bytesRead += gzstream.Read(worldSettingsSizeBytes, bytesRead, sizeof(int) - bytesRead); //read the size of the world config xml } UncompressedLength = bytesRead; var worldSettingsBytes = new byte[BitConverter.ToInt32(worldSettingsSizeBytes, 0)]; bytesRead = 0; while (bytesRead < worldSettingsBytes.Length) { bytesRead += gzstream.Read(worldSettingsBytes, bytesRead, worldSettingsBytes.Length - bytesRead); } UncompressedLength += bytesRead; WorldSettings.LoadSettings(worldSettingsBytes); var chunkTotal = WorldData.SizeInChunksX * WorldData.SizeInChunksZ; var chunkCount = 1; for (var x = 0; x < WorldData.SizeInChunksX; x++) //loop through each chunk and load it { for (var z = 0; z < WorldData.SizeInChunksZ; z++) { Settings.Launcher.UpdateProgressInvokable(string.Format("Loading Chunks: {0} / {1}", chunkCount, chunkTotal), chunkCount, chunkTotal); bytesRead = 0; var chunkBytes = new byte[Chunk.SIZE_IN_BYTES]; while (bytesRead < chunkBytes.Length) { var byteCount = gzstream.Read(chunkBytes, bytesRead, chunkBytes.Length - bytesRead); if (byteCount <= 0) throw new Exception("Received incomplete world."); //gm: was sometimes getting zero here because the gzipstream wasnt getting flushed properly, might as well leave the check here bytesRead += byteCount; } UncompressedLength += bytesRead; WorldData.LoadChunk(WorldData.Chunks[x, z], chunkBytes); chunkCount++; } } gzstream.Dispose(); memstream.Dispose(); } WorldData.InitializeAllLightMaps(); Settings.Launcher.UpdateProgressInvokable("World Ready", 0, 0); WorldData.IsLoaded = true; }
//#endif public void SendTileRowCompressed(int xStart, int yStart, short width, short height, bool packChests) { Begin(Packet.SEND_TILE_ROW); var bufferStart = this.bin.BaseStream.Position; using (MemoryStream memoryStream = new MemoryStream()) { using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream)) { binaryWriter.Write(xStart); binaryWriter.Write(yStart); binaryWriter.Write(width); binaryWriter.Write(height); NetMessage.CompressTileBlock_Inner(binaryWriter, xStart, yStart, (int)width, (int)height); int num = this.buf.Length; if ((long)bufferStart + memoryStream.Length > (long)num) { //result = (int)((long)(num - bufferStart) + memoryStream.Length); } else { memoryStream.Position = 0L; MemoryStream memoryStream2 = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(memoryStream2, CompressionMode.Compress, true)) { memoryStream.CopyTo(deflateStream); deflateStream.Flush(); deflateStream.Close(); deflateStream.Dispose(); } if (memoryStream.Length <= memoryStream2.Length) { memoryStream.Position = 0L; //buffer[bufferStart] = 0; Byte(0); //memoryStream.Read(buffer, bufferStart, (int)memoryStream.Length); //result = (int)memoryStream.Length + 1; var b = new byte[128]; int read = 0; while ((read = memoryStream.Read(b, 0, b.Length)) > 0) { Byte(b, read); } } else { memoryStream2.Position = 0L; Byte(1); //memoryStream2.Read(buffer, bufferStart, (int)memoryStream2.Length); //memoryStream2.CopyTo(sink); //result = (int)memoryStream2.Length + 1; var b = new byte[128]; int read = 0; while ((read = memoryStream2.Read(b, 0, b.Length)) > 0) { Byte(b, read); } } } } } End(); }
/// <summary> /// Gets the client-side save state as a string. /// </summary> /// <returns></returns> string GetSaveString(Document document) { Contract.Requires<ArgumentNullException>(document != null); using (var stream = new MemoryStream()) using (var encode = new CryptoStream(stream, new ToBase64Transform(), CryptoStreamMode.Write)) using (var deflate = new DeflateStream(encode, CompressionMode.Compress)) using (var writer = XmlDictionaryWriter.CreateBinaryWriter(deflate)) { document.Save(writer); // flush output writer.Dispose(); deflate.Dispose(); encode.Dispose(); return Encoding.ASCII.GetString(stream.ToArray()); } }
public static async Task FlushAsyncFailsAfterDispose() { var ms = new MemoryStream(); var ds = new DeflateStream(ms, CompressionMode.Compress); ds.Dispose(); await Assert.ThrowsAsync<ObjectDisposedException>(async () => { await ds.FlushAsync(); }); }
public void compressData() { MemoryStream outbuf = new MemoryStream(); DeflateStream compress = new DeflateStream(outbuf, CompressionMode.Compress); compress.Write(data.buf, 0, data.Length); compress.Close(); byte[] compData = outbuf.ToArray(); retvalue = compData.Length; compress.Dispose(); outbuf.Dispose(); }
public static void FlushFailsAfterDispose() { var ms = new MemoryStream(); var ds = new DeflateStream(ms, CompressionMode.Compress); ds.Dispose(); Assert.Throws<ObjectDisposedException>(() => { ds.Flush(); }); }
/// <summary> /// Copy the contents of a stored file into an opened stream /// </summary> /// <param name="zfe">Entry information of file to extract</param> /// <param name="stream">Stream to store the uncompressed data</param> /// <returns>True if success, false if not.</returns> /// <remarks>Unique compression methods are Store and Deflate</remarks> public bool ExtractFile(ZipFileEntry zfe, Stream stream) { if (!stream.CanWrite) throw new InvalidOperationException("Stream cannot be written"); // check signature var signature = new byte[4]; _zipFileStream.Seek(zfe.HeaderOffset, SeekOrigin.Begin); _zipFileStream.Read(signature, 0, 4); if (BitConverter.ToUInt32(signature, 0) != 0x04034b50) return false; // Select input stream for inflating or just reading Stream inStream; switch (zfe.Method) { case Compression.Store: inStream = _zipFileStream; break; case Compression.Deflate: inStream = new DeflateStream(_zipFileStream, CompressionMode.Decompress, true); break; default: return false; } // Buffered copy var buffer = new byte[16384]; _zipFileStream.Seek(zfe.FileOffset, SeekOrigin.Begin); var bytesPending = zfe.FileSize; while (bytesPending > 0) { var bytesRead = inStream.Read(buffer, 0, (int) Math.Min(bytesPending, buffer.Length)); stream.Write(buffer, 0, bytesRead); bytesPending -= (uint) bytesRead; } stream.Flush(); if (zfe.Method == Compression.Deflate) inStream.Dispose(); return true; }
internal byte[] Decompress(byte[] compressedBuffer, int decompressedSize) { MemoryStream memStream = new MemoryStream(); memStream.Write(compressedBuffer, 2, compressedBuffer.Length - 2); byte[] buffer = new byte[decompressedSize]; memStream.Position = 0; DeflateStream zip = new DeflateStream(memStream, CompressionMode.Decompress); zip.Read(buffer, 0, buffer.Length); zip.Close(); zip.Dispose(); memStream.Close(); memStream.Dispose(); return buffer; }
public static void SaveMap() { int i; int num; int num1; ushort type; int num2; if (!Main.mapEnabled || MapHelper.saveLock) { return; } string str = Main.playerPathName.Substring(0, Main.playerPathName.Length - 4); lock (MapHelper.padlock) { try { MapHelper.saveLock = true; try { Directory.CreateDirectory(str); } catch (Exception ex) { #if DEBUG Console.WriteLine(ex); System.Diagnostics.Debugger.Break(); #endif } object[] directorySeparatorChar = new object[] { str, Path.DirectorySeparatorChar, Main.worldID, ".map" }; str = string.Concat(directorySeparatorChar); (new Stopwatch()).Start(); bool flag = false; if (!Main.gameMenu) { flag = true; } using (MemoryStream memoryStream = new MemoryStream(4000)) { using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream)) { using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress)) { int num3 = 0; byte[] light = new byte[16384]; binaryWriter.Write(Main.curRelease); Main.MapFileMetadata.IncrementAndWrite(binaryWriter); binaryWriter.Write(Main.worldName); binaryWriter.Write(Main.worldID); binaryWriter.Write(Main.maxTilesY); binaryWriter.Write(Main.maxTilesX); binaryWriter.Write((short)419); binaryWriter.Write((short)225); binaryWriter.Write((short)3); binaryWriter.Write((short)256); binaryWriter.Write((short)256); binaryWriter.Write((short)256); byte num4 = 1; byte num5 = 0; for (i = 0; i < 419; i++) { if (MapHelper.tileOptionCounts[i] != 1) { num5 = (byte)(num5 | num4); } if (num4 != 128) { num4 = (byte)(num4 << 1); } else { binaryWriter.Write(num5); num5 = 0; num4 = 1; } } if (num4 != 1) { binaryWriter.Write(num5); } i = 0; num4 = 1; num5 = 0; while (i < 225) { if (MapHelper.wallOptionCounts[i] != 1) { num5 = (byte)(num5 | num4); } if (num4 != 128) { num4 = (byte)(num4 << 1); } else { binaryWriter.Write(num5); num5 = 0; num4 = 1; } i++; } if (num4 != 1) { binaryWriter.Write(num5); } for (i = 0; i < 419; i++) { if (MapHelper.tileOptionCounts[i] != 1) { binaryWriter.Write((byte)MapHelper.tileOptionCounts[i]); } } for (i = 0; i < 225; i++) { if (MapHelper.wallOptionCounts[i] != 1) { binaryWriter.Write((byte)MapHelper.wallOptionCounts[i]); } } binaryWriter.Flush(); for (int j = 0; j < Main.maxTilesY; j++) { if (!flag) { float single = (float)j / (float)Main.maxTilesY; object[] objArray = new object[] { Lang.gen[66], " ", (int)(single * 100f + 1f), "%" }; Main.statusText = string.Concat(objArray); } for (int k = 0; k < Main.maxTilesX; k++) { MapTile item = Main.Map[k, j]; int num6 = 0; byte num7 = (byte)num6; byte num8 = (byte)num6; int num9 = 0; bool flag1 = true; bool flag2 = true; int num10 = 0; int num11 = 0; byte color = 0; if (item.Light > 18) { color = item.Color; type = item.Type; if (type < MapHelper.wallPosition) { num1 = 1; type = (ushort)(type - MapHelper.tilePosition); } else if (type < MapHelper.liquidPosition) { num1 = 2; type = (ushort)(type - MapHelper.wallPosition); } else if (type < MapHelper.skyPosition) { num1 = 3 + (type - MapHelper.liquidPosition); flag1 = false; } else if (type < MapHelper.dirtPosition) { num1 = 6; flag2 = false; flag1 = false; } else if (type >= MapHelper.hellPosition) { num1 = 6; flag1 = false; } else { num1 = 7; type = (type >= MapHelper.rockPosition ? (ushort)(type - MapHelper.rockPosition) : (ushort)(type - MapHelper.dirtPosition)); } if (item.Light == 255) { flag2 = false; } if (!flag2) { num9 = 0; num = k + 1; num2 = Main.maxTilesX - k - 1; while (num2 > 0) { MapTile mapTile = Main.Map[num, j]; if (!item.Equals(ref mapTile)) { break; } num2--; num9++; num++; } } else { num9 = 0; num = k + 1; num2 = Main.maxTilesX - k - 1; num10 = num; while (num2 > 0) { MapTile item1 = Main.Map[num, j]; if (!item.EqualsWithoutLight(ref item1)) { num11 = num; goto Label0; } else { num2--; num9++; num++; } } } } else { flag2 = false; flag1 = false; num1 = 0; type = 0; num9 = 0; num = k + 1; num2 = Main.maxTilesX - k - 1; while (num2 > 0) { if (Main.Map[num, j].Light > 18) { goto Label0; } num9++; num2--; num++; } } Label0: if (color > 0) { num7 = (byte)(num7 | (byte)(color << 1)); } if (num7 != 0) { num8 = (byte)(num8 | 1); } num8 = (byte)(num8 | (byte)(num1 << 1)); if (flag1 && type > 255) { num8 = (byte)(num8 | 16); } if (flag2) { num8 = (byte)(num8 | 32); } if (num9 > 0) { num8 = (num9 <= 255 ? (byte)(num8 | 64) : (byte)(num8 | 128)); } light[num3] = num8; num3++; if (num7 != 0) { light[num3] = num7; num3++; } if (flag1) { light[num3] = (byte)type; num3++; if (type > 255) { light[num3] = (byte)(type >> 8); num3++; } } if (flag2) { light[num3] = item.Light; num3++; } if (num9 > 0) { light[num3] = (byte)num9; num3++; if (num9 > 255) { light[num3] = (byte)(num9 >> 8); num3++; } } for (int l = num10; l < num11; l++) { light[num3] = Main.Map[l, j].Light; num3++; } k = k + num9; if (num3 >= 4096) { deflateStream.Write(light, 0, num3); num3 = 0; } } } if (num3 > 0) { deflateStream.Write(light, 0, num3); } deflateStream.Dispose(); FileUtilities.WriteAllBytes(str, memoryStream.ToArray()); } } } } catch (Exception exception1) { Exception exception = exception1; using (StreamWriter streamWriter = new StreamWriter("client-crashlog.txt", true)) { streamWriter.WriteLine(DateTime.Now); streamWriter.WriteLine(exception); streamWriter.WriteLine(""); } } MapHelper.saveLock = false; } }
public byte[] CompressDataSet(DataSet ds) { ds.RemotingFormat = SerializationFormat.Binary; BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, ds); byte[] inbyt = ms.ToArray(); MemoryStream objStream = new MemoryStream(); DeflateStream objZS = new DeflateStream(objStream, CompressionMode.Compress); objZS.Write(inbyt, 0, inbyt.Length); objZS.Flush(); objZS.Close(); byte[] b = objStream.ToArray(); objZS.Dispose(); return b; }
public void bitmapCompressData() { byte[] bm = new byte[data.Length/4]; byte[] dt = new byte[data.Length]; int bi = 0, di = 0; for (int i=0; i<data.Length; i+=sizeof(UInt32)) if (data.buf[i+3] == 0) bm[bi++]=0x00; else { bm[bi++]=0xFF; dt[di++] = data.buf[i]; dt[di++] = data.buf[i+1]; dt[di++] = data.buf[i+2]; } MemoryStream outbuf = new MemoryStream(); DeflateStream compress = new DeflateStream(outbuf, CompressionMode.Compress); compress.Write(bm, 0, bi); compress.Write(dt, 0, di); compress.Close(); byte[] compData = outbuf.ToArray(); retvalue = compData.Length; compress.Dispose(); outbuf.Dispose(); }
public void CheckGetCanWriteProp () { MemoryStream backing = new MemoryStream (); DeflateStream decompress = new DeflateStream (backing, CompressionMode.Decompress); Assert.IsFalse (decompress.CanWrite, "#A1"); Assert.IsTrue (backing.CanWrite, "#A2"); decompress.Dispose (); Assert.IsFalse (decompress.CanWrite, "#A3"); Assert.IsFalse (backing.CanWrite, "#A4"); backing = new MemoryStream (); DeflateStream compress = new DeflateStream (backing, CompressionMode.Compress); Assert.IsTrue (compress.CanWrite, "#B1"); Assert.IsTrue (backing.CanWrite, "#B2"); compress.Dispose (); Assert.IsFalse (decompress.CanWrite, "#B3"); Assert.IsFalse (backing.CanWrite, "#B4"); }
public bool DecompressMovieHeader() { MovieBox moov = this.Children.OfType<MovieBox>().SingleOrDefault(); if (moov == null) return false; CompressedMovieBox cmov = moov.Children.OfType<CompressedMovieBox>().SingleOrDefault(); if (cmov == null) return false; DataCompressionBox dcom = cmov.Children.OfType<DataCompressionBox>().SingleOrDefault(); if (dcom == null) return false; CompressedMovieDataBox cmvd = cmov.Children.OfType<CompressedMovieDataBox>().SingleOrDefault(); if (cmvd == null) return false; if (dcom.Format != "zlib") throw new FileFormatException("Unsupported compression type: " + dcom.Format); Stream contentStream = cmvd.GetContentStream(); contentStream.ReadByte(); contentStream.ReadByte(); Stream compressedStream = new DeflateStream(contentStream, CompressionMode.Decompress, true); MemoryStream uncompressedStream = new MemoryStream(); compressedStream.CopyTo(uncompressedStream); uncompressedStream.Flush(); compressedStream.Dispose(); uncompressedStream.Seek(0, SeekOrigin.Begin); BaseMedia uncompressedMoov = new BaseMedia(uncompressedStream); MovieBox newMoov = uncompressedMoov.Children.OfType<MovieBox>().SingleOrDefault(); if (newMoov != null) { int insertionPoint = Children.IndexOf(moov); Children.Remove(moov); FreeSpaceBox free = new FreeSpaceBox(moov.EffectiveSize); ((ObservableCollection<Box>)Children).Insert(insertionPoint, free); ((ObservableCollection<Box>)Children).Add(newMoov); } return true; }
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { Stream compressedStream = new DeflateStream(stream, CompressionMode.Compress, leaveOpen: true); return (_originalContent == null)? Task.Run(() => GetMensagem()): _originalContent.CopyToAsync(compressedStream).ContinueWith(tsk => { if (compressedStream != null) compressedStream.Dispose(); }); }
public static byte[] DeflateDecompress(byte[] data) { MemoryStream ms = new MemoryStream(data); DeflateStream stream = new DeflateStream(ms, CompressionMode.Decompress); byte[] buffer = StreamDataHelper.ReadDataToBytes(stream); ms.Close(); ms.Dispose(); ms = null; stream.Close(); stream.Dispose(); stream = null; return buffer; }