public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer", Resources.BufferCannotBeNull); } if (offset < 0 || offset >= buffer.Length) { throw new ArgumentOutOfRangeException("offset", Resources.OffsetMustBeValid); } if ((offset + count) > buffer.Length) { throw new ArgumentException(Resources.BufferNotLargeEnough, "buffer"); } if (inPos == maxInPos) { PrepareNextPacket(); } int countToRead = Math.Min(count, maxInPos - inPos); int countRead = 0; if (zInStream != null) { countRead = zInStream.read(buffer, offset, countToRead); } else { countRead = baseStream.Read(buffer, offset, countToRead); } inPos += countRead; return(countRead); }
public static void Uncompress(Stream input, Stream output, int uncompressedSize, byte[] buff, CancellationToken cancelationToken, Action <long> uncompressed = null) { Exceptions.CheckArgumentNull(input, "input"); Exceptions.CheckArgumentNull(output, "output"); Exceptions.CheckArgumentOutOfRangeException(uncompressedSize, "uncompressedSize", 0, int.MaxValue); ZInputStream reader = new ZInputStream(input); int readed; while (uncompressedSize > 0 && (readed = reader.read(buff, 0, Math.Min(buff.Length, uncompressedSize))) > 0) { if (cancelationToken.IsCancellationRequested) { return; } uncompressedSize -= readed; output.Write(buff, 0, readed); uncompressed.NullSafeInvoke(readed); } if (uncompressedSize != 0) { throw new Exception("Неожиданный конец потока."); } }
public static byte[] LoadDLL(Stream stream) { if (stream == null) { return(null); } byte[] lenBytes = new byte[4]; stream.Read(lenBytes, 0, 4); int len = System.Net.IPAddress.NetworkToHostOrder((int)BitConverter.ToUInt32(lenBytes, 0)); stream.Read(lenBytes, 0, 4); int decryLen = System.Net.IPAddress.NetworkToHostOrder((int)BitConverter.ToUInt32(lenBytes, 0)); var trans = m_netCrypte.GetCryptoTransform(); byte[] srcBytes = new byte[len]; byte[] dbytes = new byte[len]; stream.Read(srcBytes, 0, (int)stream.Length - 8); trans.TransformBlock(srcBytes, 0, (int)stream.Length - 8, dbytes, 0); MemoryStream ms = new MemoryStream(dbytes, 0, decryLen, false); var zos = new ZInputStream(ms); MemoryStream output = new MemoryStream(srcBytes, true); int tlen = 0; while ((tlen = zos.read(m_tempBuffer, 0, m_tempBuffer.Length)) > 0) { output.Write(m_tempBuffer, 0, tlen); } ; zos.Close(); return(srcBytes); }
public static byte[] UnZlib(byte[] bytes) { try { MemoryStream ms = new MemoryStream(bytes); ZInputStream zs = new ZInputStream(ms); MemoryStream mz = new MemoryStream(); byte[] buffer = new byte[BUFFER_SIZE]; int read; do { read = zs.read(buffer, 0, BUFFER_SIZE); if (read > 0) { mz.Write(buffer, 0, read); } }while (read > 0); ms.Close(); zs.Close(); byte[] retVal = mz.ToArray(); mz.Close(); return(retVal); } catch { return(null); } }
public static byte[] ZLibDecompress(byte[] CompData, int Offset, int DecompLength) { byte[] buffer = new byte[CompData.Length - Offset]; Array.Copy((Array)CompData, Offset, (Array)buffer, 0, buffer.Length); ZInputStream zinputStream = new ZInputStream((Stream) new MemoryStream(buffer)); byte[] b = new byte[DecompLength]; zinputStream.read(b, 0, DecompLength); zinputStream.Close(); return(b); }
private static byte[] Decompress(byte[] input, int ilen = 0) { MemoryStream ms = new MemoryStream(input, 0, ilen == 0 ? input.Length : ilen, false); var zos = new ZInputStream(ms); MemoryStream output = new MemoryStream(input.Length * 5); int len = 0; while ((len = zos.read(m_tempBuffer, 0, m_tempBuffer.Length)) > 0) { output.Write(m_tempBuffer, 0, len); } ; zos.Close(); return(output.ToArray()); }
public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer", Resources.BufferCannotBeNull); } if (offset < 0 || offset >= buffer.Length) { throw new ArgumentOutOfRangeException("offset", Resources.OffsetMustBeValid); } if ((offset + count) > buffer.Length) { throw new ArgumentException(Resources.BufferNotLargeEnough, "buffer"); } if (inPos == maxInPos) { PrepareNextPacket(); } int countToRead = Math.Min(count, maxInPos - inPos); int countRead; if (zInStream != null) { countRead = zInStream.read(buffer, offset, countToRead); } else { countRead = baseStream.Read(buffer, offset, countToRead); } inPos += countRead; // release the weak reference if (inPos == maxInPos) { zInStream = null; if (!Platform.IsMono()) { inBufferRef = new WeakReference(inBuffer, false); inBuffer = null; } } return(countRead); }
/// <summary> /// Unpacks zipped data. /// </summary> /// <param name="str">In Stream.</param> /// <param name="outStream">Out stream.</param> /// <param name = "plainLen">Data size after decompress.</param> /// <param name = "rewind">Manual control for stream seek position.</param> public static void Unzip(Stream str, Stream outStream, bool rewind = true) { int len; var buffer = new byte[65536]; var zOutputStream = new ZInputStream(str); while ((len = zOutputStream.read(buffer, 0, buffer.Length)) > 0) { outStream.Write(buffer, 0, len); } zOutputStream.Close(); buffer = null; if (rewind) { outStream.Position = 0; outStream.Flush(); } }
public static byte[] Decompress(byte[] input) { MemoryStream ms = new MemoryStream(input); var zos = new ZInputStream(ms); MemoryStream output = new MemoryStream(); byte[] temp = new byte[4096]; int len = 0; while ((len = zos.read(temp, 0, temp.Length)) > 0) { output.Write(temp, 0, len); } ; zos.Close(); return(output.ToArray()); }
public static byte[] Decompress(byte[] compressed, int decompressedSize, byte compressionFlags, bool chunked = false) { switch ((CompressionMethod)(compressionFlags & 0x0F)) { case CompressionMethod.None: return(compressed); case CompressionMethod.Zlib: { using (var compressedStream = new MemoryStream(compressed)) using (var decompressedStream = new MemoryStream()) using (var stream = new ZInputStream(compressedStream)) { byte[] buf = new byte[0x10000]; int length = 0; while ((length = stream.read(buf, 0, buf.Length)) > 0) { decompressedStream.Write(buf, 0, length); } return(decompressedStream.ToArray()); } } case CompressionMethod.LZ4: if (chunked) { var decompressed = Native.LZ4FrameCompressor.Decompress(compressed); return(decompressed); } else { var decompressed = new byte[decompressedSize]; LZ4Codec.Decode(compressed, 0, compressed.Length, decompressed, 0, decompressedSize, true); return(decompressed); } default: { var msg = String.Format("No decompressor found for this format: {0}", compressionFlags); throw new InvalidDataException(msg); } } }
public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer", System.Data.MySqlClient.Properties.Resources.BufferCannotBeNull); } if (offset < 0 || offset >= buffer.Length) { throw new ArgumentOutOfRangeException("offset", System.Data.MySqlClient.Properties.Resources.OffsetMustBeValid); } if ((offset + count) > buffer.Length) { throw new ArgumentException(System.Data.MySqlClient.Properties.Resources.BufferNotLargeEnough, "buffer"); } if (inPos == maxInPos) { PrepareNextPacket(); } int countToRead = Math.Min(count, maxInPos - inPos); int countRead; if (zInStream != null) { countRead = zInStream.read(buffer, offset, countToRead); } else { countRead = baseStream.Read(buffer, offset, countToRead); } inPos += countRead; // release the weak reference if (inPos == maxInPos) { zInStream = null; inBufferRef.Target = inBuffer; inBuffer = null; } return(countRead); }
private byte[] DecompressBytes(ARZFile arzFile) { // Read in the compressed data and decompress it, storing the results in a memorystream FileStream arzStream = new FileStream(arzFile.m_filename, FileMode.Open, FileAccess.Read, FileShare.Read); try { arzStream.Seek(m_offset, SeekOrigin.Begin); // Create a decompression stream ZInputStream zinput = new ZInputStream(arzStream); // Create a memorystream to hold the decompressed data MemoryStream outStream = new MemoryStream(); try { // Now decompress byte[] buffer = new byte[1024]; int len; while ((len = zinput.read(buffer, 0, 1024)) > 0) { outStream.Write(buffer, 0, len); } // Now create a final Byte array to hold the answer byte[] ans = new byte[(int)zinput.TotalOut]; // Copy the data into it Array.Copy(outStream.GetBuffer(), ans, (int)zinput.TotalOut); // Return the decompressed data return(ans); } finally { outStream.Close(); } } finally { arzStream.Close(); } }
public byte[] DecompressPacket(byte[] Payload, int Offset) { MemoryStream ms = new MemoryStream(Payload.GetUpperBound(0) - Offset); ms.Write(Payload, Offset, Payload.GetUpperBound(0) - Offset); ms.Seek(0, System.IO.SeekOrigin.Begin); ZInputStream zs = new ZInputStream(ms); int UncompressedSize; byte[] Uncompressed = new byte[4096]; try { UncompressedSize = zs.read(Uncompressed, 0, 4096); } catch { if (DEBUG) { Debug("DECOMPRESSION FAILURE"); } Array.Copy(Payload, Offset - 1, Uncompressed, 0, Payload.Length - (Offset - 1)); UncompressedSize = Payload.Length - (Offset - 1); } zs.Close(); zs.Dispose(); ms.Close(); ms.Dispose(); Array.Resize(ref Uncompressed, UncompressedSize); return(Uncompressed); }
/// <summary> /// 解压Deflate数据至 /// </summary> /// <param name="A">被解压的流</param> /// <param name="B">要输出的流</param> /// <param name="Length">被解压的数据长度</param> /// <returns>解压的数据长度</returns> public static int DeflateDecodeTo(Stream A, Stream B, int Length = 0) { ZInputStream tDecode = new ZInputStream(A); byte[] tBuffer = new byte[8192]; // 8kb缓冲区 int tLen = 0; int tTotal = 0; while ((tLen = tDecode.read(tBuffer, 0, (Length - tTotal > 8192 ? 8192 : Length - tTotal))) > 0) { tTotal += tLen; B.Write(tBuffer, 0, tLen); } if (Length != 0 && tTotal != Length) { throw new IndexOutOfRangeException(); } return(tTotal); }
/// <summary> /// 解压 /// </summary> /// <param name="param"></param> /// <returns></returns> static public void DecompressByteZipNet(byte[] inBytes, uint startPos, uint inLen, ref byte[] outBytes, ref uint outLen) { MemoryStream outStream = new MemoryStream(); MemoryStream outms = new MemoryStream(); outms.Write(inBytes, (int)startPos, (int)inLen); outms.Position = 0; ZInputStream outzipStream = new ZInputStream(outms); byte[] writeData = new byte[1024]; try { int size = 0; while ((size = outzipStream.read(writeData, 0, writeData.Length)) > 0) { if (size > 0) { outStream.Write(writeData, 0, size); } else { Ctx.m_instance.m_logSys.log("ZipNet Decompress Error"); } } outzipStream.Close(); // 一定要先 Close ZipOutputStream ,然后再获取 ToArray ,如果不关闭, ToArray 将不能返回正确的值 outBytes = outStream.ToArray(); outLen = (uint)outBytes.Length; outStream.Close(); outms.Close(); } catch { Ctx.m_instance.m_logSys.log("DecompressByteZipNet error"); } }
public byte[] Decompress(byte[] compressed, int decompressedSize, byte compressionFlags, bool chunked = false) { switch (compressionFlags & 15) { case 0: return(compressed); case 1: using (MemoryStream memoryStream = new MemoryStream(compressed)) { using (MemoryStream memoryStream2 = new MemoryStream()) { using (ZInputStream zInputStream = new ZInputStream(memoryStream)) { byte[] array = new byte[65536]; int count; while ((count = zInputStream.read(array, 0, array.Length)) > 0) { memoryStream2.Write(array, 0, count); } return(memoryStream2.ToArray()); } } } break; case 2: break; default: throw new InvalidDataException(string.Format("No decompressor found for this format: {0}", compressionFlags)); } if (chunked) { return(LZ4FrameCompressor.Decompress(compressed)); } byte[] array2 = new byte[decompressedSize]; LZ4Codec.Decode(compressed, 0, compressed.Length, array2, 0, decompressedSize, false); return(array2); }
public static void EnsureRead(this ZInputStream self, byte[] buff, int offset, int size) { Exceptions.CheckArgumentNull(self, "self"); int readed; while (size > 0 && (readed = self.read(buff, offset, size)) != 0) { if (readed < 0) { throw new Exception("Неожиданный конец потока."); } size -= readed; offset += readed; } if (size != 0) { throw new Exception("Неожиданный конец потока."); } }
private PListDict decompressPlist(string encodedPList) { var data = Convert.FromBase64String(encodedPList); var z = new ZStream(); MemoryStream oInStream = new MemoryStream(data); MemoryStream oOutStream = new MemoryStream(); var zIn = new ZInputStream(oInStream); byte[] buffer = new byte[2000]; int len; while ((len = zIn.read(buffer, 0, 2000)) > 0) { oOutStream.Write(buffer, 0, len); } oOutStream.Flush(); zIn.Close(); var plist = PListRoot.Load(oOutStream).Root as PListDict; oOutStream.Close(); return(plist); }
// Reads data from an ARC file and puts it into a Byte array (or NULL if not found) public byte[] GetData(string dataID) { if (!m_fileHasBeenRead) { ReadARCToC(); } if (m_dir == null) { return(null); // could not read the file } // First normalize the filename dataID = NormalizeRecordPath(dataID); // Find our file in the toc. // First strip off the leading folder since it is just the ARC name int firstPathDelim = dataID.IndexOf('\\'); if (firstPathDelim != -1) { dataID = dataID.Substring(firstPathDelim + 1); } // Now see if this file is in the toc. ARCDirEntry dirEntry = (ARCDirEntry)m_dir[dataID]; if (dirEntry == null) { return(null); // record not found } // Now open the ARC file and read in the record FileStream arcFile = new FileStream(m_filename, FileMode.Open, FileAccess.Read); try { // Allocate memory for the uncompressed data byte[] ans = new byte[dirEntry.realSize]; // Now process each part of this record int ipos = 0; if ((dirEntry.storageType == 1) && (dirEntry.compressedSize == dirEntry.realSize)) { arcFile.Seek(dirEntry.fileOffset, SeekOrigin.Begin); arcFile.Read(ans, 0, dirEntry.realSize); } else { for (int ipart = 0; ipart < dirEntry.parts.Length; ++ipart) { // seek to the part we want arcFile.Seek(dirEntry.parts[ipart].fileOffset, SeekOrigin.Begin); // Create a decompression stream ZInputStream zinput = new ZInputStream(arcFile); int len; int partLen = 0; while ((len = zinput.read(ans, ipos, ans.Length - ipos)) > 0) { ipos += len; partLen += len; // break out of the read loop if we have processed this part completely. if (partLen >= dirEntry.parts[ipart].realSize) { break; } } } } return(ans); } finally { if (arcFile != null) { arcFile.Close(); } } }
public bool LoadSZX(Stream fs) { for (int f = 0; f < 16; f++) { RAM_BANK[f] = new byte[8192]; } using (BinaryReader r = new BinaryReader(fs)) { int bytesToRead = (int)fs.Length; byte[] buffer = new byte[bytesToRead]; int bytesRead = r.Read(buffer, 0, bytesToRead); if (bytesRead == 0) { return(false); //something bad happened! } GCHandle pinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned); //Read in the szx header to begin proceedings header = (ZXST_Header)Marshal.PtrToStructure(pinnedBuffer.AddrOfPinnedObject(), typeof(ZXST_Header)); if (header.MajorVersion != 1) { pinnedBuffer.Free(); return(false); } string formatName = GetID(header.Magic); int bufferCounter = Marshal.SizeOf(header); while (bufferCounter < bytesRead) { //Read the block info ZXST_Block block = (ZXST_Block)Marshal.PtrToStructure(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, bufferCounter), typeof(ZXST_Block)); bufferCounter += Marshal.SizeOf(block); string blockID = GetID(block.Id); switch (blockID) { case "SPCR": //Read the ZXST_SpecRegs structure specRegs = (ZXST_SpecRegs)Marshal.PtrToStructure(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, bufferCounter), typeof(ZXST_SpecRegs)); break; case "Z80R": //Read the ZXST_SpecRegs structure z80Regs = (ZXST_Z80Regs)Marshal.PtrToStructure(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, bufferCounter), typeof(ZXST_Z80Regs)); break; case "KEYB": //Read the ZXST_SpecRegs structure keyboard = (ZXST_Keyboard)Marshal.PtrToStructure(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, bufferCounter), typeof(ZXST_Keyboard)); break; case "AY\0\0": ayState = (ZXST_AYState)Marshal.PtrToStructure(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, bufferCounter), typeof(ZXST_AYState)); break; case "+3\0\0": plus3Disk = (ZXST_Plus3Disk)Marshal.PtrToStructure(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, bufferCounter), typeof(ZXST_Plus3Disk)); numDrivesPresent = plus3Disk.numDrives; plus3DiskFile = new ZXST_DiskFile[plus3Disk.numDrives]; externalDisk = new String[plus3Disk.numDrives]; InsertDisk = new bool[plus3Disk.numDrives]; break; case "DSK\0": ZXST_DiskFile df = (ZXST_DiskFile)Marshal.PtrToStructure(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, bufferCounter), typeof(ZXST_DiskFile)); plus3DiskFile[df.driveNum] = df; InsertDisk[df.driveNum] = true; int offset2 = bufferCounter + Marshal.SizeOf(df); char[] file = new char[df.uncompressedSize]; Array.Copy(buffer, offset2, file, 0, df.uncompressedSize); //leave out the \0 terminator externalDisk[df.driveNum] = new String(file); break; case "TAPE": tape = (ZXST_Tape)Marshal.PtrToStructure(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, bufferCounter), typeof(ZXST_Tape)); InsertTape = true; //Embedded tape file if ((tape.flags & 1) != 0) { int offset = bufferCounter + Marshal.SizeOf(tape); //Compressed? if ((tape.flags & 2) != 0) { MemoryStream compressedData = new MemoryStream(buffer, offset, tape.compressedSize); MemoryStream uncompressedData = new MemoryStream(); using (ZInputStream zipStream = new ZInputStream(compressedData)) { byte[] tempBuffer = new byte[2048]; int bytesUnzipped = 0; while ((bytesUnzipped = zipStream.read(tempBuffer, 0, 2048)) > 0) { uncompressedData.Write(tempBuffer, 0, bytesUnzipped); } embeddedTapeData = uncompressedData.ToArray(); compressedData.Close(); uncompressedData.Close(); } } else { embeddedTapeData = new byte[tape.compressedSize]; Array.Copy(buffer, offset, embeddedTapeData, 0, tape.compressedSize); } } else //external tape file { int offset = bufferCounter + Marshal.SizeOf(tape); char[] file2 = new char[tape.compressedSize - 1]; Array.Copy(buffer, offset, file2, 0, tape.compressedSize - 1); //leave out the \0 terminator externalTapeFile = new String(file2); } break; case "RAMP": //Read the ZXST_SpecRegs structure ZXST_RAMPage ramPages = (ZXST_RAMPage)Marshal.PtrToStructure(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, bufferCounter), typeof(ZXST_RAMPage)); if (ramPages.wFlags == ZXSTRF_COMPRESSED) { int offset = bufferCounter + Marshal.SizeOf(ramPages); int compressedSize = ((int)block.Size - (Marshal.SizeOf(ramPages)));// - Marshal.SizeOf(block) - 1 )); MemoryStream compressedData = new MemoryStream(buffer, offset, compressedSize); MemoryStream uncompressedData = new MemoryStream(); using (ZInputStream zipStream = new ZInputStream(compressedData)) { byte[] tempBuffer = new byte[2048]; int bytesUnzipped = 0; while ((bytesUnzipped = zipStream.read(tempBuffer, 0, 2048)) > 0) { uncompressedData.Write(tempBuffer, 0, bytesUnzipped); } byte[] pageData = uncompressedData.ToArray(); { Array.Copy(pageData, 0, RAM_BANK[ramPages.chPageNo * 2], 0, 8192); Array.Copy(pageData, 0 + 8192, RAM_BANK[ramPages.chPageNo * 2 + 1], 0, 8192); } compressedData.Close(); uncompressedData.Close(); } } else { int bufferOffset = bufferCounter + Marshal.SizeOf(ramPages); { Array.Copy(buffer, bufferOffset, RAM_BANK[ramPages.chPageNo * 2], 0, 8192); Array.Copy(buffer, bufferOffset + 8192, RAM_BANK[ramPages.chPageNo * 2 + 1], 0, 8192); } } break; case "PLTT": palette = (ZXST_PaletteBlock)Marshal.PtrToStructure(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, bufferCounter), typeof(ZXST_PaletteBlock)); paletteLoaded = true; break; default: //unrecognised block, so skip to next break; } bufferCounter += (int)block.Size; //Move to next block } pinnedBuffer.Free(); return(true); } }
protected override int ReadNextBlock(byte[] buffer, int offset, int count) { // OMG! reader.Read is the base-stream, reader.read is decompressed! yeuch return(reader.read(buffer, offset, count)); }