forked from BAndysc/WoWDatabaseEditor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGroupedArrayPooler.cs
92 lines (79 loc) · 2.22 KB
/
GroupedArrayPooler.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
92
using System;
using System.Buffers;
using System.Collections;
using System.Diagnostics;
namespace WDE.MpqReader
{
public class PooledArray<T> : System.IDisposable
{
private readonly T[] array;
private int length;
private bool disposed;
public PooledArray(int length)
{
this.length = length;
array = ArrayPool<T>.Shared.Rent(length);
}
~PooledArray()
{
if (!disposed)
{
Console.WriteLine("PooledArray was not disposed");
Dispose();
}
}
public int Length => length;
public bool IsDisposed => disposed;
public T this[int index]
{
get
{
#if DEBUG
Debug.Assert(!disposed, "Trying to read disposed PooledArray");
#endif
return array[index];
}
set => array[index] = value;
}
public ReadOnlySpan<T> AsSpan() => array.AsSpan(0, length);
public T[] AsArray() => array;
public void Dispose()
{
disposed = true;
ArrayPool<T>.Shared.Return(array);
}
public void Shrink(int newLength)
{
Debug.Assert(newLength <= length);
length = newLength;
}
}
public struct GroupedArrayPooler<T> : System.IDisposable
{
private readonly T[][] arrays;
private readonly int length;
private int i = 0;
public GroupedArrayPooler(int capacity)
{
length = capacity;
i = 0;
arrays = ArrayPool<T[]>.Shared.Rent(capacity);
}
public T[] Get(int size)
{
var array= ArrayPool<T>.Shared.Rent(size);
if (i >= length)
throw new Exception("This array pooler can create no more than " + length + " arrays");
arrays[i++] = array;
return array;
}
public void Dispose()
{
for (int j = 0; j < i; ++j)
{
ArrayPool<T>.Shared.Return(arrays[j]);
}
ArrayPool<T[]>.Shared.Return(arrays);
}
}
}