aboutsummaryrefslogtreecommitdiff
path: root/src/Spv.Generator/GeneratorPool.cs
blob: 3c16586c958d411c692472051573b583b24e905c (plain) (blame)
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
using System.Collections.Generic;

namespace Spv.Generator
{
    public class GeneratorPool<T> where T : class, new()
    {
        private readonly List<T[]> _pool;
        private int _chunkIndex = -1;
        private int _poolIndex = -1;
        private readonly int _poolSizeIncrement;

        public GeneratorPool() : this(1000, 200) { }

        public GeneratorPool(int chunkSizeLimit, int poolSizeIncrement)
        {
            _poolSizeIncrement = poolSizeIncrement;

            _pool = new(chunkSizeLimit * 2);

            AddChunkIfNeeded();
        }

        public T Allocate()
        {
            if (++_poolIndex >= _poolSizeIncrement)
            {
                AddChunkIfNeeded();

                _poolIndex = 0;
            }

            return _pool[_chunkIndex][_poolIndex];
        }

        private void AddChunkIfNeeded()
        {
            if (++_chunkIndex >= _pool.Count)
            {
                T[] pool = new T[_poolSizeIncrement];

                for (int i = 0; i < _poolSizeIncrement; i++)
                {
                    pool[i] = new T();
                }

                _pool.Add(pool);
            }
        }

        public void Clear()
        {
            _chunkIndex = 0;
            _poolIndex = -1;
        }
    }
}