Ejemplo n.º 1
0
        /// <summary>
        /// Closes the stream.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (_mode == CompressionMode.Decompress)
            {
                // Can only check Adler checksum on seekable streams.  Since DeflateStream
                // aggresively caches input, it normally has already consumed the footer.
                if (_stream.CanSeek)
                {
                    _stream.Seek(-4, SeekOrigin.End);
                    byte[] footerBuffer = StreamUtilities.ReadExact(_stream, 4);
                    if (EndianUtilities.ToInt32BigEndian(footerBuffer, 0) != _adler32.Value)
                    {
                        throw new InvalidDataException("Corrupt decompressed data detected");
                    }
                }

                _deflateStream.Dispose();
            }
            else
            {
                _deflateStream.Dispose();

                byte[] footerBuffer = new byte[4];
                EndianUtilities.WriteBytesBigEndian(_adler32.Value, footerBuffer, 0);
                _stream.Write(footerBuffer, 0, 4);
            }

            base.Dispose(disposing);
        }
Ejemplo n.º 2
0
        [Category("StaticLinkedAotNotWorking")]          // Native MPH loading issues
        public void DisposeTest()
        {
            MemoryStream  backing    = new MemoryStream(compressed_data);
            DeflateStream decompress = new DeflateStream(backing, CompressionMode.Decompress);

            decompress.Dispose();
            decompress.Dispose();
        }
Ejemplo n.º 3
0
        public void DoubleDispose()
        {
            var ms = new MemoryStream();
            var ds = new DeflateStream(ms, CompressionMode.Compress);

            ds.Dispose();
            ds.Dispose();
        }
Ejemplo n.º 4
0
        public 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
        }
Ejemplo n.º 5
0
 internal override void Dispose(bool disposing)
 {
     if (!_isDisposed)
     {
         if (disposing)
         {
             _connectCancelToken?.Dispose();
             (WebSocketClient as IDisposable)?.Dispose();
             _decompressor?.Dispose();
             _compressed?.Dispose();
         }
         _isDisposed = true;
     }
 }
Ejemplo n.º 6
0
        public override byte[] EndCompress()
        {
            m_Deflate.Dispose();
            m_Deflate = null;

            try
            {
                return(m_Memory.ToArray());
            }
            finally
            {
                m_Memory.Position = 0;
                m_Memory.SetLength(0);
            }
        }
Ejemplo n.º 7
0
        public byte[] ReadAt(int pos, int cnt)
        {
            EnsureReadMode();
            int end = pos + cnt - 1;

            if (pos < 0 || end > OriginalSize)
            {
                throw new ArgumentOutOfRangeException();
            }
            int startIdx = pos / ExtraField.ChunkSize;
            int offset   = pos % ExtraField.ChunkSize;
            int endIdx   = end / ExtraField.ChunkSize;

            if (startIdx != _lastStart || endIdx != _lastEnd || _buf == null)
            {
                _lastStart = startIdx;
                _lastEnd   = endIdx;
                _buf       = new byte[(endIdx - startIdx + 1) * ExtraField.ChunkSize];
                //read chunks
                for (int i = startIdx; i <= endIdx; ++i)
                {
                    FileStream.Position = _dataBegin + ExtraField.Indices[i];
                    DeflateStream.Dispose();
                    DeflateStream = new DeflateStream(FileStream, CompressionMode.Decompress, true);
                    //If I keep using the same deflatestream the data will become corrupted
                    //when crossing chunks, I don't no why :(

                    Read(_buf, (i - startIdx) * ExtraField.ChunkSize, ExtraField.ChunkSize);
                }
            }
            byte[] res = new byte[cnt];
            Buffer.BlockCopy(_buf, offset, res, 0, cnt);
            return(res);
        }
 public virtual void Close()
 {
     if (!initdone)
     {
         doInit();            // can happen if never called write
     }
     if (closed)
     {
         return;
     }
     closed = true;
     if (deflateStream != null)
     {
         deflateStream.Dispose();
     }
     if (crcread == null)   // eat trailing 4 bytes
     {
         crcread = new byte[4];
         for (int i = 0; i < 4; i++)
         {
             crcread[i] = (byte)rawStream.ReadByte();
         }
     }
     if (!leaveOpen)
     {
         rawStream.Dispose();
     }
 }
        void HandleLevelFinalise()
        {
            game.SetNewScreen(null);
            game.activeScreen = prevScreen;
            if (prevScreen != null)
            {
                game.CursorVisible = prevCursorVisible;
            }
            prevScreen = null;

            int mapWidth  = reader.ReadInt16();
            int mapHeight = reader.ReadInt16();
            int mapLength = reader.ReadInt16();

            double loadingMs = (DateTime.UtcNow - receiveStart).TotalMilliseconds;

            Utils.LogDebug("map loading took:" + loadingMs);
            game.Map.SetData(map, mapWidth, mapHeight, mapLength);
            game.MapEvents.RaiseOnNewMapLoaded();

            map = null;
            gzipStream.Dispose();
            if (sendWomId && !sentWomId)
            {
                SendChat("/womid WoMClient-2.0.7", false);
                sentWomId = true;
            }
            gzipStream = null;
            ServerName = null;
            ServerMotd = null;
            GC.Collect();
        }
