Repository navigation
Expand file tree
/
Copy pathGzipCodec.cs
More file actions
52 lines (41 loc) · 1.68 KB
/
Copy pathGzipCodec.cs
File metadata and controls
52 lines (41 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System.IO.Compression;
namespace ZarrNET;
/// <summary>
/// Gzip bytes-to-bytes codec. Wraps System.IO.Compression — no native dependencies.
/// Configuration mirrors the zarr.json "gzip" codec configuration object.
/// </summary>
public sealed class GzipCodec : IZarrCodec
{
public string Name => "gzip";
private readonly CompressionLevel _compressionLevel;
public GzipCodec(int level = 6)
{
_compressionLevel = level switch
{
0 => CompressionLevel.NoCompression,
1 => CompressionLevel.Fastest,
>= 7 => CompressionLevel.SmallestSize,
_ => CompressionLevel.Optimal
};
}
// -------------------------------------------------------------------------
// IZarrCodec
// -------------------------------------------------------------------------
public async Task<byte[]> DecodeAsync(byte[] input, CancellationToken ct = default)
{
await using var inputStream = new MemoryStream(input);
await using var gzipStream = new GZipStream(inputStream, CompressionMode.Decompress);
await using var outputStream = new MemoryStream();
await gzipStream.CopyToAsync(outputStream, ct).ConfigureAwait(false);
return outputStream.ToArray();
}
public async Task<byte[]> EncodeAsync(byte[] input, CancellationToken ct = default)
{
await using var outputStream = new MemoryStream();
await using (var gzipStream = new GZipStream(outputStream, _compressionLevel, leaveOpen: true))
{
await gzipStream.WriteAsync(input, ct).ConfigureAwait(false);
}
return outputStream.ToArray();
}
}