-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathExactMemoryPool.cs
More file actions
71 lines (60 loc) · 1.66 KB
/
Copy pathExactMemoryPool.cs
File metadata and controls
71 lines (60 loc) · 1.66 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
using System;
using System.Buffers;
namespace ICSharpCode.SharpZipLib.Core
{
/// <summary>
/// A MemoryPool that will return a Memory which is exactly the length asked for using the bufferSize parameter.
/// This is in contrast to the default ArrayMemoryPool which will return a Memory of equal size to the underlying
/// array which at least as long as the minBufferSize parameter.
/// Note: The underlying array may be larger than the slice of Memory
/// </summary>
/// <typeparam name="T"></typeparam>
internal sealed class ExactMemoryPool<T> : MemoryPool<T>
{
public new static readonly MemoryPool<T> Shared = new ExactMemoryPool<T>();
public override IMemoryOwner<T> Rent(int bufferSize = -1)
{
if ((uint)bufferSize > int.MaxValue || bufferSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize));
}
return new ExactMemoryPoolBuffer(bufferSize);
}
protected override void Dispose(bool disposing)
{
}
public override int MaxBufferSize => int.MaxValue;
private sealed class ExactMemoryPoolBuffer : IMemoryOwner<T>, IDisposable
{
private T[] array;
private readonly int size;
public ExactMemoryPoolBuffer(int size)
{
this.size = size;
this.array = ArrayPool<T>.Shared.Rent(size);
}
public Memory<T> Memory
{
get
{
T[] array = this.array;
if (array == null)
{
throw new ObjectDisposedException(nameof(ExactMemoryPoolBuffer));
}
return new Memory<T>(array).Slice(0, size);
}
}
public void Dispose()
{
T[] array = this.array;
if (array == null)
{
return;
}
this.array = null;
ArrayPool<T>.Shared.Return(array);
}
}
}
}