Ejemplo n.º 10
0
 protected override void Dispose(bool disposing)
 {
     if (!initdone)
     {
         doInit();
     }
     if (!closed)
     {
         closed = true;
         if (deflateStream != null)
         {
             deflateStream.Dispose();
         }
         else
         {
             rawStream.WriteByte(3);
             rawStream.WriteByte(0);
         }
         uint value = adler32.GetValue();
         rawStream.WriteByte((byte)((value >> 24) & 0xFF));
         rawStream.WriteByte((byte)((value >> 16) & 0xFF));
         rawStream.WriteByte((byte)((value >> 8) & 0xFF));
         rawStream.WriteByte((byte)(value & 0xFF));
         if (!leaveOpen)
         {
             rawStream.Dispose();
         }
     }
 }
Ejemplo n.º 11
0
 protected override void Dispose(bool disposing)
 {
     if (!m_disposed)
     {
         try
         {
             if (disposing)
             {
                 var output = m_stream.BaseStream;
                 m_stream.Dispose();
                 if (m_writing)
                 {
                     WriteCheckSum(output);
                     m_adler.Dispose();
                 }
                 if (m_should_dispose_base)
                 {
                     output.Dispose();
                 }
             }
             m_disposed = true;
         }
         finally
         {
             base.Dispose(disposing);
         }
     }
 }
Ejemplo n.º 12
0
 protected override void Dispose(bool disposing)
 {
     if (isDisposed)
     {
         return;
     }
     if (disposing)
     {
         if (deflateStream != null)
         {
             deflateStream.Dispose();
             deflateStream = null;
         }
         else
         {
             rawStream.WriteByte(3);
             rawStream.WriteByte(0);
         }
         uint crc = (uint)adler32.Value;
         rawStream.WriteByte((byte)((crc >> 24) & 0xFF));
         rawStream.WriteByte((byte)((crc >> 16) & 0xFF));
         rawStream.WriteByte((byte)((crc >> 8) & 0xFF));
         rawStream.WriteByte((byte)((crc) & 0xFF));
     }
     base.Dispose(disposing);
     isDisposed = true;
 }
