private static void UE4ChunkUnzip(string source, string destination) { if (!File.Exists(source)) { return; } using (BinaryReader inReader = new BinaryReader(File.Open(source, FileMode.Open))) { using (BinaryWriter binaryWriter = new BinaryWriter(File.Open(destination, FileMode.Create))) { FCompressedChunkInfo fcompressedChunkInfo1 = new FCompressedChunkInfo(); fcompressedChunkInfo1.Serialize(inReader); FCompressedChunkInfo fcompressedChunkInfo2 = new FCompressedChunkInfo(); fcompressedChunkInfo2.Serialize(inReader); long num1 = fcompressedChunkInfo1.CompressedSize; long num2 = fcompressedChunkInfo1.UncompressedSize; if (num2 == 2653586369L) { num2 = 131072L; } long length = (fcompressedChunkInfo2.UncompressedSize + num2 - 1L) / num2; FCompressedChunkInfo[] fcompressedChunkInfoArray = new FCompressedChunkInfo[length]; long val2 = 0L; for (int index = 0; index < length; ++index) { fcompressedChunkInfoArray[index] = new FCompressedChunkInfo(); fcompressedChunkInfoArray[index].Serialize(inReader); val2 = Math.Max(fcompressedChunkInfoArray[index].CompressedSize, val2); } for (long index = 0L; index < length; ++index) { FCompressedChunkInfo fcompressedChunkInfo3 = fcompressedChunkInfoArray[index]; byte[] buffer = ZlibStream.UncompressBuffer(inReader.ReadBytes((int)fcompressedChunkInfo3.CompressedSize)); binaryWriter.Write(buffer); } } } }
public static Firmware ProcessFirmware(string path) { // JavaScriptSerializer serializer = new JavaScriptSerializer(); Console.WriteLine("Read File " + path); // read the file StreamReader f = new StreamReader(File.OpenRead(path)); //fw = serializer.Deserialize<Firmware>(f.ReadToEnd()); fw = JSON.Instance.ToObject <Firmware>(f.ReadToEnd()); f.Close(); byte[] data = Convert.FromBase64String(fw.image); MemoryStream imagems = new MemoryStream(data, true); ZlibStream decompressionStream = new ZlibStream(imagems, CompressionMode.Decompress); int size = fw.image_size + (fw.image_size % 4); fw.imagebyte = new byte[size]; for (int a = 0; a < fw.imagebyte.Length; a++) { fw.imagebyte[a] = 0xff; } try { decompressionStream.Read(fw.imagebyte, 0, fw.image_size); } catch { Console.WriteLine("Possible bad file - usually safe to ignore"); } Console.WriteLine("image_size {0} size {1}", fw.image_size, size); // pad image to 4-byte length //while ((fw.imagebyte.Length % 4) != 0) { //fw.imagebyte. += b'\x00' return(fw); }
// Encryption Routine: Zlib -> AES -> Base64 public static byte[] Encrypt(uint uVer, byte[] pSrc, uint dwBufferFlag, out uint uLen, out uint uLenCompressed, out uint uLenEncoded) { byte[] bits = BitConverter.GetBytes(dwBufferFlag); byte[] pEncrypted; if (bits[0] != 0) { pEncrypted = ZlibStream.CompressBuffer(pSrc); } else { pEncrypted = new byte[pSrc.Length]; Buffer.BlockCopy(pSrc, 0, pEncrypted, 0, pSrc.Length); } uLen = (uint)pSrc.Length; uLenCompressed = (uint)pEncrypted.Length; if (!((bits[3] & 1) != 0)) { byte[] aKey; byte[] aIV; // Get the AES Key/IV for transformation CipherKeys.GetKeyAndIV(uVer, uLenCompressed, out aKey, out aIV); // Perform AES block encryption AESCipher pCipher = new AESCipher(aKey, aIV); pCipher.TransformBlock(pEncrypted, 0, uLen, pEncrypted, 0); // Encode the encrypted data into a base64 encoded string pEncrypted = Encoding.UTF8.GetBytes(Convert.ToBase64String(pEncrypted)); } else { // Perform XOR block encryption pEncrypted = EncryptXOR(uVer, pEncrypted, uLen, uLenCompressed); } uLenEncoded = (uint)pEncrypted.Length; return(pEncrypted); }
public byte[] Decompress(byte[] file, string type) { byte[] align = new byte[4]; Array.Copy(file, 4, align, 0, 4); //used for byte alignment. But it's being fudged by the dll. byte[] compressed = new byte[4]; Array.Copy(file, 8, compressed, 0, 4); byte[] uncompressed = new byte[4]; Array.Copy(file, 12, uncompressed, 0, 4); byte[] input = new byte[BitConverter.ToInt32(compressed, 0)]; Array.Copy(file, 16, input, 0, file.Length - 16); byte[] output = new byte[BitConverter.ToInt32(uncompressed, 0)]; int padding = BitConverter.ToInt32(uncompressed, 0) - BitConverter.ToInt32(compressed, 0); if (type == "BPE ") { yukes_bpe(input, BitConverter.ToInt32(compressed, 0), output, BitConverter.ToInt32(uncompressed, 0), padding); } if (type == "ZLIB") { output = ZlibStream.UncompressBuffer(input); } return(output); }
public static void MapChunkBulk(MinecraftClient client, IPacket _packet) { var packet = (MapChunkBulkPacket)_packet; var data = ZlibStream.UncompressBuffer(packet.ChunkData); var offset = 0; foreach (var metadata in packet.ChunkMetadata) { var chunkLength = (BlockDataLength + (NibbleDataLength * 2) + (packet.LightIncluded ? NibbleDataLength : 0)) * GetSectionCount(metadata.PrimaryBitMap) + NibbleDataLength * GetSectionCount(metadata.AddBitMap) + (Chunk.Width * Chunk.Depth); var chunkData = new byte[chunkLength]; Array.Copy(data, offset, chunkData, 0, chunkLength); AddChunk(client, metadata.ChunkX, metadata.ChunkZ, metadata.PrimaryBitMap, metadata.AddBitMap, packet.LightIncluded, true, chunkData); offset += chunkLength; } }
protected override byte[] OnConstruct() { if (_compressedBitmapData == null) { _compressedBitmapData = ZlibStream.CompressBuffer(_bitmapData); } using (var tag = new FlashWriter(7 + _compressedBitmapData.Length)) { tag.Write(CharacterId); tag.Write(BitmapFormat); tag.Write(BitmapWidth); tag.Write(BitmapHeight); tag.Write(_compressedBitmapData); return(tag.ToArray()); } }
static byte[] DecompressBuffer(byte[] compressed_bytes, System.Action <float> progress_act) { using (var input = new MemoryStream(compressed_bytes)) { using (var decompressor = new ZlibStream(input, CompressionMode.Decompress)) { using (var output = new MemoryStream()) { int n; var buffer = new byte[4 * 1024]; while ((n = decompressor.Read(buffer, 0, buffer.Length)) != 0) { output.Write(buffer, 0, n); if (progress_act != null) { progress_act((float)decompressor.Position / input.Length); } } return(output.ToArray()); } } } }
private static ChunkDataPacket CreatePacket(IChunk chunk) { var X = chunk.Coordinates.X; var Z = chunk.Coordinates.Z; const int blocksPerChunk = Chunk.Width * Chunk.Height * Chunk.Depth; const int bytesPerChunk = (int)(blocksPerChunk * 2.5); byte[] data = new byte[bytesPerChunk]; Buffer.BlockCopy(chunk.Blocks, 0, data, 0, chunk.Blocks.Length); Buffer.BlockCopy(chunk.Metadata.Data, 0, data, chunk.Blocks.Length, chunk.Metadata.Data.Length); Buffer.BlockCopy(chunk.BlockLight.Data, 0, data, chunk.Blocks.Length + chunk.Metadata.Data.Length, chunk.BlockLight.Data.Length); Buffer.BlockCopy(chunk.SkyLight.Data, 0, data, chunk.Blocks.Length + chunk.Metadata.Data.Length + chunk.BlockLight.Data.Length, chunk.SkyLight.Data.Length); var result = ZlibStream.CompressBuffer(data); return(new ChunkDataPacket(X * Chunk.Width, 0, Z * Chunk.Depth, Chunk.Width, Chunk.Height, Chunk.Depth, result)); }
static void Main(string[] args) { var utf8 = new UTF8Encoding(); using (var client = new SubscriberSocket()) { client.Options.ReceiveHighWatermark = 1000; client.Connect("tcp://cedar.canonn.tech:9500"); client.SubscribeToAnyTopic(); while (true) { var bytes = client.ReceiveFrameBytes(); var uncompressed = ZlibStream.UncompressBuffer(bytes); var result = utf8.GetString(uncompressed); Console.WriteLine(result); } } }
public static void AddCompressed(this List <byte> _Packet, string _Value, bool addbool = true) { if (addbool) { _Packet.AddBool(true); } if (_Value == null) { _Packet.AddInt(-1); } else { byte[] Compressed = ZlibStream.CompressString(_Value); _Packet.AddInt(Compressed.Length + 4); _Packet.AddIntEndian(_Value.Length); _Packet.AddRange(Compressed); } }
private static ChunkDataPacket CreatePacket(IChunk chunk) { var X = chunk.Coordinates.X; var Z = chunk.Coordinates.Z; Profiler.Start("client.encode-chunks.compress"); byte[] result; using (var ms = new MemoryStream()) { using (var deflate = new ZlibStream(new MemoryStream(chunk.Data), CompressionMode.Compress, CompressionLevel.BestSpeed)) deflate.CopyTo(ms); result = ms.ToArray(); } Profiler.Done(); return(new ChunkDataPacket(X * Chunk.Width, 0, Z * Chunk.Depth, Chunk.Width, Chunk.Height, Chunk.Depth, result)); }
private void button3_Click(object sender, EventArgs e) { saveFileDialog1.Filter = "All Files (*.*)|*.*"; saveFileDialog1.ShowDialog(); if (saveFileDialog1.FileName != null) { byte[] bytes = System.IO.File.ReadAllBytes(openFileDialog1.FileName); var decompressedBlob = ZlibStream.UncompressBuffer(bytes); try { System.IO.FileStream _FileStream = (System.IO.FileStream)saveFileDialog1.OpenFile(); _FileStream.Write(decompressedBlob, 0, decompressedBlob.Length); _FileStream.Close(); } catch { } } }
private void OutputFile(FileInfo fileInfo, Stream input, Stream output) { input.Position = fileInfo.Offset; switch (fileInfo.Type) { case 2: input.Position += 0x30; using (var deflate = new ZlibStream(input, CompressionMode.Decompress, true)) { deflate.CopyTo(output, fileInfo.UncompressedSize); } break; case 0: input.CopyStream(output, fileInfo.CompressedSize); break; } }
public void putDataBlob(string cmd, TestData data) { if (connEnable) { try{ string uriStr = "http://" + serverUrl + cmd; Debug.Log("start Upload url=" + uriStr); WebClient client = new WebClient(); client.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); //byte[] byteDocs = Encoding.UTF8.GetBytes(JsonUtility.ToJson(data)); byte[] byteDocs = ZlibStream.CompressString(JsonUtility.ToJson(data)); client.UploadDataCompleted += new UploadDataCompletedEventHandler(UploadBlobResult); client.UploadDataAsync(new System.Uri(uriStr), "POST", byteDocs); Debug.Log("Start Uploading result"); } catch (System.Exception e) { Debug.Log("Connection error: " + e); } } }
public void WriteAssetToFile(string filePath, bool zlibCompressed) { using (WebResponse response = WebRequest.Create(this.RemoteURL).GetResponse()) { using (FileStream fs = new FileStream(filePath, FileMode.Create)) { if (this.IsCompressed == zlibCompressed) { response.GetResponseStream().CopyTo(fs); } else { using (ZlibStream zlibStream = new ZlibStream(response.GetResponseStream(), this.IsCompressed ? CompressionMode.Decompress : CompressionMode.Compress)) { zlibStream.CopyTo(fs); } } } } }
/// <summary> /// Make a complete payload from <see cref="FbnsConnectionData"/> using Thrift. /// </summary> /// <returns>Payload</returns> public static async Task <IBuffer> BuildPayload(FbnsConnectionData data) { _memoryBufferTransport = new TMemoryBufferTransport(); _thrift = new TCompactProtocol(_memoryBufferTransport); _payloadData = data; var rawPayload = await ToThrift(); // zlib deflate var dataStream = new MemoryStream(512); using (var zlibStream = new ZlibStream(dataStream, CompressionMode.Compress, CompressionLevel.Level9, true)) { await zlibStream.WriteAsync(rawPayload, 0, rawPayload.Length); } var compressed = dataStream.GetWindowsRuntimeBuffer(0, (int)dataStream.Length); return(compressed); }
static void Main(string[] args) { if (args[0] == "-d") { FileStream fs = File.OpenRead(args[1]); int BufferSz = ReadInt32(fs); byte[] RunDataBuffer = new byte[BufferSz]; fs.Read(RunDataBuffer, 0x00, BufferSz); byte[] RunDataUncompressed = ZlibStream.UncompressBuffer(RunDataBuffer); File.WriteAllBytes(args[2], RunDataUncompressed); } if (args[0] == "-e") { byte[] RunDataUncompressed = File.ReadAllBytes(args[1]); FileStream fs = File.OpenWrite(args[2]); byte[] RunDataCompressed = Compress(RunDataUncompressed); WriteInt32(fs, RunDataCompressed.Length); fs.Write(RunDataCompressed, 0x00, RunDataCompressed.Length); } }
public void Write(RS5DirectoryEntry dirent) { long dataOffset = this.ArchiveStream.Length; this.ArchiveStream.Seek(dataOffset, SeekOrigin.Begin); using (ZlibStream zstream = new ZlibStream(this.ArchiveStream, CompressionMode.Compress, true)) { dirent.Data.ChunkData.CopyTo(zstream); } long comprlen = this.ArchiveStream.Position - dataOffset; int direntIndex = AddDirEntry(dataOffset, (int)comprlen, (int)dirent.Data.TotalSize, true, dirent.Name, dirent.Type, dirent.ModTime); byte[] direntdata = GetDirentBytes(this.CentralDirectoryEntries[direntIndex]); this.ArchiveStream.Seek(this.CentralDirectoryEntries[0].DataOffset + direntIndex * this.DirectoryEntryLength, SeekOrigin.Begin); this.ArchiveStream.Write(direntdata, 0, direntdata.Length); }
/// <summary> /// Compress a byte array into another bytes array using Zlib compression /// </summary> /// <param name="toCompress">Data to compress</param> /// <returns>Compressed data as a byte array</returns> public static byte[] Compress(byte[] toCompress) { ZlibStream stream = new ZlibStream(new MemoryStream(toCompress, false), CompressionMode.Compress); MemoryStream outputStream = new MemoryStream(); var buffer = new byte[32768]; while (true) { var read = stream.Read(buffer, 0, buffer.Length); if (read > 0) { outputStream.Write(buffer, 0, read); } else { break; } } return(outputStream.ToArray()); }
// Use this for initialization void Start() { FileStream input = new FileStream("E:/gamecheat/resource/ttlz/dump.txt", FileMode.Open, FileAccess.ReadWrite); FileStream output = new FileStream("E:/gamecheat/resource/ttlz/dump.dll", FileMode.OpenOrCreate, FileAccess.ReadWrite); string FileName_HashKey = "dump"; long FileSize = input.Length; byte[] data = new byte[FileSize]; input.Read(data, 0, (int)FileSize); System.Random random = new System.Random(FileName_HashKey.GetHashCode()); for (int i = 0; i < data.Length; i++) { data[i] ^= (byte)random.Next(256); } byte[] temp = ZlibStream.UncompressBuffer(data); for (int i = 0; i < temp.Length; i++) { output.WriteByte(temp[i]); } }
private bool ReadCompressed(ClientWrapper client, NetworkStream clientStream, int dlength) { var buffie = new byte[dlength]; int receivedData; receivedData = clientStream.Read(buffie, 0, buffie.Length); buffie = ZlibStream.UncompressBuffer(buffie); if (receivedData > 0) { var buf = new DataBuffer(client); if (client.Decrypter != null) { var date = new byte[4096]; client.Decrypter.TransformBlock(buffie, 0, buffie.Length, date, 0); buf.BufferedData = date; } else { buf.BufferedData = buffie; } buf.BufferedData = buffie; buf.Size = dlength; var packid = buf.ReadVarInt(); if (!new PackageFactory(client, buf).Handle(packid)) { ConsoleFunctions.WriteWarningLine("Unknown packet received! \"0x" + packid.ToString("X2") + "\""); } buf.Dispose(); return(true); } else { return(false); } }
public static IEnumerable <ZlibFile> Open(string path) { var files = new List <ZlibFile>(); using (var reader = new BinaryReader(File.OpenRead(path))) { byte[] header = reader.ReadBytes(0x10); int count = reader.ReadInt32(); byte[] separator = reader.ReadBytes(1); for (int i = 0; i != count; i++) { int id = reader.ReadInt32(); int offset = reader.ReadInt32(); long previous = reader.BaseStream.Position; reader.BaseStream.Seek(offset, SeekOrigin.Begin); int creation = reader.ReadInt32(); int size = reader.ReadInt32(); int compressedSize = reader.ReadInt32(); bool compressed = Convert.ToBoolean(reader.ReadBytes(1)[0]); byte[] data = reader.ReadBytes(compressedSize); if (compressed) { data = ZlibStream.UncompressBuffer(data); } files.Add(new ZlibFile { Id = id, Content = data }); reader.BaseStream.Seek(previous, SeekOrigin.Begin); } } return(files); }
static WAD WriteOnlineWAD(string[] filenames) { WADHeader header = new WADHeader(); header.magic = 0x543377AB; header.timestamp = 13371337; header.numEntries = (uint)filenames.Length; header.ffotdVersion = 0; List <WADEntry> entries = new List <WADEntry>(); uint offset = 16 + (header.numEntries * 44); foreach (string name in filenames) { string[] nameA = name.Split('\\'); string name2 = nameA[nameA.Length - 1]; Console.WriteLine("Compressing " + name2 + "..."); WADEntry entry = new WADEntry(); byte[] decompressedBuf = File.ReadAllBytes(name); byte[] compressedBuf = ZlibStream.CompressBuffer(decompressedBuf); entry.name = name2; entry.compressedBuf = compressedBuf; entry.compressedSize = (uint)compressedBuf.Length; entry.offset = offset; entry.size = (uint)decompressedBuf.Length; offset += entry.compressedSize; entries.Add(entry); } WAD wad = new WAD(); wad.header = header; wad.entries = entries; return(wad); }
public static MapFormatHelper FromStream(Stream inputStream) { MapFormatHelper helper = new MapFormatHelper(); BinaryReader reader = new BinaryReader(inputStream); // Signature1 int signature1 = reader.ReadInt32(); ValidateSignature(_signature1, signature1, inputStream.Position - sizeof(int)); // Signature 2 int signature2 = reader.ReadInt32(); // Header length, IDs inputStream.Position += 4; // always 0 int headerLength = reader.ReadInt32(); helper.ModID = reader.ReadInt32(); helper.MapClassID = reader.ReadInt32(); // Header stream helper.HeaderStream = new MemoryStream(); inputStream.CopyBytesTo(helper.HeaderStream, headerLength); // CFS signature ValidateSignature(reader, _signatureCFS); // Data stream helper._dataStream = new Lazy <Stream>( () => { MemoryStream dataStream = new MemoryStream(); using (ZlibStream zlib = new ZlibStream(inputStream, CompressionMode.Decompress)) { zlib.CopyTo(dataStream); } return(dataStream); }); return(helper); }
/// <summary> /// Flush all data to the TCPClient NetworkStream. /// </summary> public void FlushData(bool quee = false) { try { var AllData = bffr.ToArray(); bffr.Clear(); if (Globals.UseCompression && _client.PacketMode == PacketMode.Play) { var mg = new MSGBuffer(_client); //ToWriteAllData var compressed = ZlibStream.CompressBuffer(AllData); mg.WriteVarInt(compressed.Length); mg.WriteVarInt(compressed.Length); mg.Write(compressed); _client.AddToQuee(mg.ExportWriter, quee); } else { WriteVarInt(AllData.Length); var Buffer = bffr.ToArray(); var data = new List <byte>(); foreach (var i in Buffer) { data.Add(i); } foreach (var i in AllData) { data.Add(i); } _client.AddToQuee(data.ToArray(), quee); } bffr.Clear(); } catch (Exception ex) { ConsoleFunctions.WriteErrorLine("Failed to send a packet!\n" + ex); } }
public static byte[] Compress(byte[] file) { int splitSize = 0x10000; int partitionCount = ((file.Length - 1) / 0x10000) + 1; var partitionList = new List <byte[]>(); using (var reader = new BinaryReader(new MemoryStream(file))) { for (int i = 0; i < partitionCount; i++) { var encoding = new ZlibCodec(); encoding.InitializeDeflate(Ionic.Zlib.CompressionLevel.BestCompression); // RFC1950/1951/1952 encoding needed byte[] buffer = ZlibStream.CompressBuffer(reader.ReadBytes(splitSize)); encoding.EndDeflate(); partitionList.Add(buffer); } } using (var ms = new MemoryStream()) using (var br = new BinaryWriter(ms)) { // Header br.Write(splitSize); br.Write(partitionCount); br.Write(file.Length); // Uncompressed file length for (int i = 0; i < partitionList.Count; i++) { br.Write(partitionList[i].Length + 4); // Entry size (partition size member + partition) } long currentOffset = br.BaseStream.Position; // Entries for (int i = 0; i < partitionList.Count; i++) { br.BaseStream.Position = currentOffset + 0x7F & ~0x7F; // Aligning br.Write(partitionList[i].Length); br.BaseStream.Write(partitionList[i], 0x0, partitionList[i].Length); currentOffset = br.BaseStream.Position; } return(ms.ToArray()); } }
internal static (int modId, int mapClassId, int hmSignature, MemoryStream dataStream) ReadPreHeaderAndDecompressDataStream(Stream inputStream) { (int modId, int mapClassId, int hmSignature, int headerLength) = ReadPreHeader(inputStream); // Header stream inputStream.Position += headerLength; // CFS signature ValidateSignature(new BinaryReader(inputStream), _signatureCFS); // Data stream MemoryStream dataStream = new MemoryStream(); using (ZlibStream zlib = new ZlibStream(inputStream, CompressionMode.Decompress, leaveOpen: true)) { zlib.CopyTo(dataStream); } dataStream.Position = 0; return(modId, mapClassId, hmSignature, dataStream); }
public static EffectListEntry FillEFLEntry(string filename, List <string> subnames, TreeView tree, BinaryReader br, int c, int ID, Type filetype = null) { EffectListEntry effectList = new EffectListEntry(); List <byte> BTemp = new List <byte>(); FillEntry(filename, subnames, tree, br, c, ID, effectList, filetype); //Decompression Time. effectList.UncompressedData = ZlibStream.UncompressBuffer(effectList.CompressedData); //Type Specific Work Here. using (MemoryStream LmtStream = new MemoryStream(effectList.UncompressedData)) { using (BinaryReader bnr = new BinaryReader(LmtStream)) { BuildEffectListEntry(bnr, effectList); } } return(effectList); }
private string GetText() { var r = new StringBuilder(numTextPages); for (var i = 1; i <= numTextPages; i++) { var encryptedSection = pdbReader.GetSection(i); var decryptedSection = contentDecryptor.TransformFinalBlock(encryptedSection, 0, encryptedSection.Length); byte[] decompressedSection; using (var inStream = new MemoryStream(decryptedSection)) using (var zipStream = new ZlibStream(inStream, CompressionMode.Decompress)) using (var outStream = new MemoryStream()) { zipStream.CopyTo(outStream); decompressedSection = outStream.ToArray(); } var text = Encoding.GetEncoding(1252).GetString(decompressedSection); r.Append(text); } return(r.ToString()); }
/// <summary> /// Compress a byte array into another bytes array using Zlib compression /// </summary> /// <param name="to_compress">Data to compress</param> /// <returns>Compressed data as a byte array</returns> public static byte[] Compress(byte[] to_compress) { ZlibStream stream = new ZlibStream(new System.IO.MemoryStream(to_compress, false), CompressionMode.Compress); List <byte> temp_compression_list = new List <byte>(); byte[] b = new byte[1]; while (true) { int read = stream.Read(b, 0, 1); if (read > 0) { temp_compression_list.Add(b[0]); } else { break; } } stream.Close(); return(temp_compression_list.ToArray()); }
/// <summary> /// Writes a block of file data, possibly compressing it. /// </summary> /// <param name="buffer">The data to write</param> /// <param name="offset">Offset of the first byte to write</param> /// <param name="count">The number of bytes to write</param> /// <returns> /// The 'length' of the (possibly compressed) data written, including /// a flag indicating compression (or not). /// </returns> private uint WriteDataBlock(byte[] buffer, int offset, int count) { MemoryStream compressed = new MemoryStream(); using (ZlibStream compStream = new ZlibStream(compressed, CompressionMode.Compress, true)) { compStream.Write(buffer, offset, count); } byte[] writeData; int writeOffset; int writeLen; if (compressed.Length < count) { writeData = compressed.GetBuffer(); writeOffset = 0; writeLen = (int)compressed.Length; } else { writeData = buffer; writeOffset = offset; writeLen = count | 0x01000000; } _context.RawStream.Write(writeData, writeOffset, writeLen & 0xFFFFFF); return (uint)writeLen; }
private void NextBlock() { MemoryStream compressed = new MemoryStream(); using (ZlibStream compStream = new ZlibStream(compressed, CompressionMode.Compress, true)) { compStream.Write(_currentBlock, 0, _currentOffset); } byte[] writeData; ushort writeLen; if (compressed.Length < _currentOffset) { writeData = compressed.GetBuffer(); writeLen = (ushort)compressed.Length; } else { writeData = _currentBlock; writeLen = (ushort)(_currentOffset | 0x8000); } byte[] header = new byte[2]; Utilities.WriteBytesLittleEndian(writeLen, header, 0); _buffer.Write(header, 0, 2); _buffer.Write(writeData, 0, writeLen & 0x7FFF); ++_currentBlockNum; }