File size: 1,152 Bytes
ac55997
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
using System.Collections.Generic;
using System.Runtime.CompilerServices;

namespace Quantum
{
	public static class Pool<T> where T : new()
	{
		private const int POOL_CAPACITY = 4;

		private static readonly List<T> _pool = new List<T>(POOL_CAPACITY);

		public static int Count => _pool.Count;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static T Get()
		{
			bool found = false;
			T item = default;

			lock (_pool)
			{
				int index = _pool.Count - 1;
				if (index >= 0)
				{
					found = true;
					item = _pool[index];

					_pool.RemoveAt(index);
				}
			}

			if (found == false)
			{
				item = new T();
			}

			return item;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void Return(T item)
		{
			if (item == null)
				return;

			lock (_pool)
			{
				_pool.Add(item);
			}
		}
	}

	public static class Pool
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static T Get<T>() where T : new()
		{
			return Pool<T>.Get();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void Return<T>(T item) where T : new()
		{
			Pool<T>.Return(item);
		}
	}
}