Ejemplo n.º 13
0
        void HandleLevelFinalise()
        {
            net.task.Interval = 1.0 / 20;
            game.Gui.SetNewScreen(null);
            game.Gui.activeScreen = prevScreen;
            if (prevScreen != null && prevCursorVisible != game.CursorVisible)
            {
                game.CursorVisible = prevCursorVisible;
            }
            prevScreen = null;

            int mapWidth  = reader.ReadUInt16();
            int mapHeight = reader.ReadUInt16();
            int mapLength = reader.ReadUInt16();

            double loadingMs = (DateTime.UtcNow - mapReceiveStart).TotalMilliseconds;

            Utils.LogDebug("map loading took: " + loadingMs);

                        #if USE16_BIT
            game.World.SetNewMap(Utils.UInt8sToUInt16s(map), mapWidth, mapHeight, mapLength);
                        #else
            game.World.SetNewMap(map, mapWidth, mapHeight, mapLength);
                        #endif
            game.WorldEvents.RaiseOnNewMapLoaded();

            map = null;
            gzipStream.Dispose();
            net.wom.CheckSendWomID();
            gzipStream = null;
            GC.Collect();
        }
Ejemplo n.º 14
0
 protected override void Dispose(bool disposing)
 {
     if (isDisposed)
     {
         return;
     }
     if (disposing)
     {
         if (deflateStream != null)
         {
             deflateStream.Dispose();
             deflateStream = null;
             if (crcread == null)
             {
                 crcread = new byte[4];
                 for (int i = 0; i < 4; i++)
                 {
                     crcread[i] = (byte)rawStream.ReadByte();
                 }
             }
         }
     }
     base.Dispose(disposing);
     isDisposed = true;
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Decompresses the data.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns>
        /// The <see cref="T:byte[]"/>.
        /// </returns>
        private byte[] Decompress(byte[] data)
        {
            if (data == null || data.Length == 0)
            {
                return(null);
            }

            DeflateStream deflateStream = null;

            try
            {
                MemoryStream input = new MemoryStream(data);
                using (MemoryStream output = new MemoryStream())
                {
                    deflateStream = new DeflateStream(input, CompressionMode.Decompress);
                    deflateStream.CopyTo(output);
                    byte[] result = output.ToArray();
                    return(result);
                }
            }
            finally
            {
                deflateStream?.Dispose();
            }
        }
Ejemplo n.º 16
0
        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            Stream compressedStream = null;

            switch (_encondingType)
            {
            case "gzip":
                compressedStream = new GZipStream(stream, CompressionMode.Compress, true);
                break;

            case "deflate":
                compressedStream = new DeflateStream(stream, CompressionMode.Compress, true);
                break;

            default:
                break;
            }

            return(_originalContent.CopyToAsync(compressedStream).ContinueWith(tsk =>
            {
                if (compressedStream != null)
                {
                    compressedStream.Dispose();
                }
            }));
        }
 /// <summary>
 /// Closes and disposes of any open streams.
 /// </summary>
 internal void Close()
 {
     _deflateCompressStream?.Dispose();
     _deflateDecompressStream?.Dispose();
     _multipleMessagesStream?.Dispose();
     _zstdDecompressStream?.Dispose();
 }
Ejemplo n.º 18
0
        public void DeflateStreamVsNoCompression()
        {
            byte[] bytesToCompress = Encoding.Default.GetBytes(Text.LoremIpsum);
            Console.WriteLine("Enum.ToObject vs DynamicMethod");
            MemoryStream  targetStream  = new MemoryStream();
            DeflateStream deflateStream = new DeflateStream(targetStream, CompressionMode.Compress, true);
            int           iterations    = 1000;
            Stopwatch     stopwatch     = new Stopwatch();

            stopwatch.Start();
            for (int i = 0; i < iterations; i++)
            {
                deflateStream.Write(bytesToCompress, 0, bytesToCompress.Length);
                targetStream.WriteByte(0);
            }

            stopwatch.Stop();
            deflateStream.Close();
            deflateStream.Dispose();
            long compressDuration = stopwatch.ElapsedMilliseconds;

            stopwatch.Reset();
            stopwatch.Start();
            for (int i = 0; i < iterations; i++)
            {
                targetStream.Write(bytesToCompress, 0, bytesToCompress.Length);
            }
            stopwatch.Stop();
            long noCompressDuration = stopwatch.ElapsedMilliseconds;

            Console.WriteLine("Using compression: {0}", compressDuration);
            Console.WriteLine("Using no compression: {0}", noCompressDuration);
            Console.WriteLine("Performance gain: {0:0.00}%", this.CalculatePerformanceGain(compressDuration, compressDuration));
        }
