-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCompressor.cs
More file actions
103 lines (84 loc) · 2.6 KB
/
Compressor.cs
File metadata and controls
103 lines (84 loc) · 2.6 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
using LibDeflate.Buffers;
using LibDeflate.Imports;
using System;
using System.Buffers;
namespace LibDeflate;
using static Compression;
public abstract class Compressor : IDisposable
{
protected readonly IntPtr compressor;
private bool disposedValue;
protected Compressor(int compressionLevel)
{
if (compressionLevel < 0 || compressionLevel > 12)
{
ThrowHelperBadCompressionLevel();
}
var compressor = libdeflate_alloc_compressor(compressionLevel);
if (compressor == IntPtr.Zero)
{
ThrowHelperFailedAllocCompressor();
}
this.compressor = compressor;
static void ThrowHelperBadCompressionLevel() => throw new ArgumentOutOfRangeException(nameof(compressionLevel));
static void ThrowHelperFailedAllocCompressor() => throw new InvalidOperationException("Failed to allocate compressor");
}
~Compressor() => Dispose(disposing: false);
protected abstract nuint CompressCore(ReadOnlySpan<byte> input, Span<byte> output);
protected abstract nuint GetBoundCore(nuint inputLength);
public IMemoryOwner<byte>? Compress(ReadOnlySpan<byte> input, bool useUpperBound = false)
{
DisposedGuard();
var output = MemoryOwner<byte>.Allocate(useUpperBound ? GetBound(input.Length) : input.Length);
try
{
nuint bytesWritten = CompressCore(input, output.Span);
if (bytesWritten == UIntPtr.Zero)
{
output.Dispose();
return null;
}
return output[..(int)bytesWritten];
}
catch
{
output?.Dispose();
throw;
}
}
public int Compress(ReadOnlySpan<byte> input, Span<byte> output)
{
DisposedGuard();
return (int)CompressCore(input, output);
}
public int GetBound(int inputLength)
{
DisposedGuard();
return (int)GetBoundCore((nuint)inputLength);
}
private void DisposedGuard()
{
if(disposedValue)
{
ThrowHelperObjectDisposed();
}
static void ThrowHelperObjectDisposed() => throw new ObjectDisposedException(nameof(Compressor));
}
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
//no managed state to dispose
//if (disposing)
//{
//}
libdeflate_free_compressor(compressor);
disposedValue = true;
}
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}