summaryrefslogtreecommitdiffstats
path: root/src/AllocationPool.h
blob: f1e3249530e31ec966c0ebd41b1f35a75ef1d981 (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

#pragma once

template<class T, size_t BufferSize, class StarvationCallbacks>
class AllocationPool {
	public:
		
		~AllocationPool()
		{
			while (!m_FreeList.empty())
			{
				delete m_FreeList.front();
				m_FreeList.pop_front();
			}
		}	
		
		T* Allocate()
		{
			if (m_FreeList.Size() <= BufferSize)
			{
				try
				{
					return new T;
				}
				catch (std::bad_alloc& ex)
				{
					if (m_FreeList.size() == BufferSize)
					{
						StarvationCallbacks.OnStartingUsingBuffer();
					}
					else if (m_FreeList.empty())
					{
						StarvationCallbacks.OnBufferEmpty();
						// Try again until the memory is avalable
						return Allocate();
					}
				}
			}
			T* ret = m_FreeList.front();
			m_FreeList.pop_front();
			return ret;
		}
		void Free(T* ptr)
		{
			m_FreeList.push_front(ptr);
			if (m_FreeList.size() == BufferSize)
			{
				StarvationCallbacks.OnStopUsingBuffer();
			}
		}
		
	private:
		std::list<T*> m_FreeList;
}