Ejemplo n.º 19
0
        /// <summary> </summary>
        public static byte[] Decompress(byte[] datas, int len)
        {
            MemoryStream  stream   = new MemoryStream(datas);
            DeflateStream zlib     = new DeflateStream(stream, CompressionMode.Decompress);
            int           unk_byte = stream.ReadByte();
            int           zCMF     = stream.ReadByte();
            int           zFLG     = stream.ReadByte();

            if ((zCMF & 0xF) != Z_DEFLATE)
            {
                throw new InvalidDataException("Not 'Deflate' method.");
            }

            if (zCMF != 0x78)
            {
                throw new InvalidDataException("Invalid CMF.");
            }

            if ((zFLG & 0x20) != 0)
            {
                throw new InvalidDataException("FLG 'Directory preset' is true.");
            }

            byte[] rtn = new byte[len];
            zlib.Read(rtn, 0, len);

            zlib.Dispose();
            stream.Dispose();
            return(rtn);
        }
Ejemplo n.º 20
0
 public override void Dispose()
 {
     if (!IsCreating)
     {
         base.Dispose();
     }
     else
     {
         if (_chOffset > 0)
         {
             ChunkDone();
         }
         DeflateStream.Dispose();
         _temp.Dispose();
         ExtraField.Finish();
         FileStream.Seek(0, SeekOrigin.End);
         WriteNameComment();
         using (FileStream temp = File.OpenRead(_tempName))
         {
             temp.CopyTo(FileStream);
         }
         WriteFooter();
         FileStream.Dispose();
         File.Delete(_tempName);
     }
 }
Ejemplo n.º 21
0
 protected override void Dispose(bool disposing)
 {
     if (!initdone)
     {
         doInit();
     }
     if (closed)
     {
         return;
     }
     closed = true;
     if (deflateStream != null)
     {
         deflateStream.Dispose();
     }
     if (crcread == null)
     {
         crcread = new byte[4];
         for (int i = 0; i < 4; i++)
         {
             crcread[i] = (byte)rawStream.ReadByte();
         }
     }
     if (!leaveOpen)
     {
         rawStream.Dispose();
     }
 }
Ejemplo n.º 22
0
        protected override void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            if (!initdone)
            {
                doInit();           // can happen if never called write
            }
            if (closed)
            {
                return;
            }
            closed = true;
            if (deflateStream != null)
            {
                deflateStream.Dispose();
            }
            if (crcread == null)
            { // eat trailing 4 bytes
                crcread = new byte[4];
                for (int i = 0; i < 4; i++)
                {
                    crcread[i] = (byte)rawStream.ReadByte();
                }
            }
            if (!leaveOpen)
            {
                rawStream.Dispose();
            }

            base.Dispose(disposing);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Compresses the input stream to the output stream.
        /// </summary>
        /// <param name="inputStream">The input stream to compress.</param>
        /// <param name="inputStream">The output stream to write to.</param>
        /// <param name="compressionType">Type of the compression.</param>
        /// <returns></returns>
        public void Compress(Stream inputStream, Stream outputStream, CompressionType compressionType)
        {
            long   intialPosition    = inputStream.Position;
            Stream compressionStream = null;

            try
            {
                switch (compressionType)
                {
                case CompressionType.Gzip:
                    compressionStream = new GZipStream(outputStream, CompressionMode.Compress, leaveOpen: true);
                    break;

                case CompressionType.Deflate:
                    compressionStream = new DeflateStream(outputStream, CompressionMode.Compress, leaveOpen: true);
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(compressionType), compressionType, null);
                }
                inputStream.CopyTo(compressionStream);
            }
            finally
            {
                compressionStream?.Dispose();
                inputStream.Position = intialPosition;
            }
        }
