Files
cuberite-2a/src/AllocationPool.h
T

98 lines
2.0 KiB
C++
Raw Normal View History

2014-05-21 20:59:04 +01:00
#pragma once
#include <memory>
2014-06-14 19:46:34 +01:00
template<class T>
class cAllocationPool
{
public:
class cStarvationCallbacks
{
public:
virtual ~cStarvationCallbacks() {}
virtual void OnStartingUsingBuffer() = 0;
virtual void OnStopUsingBuffer() = 0;
virtual void OnBufferEmpty() = 0;
};
virtual ~cAllocationPool() {}
virtual T * Allocate() = 0;
virtual void Free(T * a_ptr) = 0;
};
2014-06-14 17:57:21 +01:00
template<class T, size_t NumElementsInReserve>
2014-06-14 19:46:34 +01:00
class cListAllocationPool : public cAllocationPool<T>
2014-06-14 19:05:02 +01:00
{
2014-05-21 20:59:04 +01:00
public:
2014-06-14 19:46:34 +01:00
cListAllocationPool(std::auto_ptr<typename cAllocationPool<T>::cStarvationCallbacks> a_Callbacks) :
2014-06-14 19:05:02 +01:00
m_Callbacks(a_Callbacks)
{
2014-06-14 18:43:36 +01:00
for (size_t i = 0; i < NumElementsInReserve; i++)
2014-06-14 17:59:47 +01:00
{
void * space = malloc(sizeof(T));
if (space == NULL)
{
m_Callbacks->OnStartingUsingBuffer();
break;
}
m_FreeList.push_front(space);
}
}
2014-05-21 20:59:04 +01:00
2014-06-14 19:46:34 +01:00
virtual ~cListAllocationPool()
2014-05-21 20:59:04 +01:00
{
while (!m_FreeList.empty())
{
free (m_FreeList.front());
2014-05-21 20:59:04 +01:00
m_FreeList.pop_front();
}
}
2014-06-14 19:46:34 +01:00
virtual T * Allocate() override
2014-05-21 20:59:04 +01:00
{
2014-06-14 17:57:21 +01:00
if (m_FreeList.size() <= NumElementsInReserve)
2014-05-21 20:59:04 +01:00
{
2014-05-25 17:48:40 +01:00
void * space = malloc(sizeof(T));
if (space != NULL)
2014-05-21 20:59:04 +01:00
{
2014-05-25 17:48:40 +01:00
return new(space) T;
2014-05-21 20:59:04 +01:00
}
2014-06-14 17:57:21 +01:00
else if (m_FreeList.size() == NumElementsInReserve)
2014-05-21 20:59:04 +01:00
{
2014-05-25 17:48:40 +01:00
m_Callbacks->OnStartingUsingBuffer();
}
else if (m_FreeList.empty())
{
m_Callbacks->OnBufferEmpty();
// Try again until the memory is avalable
return Allocate();
2014-05-21 20:59:04 +01:00
}
}
2014-05-23 15:48:09 +01:00
// placement new, used to initalize the object
2014-06-14 19:05:02 +01:00
T * ret = new (m_FreeList.front()) T;
2014-05-21 20:59:04 +01:00
m_FreeList.pop_front();
return ret;
}
2014-06-14 19:46:34 +01:00
virtual void Free(T * a_ptr) override
2014-05-21 20:59:04 +01:00
{
2014-06-14 19:46:34 +01:00
if (a_ptr == NULL)
2014-05-25 17:48:40 +01:00
{
return;
}
2014-05-23 15:48:09 +01:00
// placement destruct.
2014-06-14 19:46:34 +01:00
a_ptr->~T();
m_FreeList.push_front(a_ptr);
2014-06-14 17:57:21 +01:00
if (m_FreeList.size() == NumElementsInReserve)
2014-05-21 21:30:08 +01:00
{
m_Callbacks->OnStopUsingBuffer();
2014-05-21 21:30:08 +01:00
}
2014-05-21 20:59:04 +01:00
}
private:
2014-05-23 15:48:09 +01:00
std::list<void *> m_FreeList;
2014-06-14 19:46:34 +01:00
std::auto_ptr<typename cAllocationPool<T>::cStarvationCallbacks> m_Callbacks;
};