public async Task FillPipeAsync(DiscordAttachment attachment, PipeWriter writer) { using (var client = HttpClientFactory.Create()) using (var downloadStream = await client.GetStreamAsync(attachment.Url).ConfigureAwait(false)) using (var gzipStream = new GZipStream(downloadStream, CompressionMode.Decompress)) { try { int read; FlushResult flushed; do { var memory = writer.GetMemory(Config.MinimumBufferSize); read = await gzipStream.ReadAsync(memory, Config.Cts.Token); writer.Advance(read); flushed = await writer.FlushAsync(Config.Cts.Token).ConfigureAwait(false); } while (read > 0 && !(flushed.IsCompleted || flushed.IsCanceled || Config.Cts.IsCancellationRequested)); } catch (Exception e) { Config.Log.Error(e, "Error filling the log pipe"); writer.Complete(e); return; } } writer.Complete(); }
// Making this async since regular read/write are tested below private static async Task DecompressAsync(MemoryStream compareStream, MemoryStream gzStream) { var ms = new MemoryStream(); var zip = new GZipStream(gzStream, CompressionMode.Decompress); var GZipStream = new MemoryStream(); int _bufferSize = 1024; var bytes = new Byte[_bufferSize]; bool finished = false; int retCount; while (!finished) { retCount = await zip.ReadAsync(bytes, 0, _bufferSize); if (retCount != 0) await GZipStream.WriteAsync(bytes, 0, retCount); else finished = true; } GZipStream.Position = 0; compareStream.Position = 0; byte[] compareArray = compareStream.ToArray(); byte[] writtenArray = GZipStream.ToArray(); Assert.Equal(compareArray.Length, writtenArray.Length); for (int i = 0; i < compareArray.Length; i++) { Assert.Equal(compareArray[i], writtenArray[i]); } }