Ejemplo n.º 24
0
        public virtual void Close()
        {
            if (!initdone)
            {
                doInit();            // can happen if never called write
            }
            if (closed)
            {
                return;
            }
            closed = true;
            // sigh ... no only must I close the parent stream to force a flush, but I must save a reference
            // raw stream because (apparently) Close() sets it to null (shame on you, MS developers)
            if (deflateStream != null)
            {
                deflateStream.Dispose();
            }
            else             // second hack: empty input?
            {
                rawStream.WriteByte(3);
                rawStream.WriteByte(0);
            }
            // add crc
            uint crcv = adler32.GetValue();

            rawStream.WriteByte((byte)((crcv >> 24) & 0xFF));
            rawStream.WriteByte((byte)((crcv >> 16) & 0xFF));
            rawStream.WriteByte((byte)((crcv >> 8) & 0xFF));
            rawStream.WriteByte((byte)((crcv) & 0xFF));
            if (!leaveOpen)
            {
                rawStream.Dispose();
            }
        }
Ejemplo n.º 25
0
        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 inflater = new DeflateStream(stream, CompressionMode.Decompress);

                while (index < uncompressedSize &&
                       (read = inflater.Read(data, index, data.Length - index)) > 0)
                {
                    index += read;
                }

                inflater.Dispose();
                return(data);
            }
            else
            {
                Utils.LogDebug("Unsupported .zip entry compression method: " + compressionMethod);
                reader.ReadBytes(compressedSize);
                return(null);
            }
        }
Ejemplo n.º 26
0
 internal void Read()
 {
     try
     {
         using (FileStream fileStream = File.OpenRead(this.Name))
         {
             using (DeflateStream deflateStream = new DeflateStream(fileStream, CompressionMode.Decompress))
             {
                 using (BinaryReader binaryReader = new BinaryReader(deflateStream))
                 {
                     int num = (int)binaryReader.ReadByte();
                     for (int i = 0; i < num; i++)
                     {
                         this.AddFile(binaryReader.ReadString(), binaryReader.ReadBytes(binaryReader.ReadInt32()));
                     }
                 }
                 deflateStream.Dispose();
             }
         }
     }
     catch
     {
         this.InvalidFile = true;
     }
 }
Ejemplo n.º 27
0
        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            Stream compressedStream;

            switch (_compressionMethod)
            {
            case CompressionMethod.GZip:
                compressedStream = new GZipStream(stream, CompressionMode.Compress, true);
                break;

            case CompressionMethod.Deflate:
                compressedStream = new DeflateStream(stream, CompressionMode.Compress, true);
                break;

            case CompressionMethod.None:
            default:
                throw new ArgumentOutOfRangeException();
            }

            return(_originalContent.CopyToAsync(compressedStream, context)
                   .ContinueWith(_ => compressedStream?.Dispose(),
                                 CancellationToken.None,
                                 TaskContinuationOptions.ExecuteSynchronously,
                                 TaskScheduler.Default));
        }
Ejemplo n.º 28
0
        public override void NetSend(BinaryWriter trueWriter, bool lightSend)
        {
            /* Recreate a BinaryWriter writer */
            MemoryStream   buffer       = new MemoryStream(65536);
            DeflateStream  compressor   = new DeflateStream(buffer, CompressionMode.Compress, true);
            BufferedStream writerBuffer = new BufferedStream(compressor, 65536);
            BinaryWriter   writer       = new BinaryWriter(writerBuffer);

            /* Original code */
            base.NetSend(writer, lightSend);
            if (netQueue.Count > Capacity / 2 || !lightSend)
            {
                netQueue.Clear();
                netQueue.Enqueue(UnitOperation.FullSync.Create());
            }
            writer.Write((ushort)netQueue.Count);
            while (netQueue.Count > 0)
            {
                netQueue.Dequeue().Send(writer, this);
            }

            /* Forces data to be flushed into the compressed buffer */
            writerBuffer.Flush(); compressor.Close();

            /* Sends the buffer through the network */
            trueWriter.Write((ushort)buffer.Length);
            trueWriter.Write(buffer.ToArray());

            /* Dispose all objects */
            writer.Dispose(); writerBuffer.Dispose(); compressor.Dispose(); buffer.Dispose();
        }
