-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathCompression.cs
More file actions
60 lines (54 loc) · 2.25 KB
/
Copy pathCompression.cs
File metadata and controls
60 lines (54 loc) · 2.25 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
53
54
55
56
57
58
59
60
using System.IO.Compression;
namespace BytecodeApi.IO;
/// <summary>
/// Class to compress and decompress data using GZip.
/// </summary>
public static class Compression
{
/// <summary>
/// Compresses the specified <see cref="byte" />[] using GZip and returns a new <see cref="byte" />[] that can be used with the <see cref="Decompress" /> method.
/// </summary>
/// <param name="data">A <see cref="byte" />[] that represents data to be compressed.</param>
/// <returns>
/// A new <see cref="byte" />[] that can be used with the <see cref="Decompress" /> method.
/// </returns>
public static byte[] Compress(byte[] data)
{
return Compress(data, CompressionLevel.Optimal);
}
/// <summary>
/// Compresses the specified <see cref="byte" />[] using GZip and returns a new <see cref="byte" />[] that can be used with the <see cref="Decompress" /> method.
/// </summary>
/// <param name="data">A <see cref="byte" />[] that represents data to be compressed.</param>
/// <param name="compressionLevel">The level of compression to use to either emphasize speed or compression efficiency.</param>
/// <returns>
/// A new <see cref="byte" />[] that can be used with the <see cref="Decompress" /> method.
/// </returns>
public static byte[] Compress(byte[] data, CompressionLevel compressionLevel)
{
Check.ArgumentNull(data);
using MemoryStream memoryStream = new();
using (GZipStream gzipStream = new(memoryStream, compressionLevel, true))
{
gzipStream.Write(data);
}
return memoryStream.ToArray();
}
/// <summary>
/// Decompresses the specified <see cref="byte" />[] using GZip and returns a new <see cref="byte" />[] that represents the uncompressed data.
/// </summary>
/// <param name="data">A <see cref="byte" />[] that represents data compressed by the <see cref="Compress(byte[])" /> method.</param>
/// <returns>
/// A new <see cref="byte" />[] that represents the uncompressed data.
/// </returns>
public static byte[] Decompress(byte[] data)
{
Check.ArgumentNull(data);
using MemoryStream memoryStream = new();
using (GZipStream gzipStream = new(new MemoryStream(data), CompressionMode.Decompress))
{
gzipStream.CopyTo(memoryStream);
}
return memoryStream.ToArray();
}
}