summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorTycho <work.tycho+git@gmail.com>2014-05-21 21:59:04 +0200
committerTycho <work.tycho+git@gmail.com>2014-05-21 21:59:04 +0200
commit485752de82e6058473dfe8dccdf64ac04e983ae9 (patch)
treebf0765873f30ff4abc6de428f7aa60e989add41c /src
parentFixed minor style issues (diff)
downloadcuberite-485752de82e6058473dfe8dccdf64ac04e983ae9.tar
cuberite-485752de82e6058473dfe8dccdf64ac04e983ae9.tar.gz
cuberite-485752de82e6058473dfe8dccdf64ac04e983ae9.tar.bz2
cuberite-485752de82e6058473dfe8dccdf64ac04e983ae9.tar.lz
cuberite-485752de82e6058473dfe8dccdf64ac04e983ae9.tar.xz
cuberite-485752de82e6058473dfe8dccdf64ac04e983ae9.tar.zst
cuberite-485752de82e6058473dfe8dccdf64ac04e983ae9.zip
Diffstat (limited to '')
-rw-r--r--src/AllocationPool.h50
1 files changed, 50 insertions, 0 deletions
diff --git a/src/AllocationPool.h b/src/AllocationPool.h
new file mode 100644
index 000000000..f03897f98
--- /dev/null
+++ b/src/AllocationPool.h
@@ -0,0 +1,50 @@
+
+#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);
+ }
+
+ private:
+ std::list<T*> m_FreeList;
+}