Ejemplo n.º 29
0
 public void Dispose()
 {
     ZipStream.Flush();
     ZipStream.Close();
     ZipStream.Dispose();
     FileStream.Dispose();
 }
Ejemplo n.º 30
0
        private MemoryStream CompressCache()
        {
            // small arrays almost never yeild a benefit from compressing
            if (cache.Length < 50)
            {
                return(null);
            }

            byte[] cacheBytes = cache.GetBuffer();

            MemoryStream compressedBuffer = new MemoryStream();

            compressedBuffer.WriteByte(0x78);
            compressedBuffer.WriteByte(0x9c);
            var outCompStream = new DeflateStream(compressedBuffer, CompressionMode.Compress, true);

            outCompStream.Write(cacheBytes, 0, (int)cache.Length);
            outCompStream.Dispose();
            int adler = IPAddress.HostToNetworkOrder(Adler32(cacheBytes, 0, (int)cache.Length));

            compressedBuffer.Write(BitConverter.GetBytes(adler), 0, sizeof(uint));

            // if the compression hasn't helped, then just return null
            if (compressedBuffer.Length >= cache.Length)
            {
                return(null);
            }
            return(compressedBuffer);
        }
Ejemplo n.º 31
0
        public void CompressCanWrite()
        {
            var ms = new MemoryStream();
            var zip = new DeflateStream(ms, CompressionMode.Compress);
            Assert.True(zip.CanWrite);

            zip.Dispose();
            Assert.False(zip.CanWrite);
        }
Ejemplo n.º 32
0
        public void DecompressCanRead()
        {
            var ms = new MemoryStream();
            var zip = new DeflateStream(ms, CompressionMode.Decompress);

            Assert.True(zip.CanRead);

            zip.Dispose();
            Assert.False(zip.CanRead);
        }
Ejemplo n.º 33
0
        public 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 writable as expected

            baseStream.Position = 0;
            await baseStream.ReadAsync(bytes, 0, size);
        }
Ejemplo n.º 34
0
        public 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
        }
Ejemplo n.º 35
0
 public void CopyToAsyncArgumentValidation()
 {
     using (DeflateStream ds = new DeflateStream(new MemoryStream(), CompressionMode.Decompress))
     {
         Assert.Throws<ArgumentNullException>("destination", () => { ds.CopyToAsync(null); });
         Assert.Throws<ArgumentOutOfRangeException>("bufferSize", () => { ds.CopyToAsync(new MemoryStream(), 0); });
         Assert.Throws<NotSupportedException>(() => { ds.CopyToAsync(new MemoryStream(new byte[1], writable: false)); });
         ds.Dispose();
         Assert.Throws<ObjectDisposedException>(() => { ds.CopyToAsync(new MemoryStream()); });
     }
     using (DeflateStream ds = new DeflateStream(new MemoryStream(), CompressionMode.Compress))
     {
         Assert.Throws<NotSupportedException>(() => { ds.CopyToAsync(new MemoryStream()); });
     }
 }
Ejemplo n.º 36
0
        public async Task FlushAsyncFailsAfterDispose()
        {
            var ms = new MemoryStream();
            var ds = new DeflateStream(ms, CompressionMode.Compress);
            ds.Dispose();

            await Assert.ThrowsAsync<ObjectDisposedException>(async () =>
            {
                await ds.FlushAsync();
            });
        }
Ejemplo n.º 37
0
 public void FlushFailsAfterDispose()
 {
     var ms = new MemoryStream();
     var ds = new DeflateStream(ms, CompressionMode.Compress);
     ds.Dispose();
     Assert.Throws<ObjectDisposedException>(() => { ds.Flush(); });
 }
Ejemplo n.º 38
0
 public void FlushThenDispose()
 {
     var ms = new MemoryStream();
     var ds = new DeflateStream(ms, CompressionMode.Compress);
     ds.Flush();
     ds.Dispose();
 }
