| | | 1 | | using System.IO.Compression; |
| | | 2 | | using System.Text; |
| | | 3 | | |
| | | 4 | | namespace Elsa.Common.Codecs; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Represents a GZip compression strategy. |
| | | 8 | | /// </summary> |
| | | 9 | | public class GZip : ICompressionCodec |
| | | 10 | | { |
| | | 11 | | /// <inheritdoc /> |
| | | 12 | | public async ValueTask<string> CompressAsync(string input, CancellationToken cancellationToken) |
| | | 13 | | { |
| | 0 | 14 | | var inputBytes = Encoding.UTF8.GetBytes(input); |
| | 0 | 15 | | using var output = new MemoryStream(); |
| | 0 | 16 | | await using var compressionStream = new GZipStream(output, CompressionMode.Compress); |
| | 0 | 17 | | await compressionStream.WriteAsync(inputBytes, 0, inputBytes.Length, cancellationToken); |
| | 0 | 18 | | await compressionStream.FlushAsync(cancellationToken); |
| | | 19 | | |
| | 0 | 20 | | return Convert.ToBase64String(output.ToArray()); |
| | 0 | 21 | | } |
| | | 22 | | |
| | | 23 | | /// <inheritdoc /> |
| | | 24 | | public async ValueTask<string> DecompressAsync(string input, CancellationToken cancellationToken) |
| | | 25 | | { |
| | 0 | 26 | | var inputBytes = Convert.FromBase64String(input); |
| | 0 | 27 | | using var inputMemoryStream = new MemoryStream(inputBytes); |
| | 0 | 28 | | await using var decompressionStream = new GZipStream(inputMemoryStream, CompressionMode.Decompress); |
| | 0 | 29 | | using var outputMemoryStream = new MemoryStream(); |
| | 0 | 30 | | await decompressionStream.CopyToAsync(outputMemoryStream, cancellationToken); |
| | 0 | 31 | | var decompressedBytes = outputMemoryStream.ToArray(); |
| | | 32 | | |
| | 0 | 33 | | return Encoding.UTF8.GetString(decompressedBytes); |
| | 0 | 34 | | } |
| | | 35 | | } |