2014-07-22 01:58:24 +00:00
|
|
|
/*
|
|
|
|
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
|
|
|
|
Released under Apache 2.0 license as described in the file LICENSE.
|
|
|
|
|
|
|
|
Author: Leonardo de Moura
|
|
|
|
*/
|
|
|
|
#pragma once
|
|
|
|
#include "util/memory.h"
|
|
|
|
|
|
|
|
namespace lean {
|
2014-07-22 14:49:40 +00:00
|
|
|
/** \brief Auxiliary object for "recycling" allocated memory of fixed size */
|
2014-07-22 01:58:24 +00:00
|
|
|
template<unsigned Size>
|
2014-07-22 14:49:40 +00:00
|
|
|
class memory_pool {
|
2014-07-22 01:58:24 +00:00
|
|
|
void * m_free_list;
|
|
|
|
public:
|
2014-07-22 14:49:40 +00:00
|
|
|
memory_pool():m_free_list(nullptr) {}
|
|
|
|
~memory_pool() {
|
2014-07-22 01:58:24 +00:00
|
|
|
while (m_free_list != nullptr) {
|
|
|
|
void * r = m_free_list;
|
|
|
|
m_free_list = *(reinterpret_cast<void **>(r));
|
|
|
|
free(r);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void * allocate() {
|
|
|
|
if (m_free_list != nullptr) {
|
|
|
|
void * r = m_free_list;
|
|
|
|
m_free_list = *(reinterpret_cast<void **>(r));
|
|
|
|
return r;
|
|
|
|
} else {
|
|
|
|
return malloc(Size);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-07-22 16:18:26 +00:00
|
|
|
void recycle(void * ptr) {
|
2014-07-22 01:58:24 +00:00
|
|
|
*(reinterpret_cast<void**>(ptr)) = m_free_list;
|
|
|
|
m_free_list = ptr;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|