This repository has been archived by the owner on Aug 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 347
/
NativeMemoryPool.cs
91 lines (75 loc) · 2.85 KB
/
NativeMemoryPool.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
namespace System.Buffers.Native
{
public unsafe sealed partial class NativeMemoryPool : MemoryPool<byte>
{
const int DefaultSize = 4096;
/// <summary>
/// This default value passed in to Rent to use the default value for the pool.
/// </summary>
private const int AnySize = -1;
static NativeMemoryPool s_shared = new NativeMemoryPool(DefaultSize);
object _lock = new object();
bool _disposed;
IntPtr _memory;
int _bufferSize;
int _bufferCount;
bool[] _rented;
public static new NativeMemoryPool Shared => s_shared;
public NativeMemoryPool(int bufferSize, int bufferCount = 10)
{
if (bufferSize < 1) throw new ArgumentOutOfRangeException(nameof(bufferSize));
if (bufferCount < 1) throw new ArgumentOutOfRangeException(nameof(bufferSize));
_rented = new bool[bufferCount];
_bufferSize = bufferSize;
_bufferCount = bufferCount;
_memory = Marshal.AllocHGlobal(_bufferSize * _bufferCount);
}
protected override void Dispose(bool disposing)
{
lock (_lock)
{
if (_disposed) return;
_disposed = true;
}
Marshal.FreeHGlobal(_memory);
}
public override int MaxBufferSize => 1024 * 1024 * 1024;
public override IMemoryOwner<byte> Rent(int numberOfBytes = AnySize)
{
if (numberOfBytes == AnySize) numberOfBytes = DefaultSize;
if (numberOfBytes < 1 || numberOfBytes > MaxBufferSize) throw new ArgumentOutOfRangeException(nameof(numberOfBytes));
if (numberOfBytes > _bufferSize) new NotSupportedException();
int i;
lock (_lock)
{
for (i = 0; i < _rented.Length; i++)
{
if (!_rented[i])
{
_rented[i] = true;
break;
}
}
}
if (i >= _rented.Length)
{
throw new NotImplementedException("no more buffers to rent");
}
return new Memory(this, new IntPtr((byte*)(_memory + i * _bufferSize)), _bufferSize);
}
internal void Return(Memory pooledBuffer)
{
var memory = pooledBuffer.Pointer.ToInt64();
var offset = memory - _memory.ToInt64();
var index = offset / _bufferSize;
lock (_lock)
{
_rented[index] = false;
}
}
}
}