Ejemplo n.º 39
0
 public void DoubleDispose()
 {
     var ms = new MemoryStream();
     var ds = new DeflateStream(ms, CompressionMode.Compress);
     ds.Dispose();
     ds.Dispose();
 }
Ejemplo n.º 40
0
 public async Task DecompressFailsWithRealGzStream()
 {
     string[] files = { gzTestFile("GZTestDocument.doc.gz"), gzTestFile("GZTestDocument.txt.gz") };
     foreach (string fileName in files)
     {
         var baseStream = await LocalMemoryStream.readAppFileAsync(fileName);
         var zip = new DeflateStream(baseStream, CompressionMode.Decompress);
         int _bufferSize = 2048;
         var bytes = new byte[_bufferSize];
         Assert.Throws<InvalidDataException>(() => { zip.Read(bytes, 0, _bufferSize); });
         zip.Dispose();
     }
 }
Ejemplo n.º 41
0
    public override void FromXML(XmlNode node)
    {
        if (node != null && node.Name == "layer")
        {
            XmlAttributeCollection attrs = node.Attributes;
            m_name = attrs["name"].Value;
            m_layerDimensions.first = Convert.ToInt32(attrs["width"].Value);
            m_layerDimensions.second = Convert.ToInt32(attrs["height"].Value);
            foreach(XmlNode child in node.ChildNodes)
            {
                if (child.Name == "properties")
                {
                    foreach (XmlNode propertyNode in child)
                    {
                        if (propertyNode.Name != "property")
                            continue;
                        XmlAttributeCollection propertyAtts = propertyNode.Attributes;
                        m_properties[propertyAtts["name"].Value] = propertyAtts["value"].Value;
                    }
                }
                else if (child.Name == "data")
                {
                    m_data = new TileData();
                    attrs = child.Attributes;
                    if (attrs["encoding"]!= null)
                    {
                        string[] encodings = { "", "csv", "base64" };
                        string encodingValue = attrs["encoding"].Value;
                        int encodingIdx = Array.IndexOf(encodings, encodingValue);
                        if (encodingIdx >= 0)
                        {
                            m_data.m_encoding = (TileEncodingType)encodingIdx;
                        }

                        string[] compressions = { "", "gzip", "zlib" };
                        string compression = attrs["compression"].Value;
                        int compressionIdx = Array.IndexOf(compressions, compression);
                        if (compressionIdx >= 0)
                        {
                            m_data.m_compression = (TileCompressionType)compressionIdx;
                        }

                        switch(m_data.m_encoding)
                        {
                            case TileEncodingType.kCSV:
                                {
                                    string text = child.InnerText;
                                    string[] values = text.Split(',');
                                    foreach (string v in values)
                                    {
                                        uint value = Convert.ToUInt32(v);
                                        TileInfo info = new TileInfo();
                                        info.m_horizontalFlip = (value & FLIPPED_HORIZONTALLY_FLAG) != 0;
                                        info.m_verticalFlip = (value & FLIPPED_VERTICALLY_FLAG) != 0;
                                        info.m_diagonalFlip = (value & FLIPPED_DIAGONALLY_FLAG) != 0;
                                        value = value & ~(FLIPPED_DIAGONALLY_FLAG | FLIPPED_HORIZONTALLY_FLAG | FLIPPED_VERTICALLY_FLAG);
                                        info.m_gid = value;
                                        m_data.m_tiles.Add(info);
                                    }
                                    break;
                                }
                            case TileEncodingType.kBase64:
                                {
                                    byte[] bytes = null;
                                    switch(m_data.m_compression)
                                    {
                                        case TileCompressionType.kNone:
                                            {
                                                bytes = Convert.FromBase64String(child.InnerText);
                                                break;
                                            }
                                        case TileCompressionType.kGzip:
                                            {
                                                //Transform string into byte[]
                                                string str = child.InnerText;
                                                byte[] byteArray = new byte[str.Length];
                                                int indexBA = 0;
                                                foreach (char item in str.ToCharArray())
                                                {
                                                    byteArray[indexBA++] = (byte)item;
                                                }

                                                MemoryStream ms = new MemoryStream(byteArray);
                                                GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress);

                                                byteArray = new byte[byteArray.Length];
                                                int rBytes = gzip.Read(byteArray, 0, byteArray.Length);

                                                StringBuilder sb = new StringBuilder(rBytes);
                                                for (int i = 0; i < rBytes; ++i)
                                                {
                                                    sb.Append((char)byteArray[i]);
                                                }

                                                gzip.Close();
                                                ms.Close();
                                                gzip.Dispose();
                                                ms.Dispose();

                                                bytes = Convert.FromBase64String(sb.ToString());
                                                break;
                                            }
                                        case TileCompressionType.kZlib:
                                            {
                                                //Transform string into byte[]
                                                string str = child.InnerText;
                                                byte[] byteArray = new byte[str.Length];
                                                int indexBA = 0;
                                                foreach (char item in str.ToCharArray())
                                                {
                                                    byteArray[indexBA++] = (byte)item;
                                                }

                                                MemoryStream ms = new MemoryStream(byteArray);
                                                DeflateStream zlib = new DeflateStream(ms, CompressionMode.Decompress);

                                                byteArray = new byte[byteArray.Length];
                                                int rBytes = zlib.Read(byteArray, 0, byteArray.Length);

                                                StringBuilder sb = new StringBuilder(rBytes);
                                                for (int i = 0; i < rBytes; ++i)
                                                {
                                                    sb.Append((char)byteArray[i]);
                                                }

                                                zlib.Close();
                                                ms.Close();
                                                zlib.Dispose();
                                                ms.Dispose();

                                                bytes = Convert.FromBase64String(sb.ToString());
                                                break;
                                            }
                                    }
                                    for (int i = 0; i < bytes.Length; i += 4)
                                    {
                                        uint value = (uint)bytes[i] | ((uint)bytes[i + 1] << 8) | ((uint)bytes[i + 2] << 16) | ((uint)bytes[i + 3] << 24);
                                        TileInfo info = new TileInfo();
                                        info.m_horizontalFlip = (value & FLIPPED_HORIZONTALLY_FLAG) != 0;
                                        info.m_verticalFlip = (value & FLIPPED_VERTICALLY_FLAG) != 0;
                                        info.m_diagonalFlip = (value & FLIPPED_DIAGONALLY_FLAG) != 0;
                                        value = value & ~(FLIPPED_DIAGONALLY_FLAG | FLIPPED_HORIZONTALLY_FLAG | FLIPPED_VERTICALLY_FLAG);
                                        info.m_gid = value;
                                        m_data.m_tiles.Add(info);
                                    }
                                    break;
                                }
                            default:
                                {
                                    break;
                                }
                        }
                    }
                    else
                    {
                        m_data.m_encoding = TileEncodingType.kNone;
                        m_data.m_compression = TileCompressionType.kNone;

                        m_data.m_tiles.Clear();
                        foreach(XmlNode tileNode in child.ChildNodes)
                        {
                            if (tileNode.Name != "tile")
                            {
                                continue;
                            }
                            TileInfo info = new TileInfo();
                            uint value = Convert.ToUInt32(tileNode.Attributes["gid"].Value);

                            info.m_horizontalFlip = (value & FLIPPED_HORIZONTALLY_FLAG) != 0;
                            info.m_verticalFlip = (value & FLIPPED_VERTICALLY_FLAG) != 0;
                            info.m_diagonalFlip = (value & FLIPPED_DIAGONALLY_FLAG) != 0;
                            value = value & ~(FLIPPED_DIAGONALLY_FLAG | FLIPPED_HORIZONTALLY_FLAG |FLIPPED_VERTICALLY_FLAG);
                            info.m_gid = value;
                            m_data.m_tiles.Add(info);
                        }
                    }
                }
            }
        }
    }