2015-10-28 17:39:40 +03:00
|
|
|
/*
|
|
|
|
* MemPool.cpp
|
|
|
|
*
|
|
|
|
* Created on: 28 Oct 2015
|
|
|
|
* Author: hieu
|
|
|
|
*/
|
|
|
|
|
2015-10-28 21:11:52 +03:00
|
|
|
#include <boost/foreach.hpp>
|
2015-10-28 17:39:40 +03:00
|
|
|
#include "MemPool.h"
|
|
|
|
#include "util/scoped.hh"
|
2015-12-04 23:32:03 +03:00
|
|
|
#include "legacy/Util2.h"
|
2015-10-28 17:39:40 +03:00
|
|
|
|
2015-12-04 19:08:59 +03:00
|
|
|
using namespace std;
|
|
|
|
|
2015-12-10 23:49:30 +03:00
|
|
|
namespace Moses2
|
|
|
|
{
|
|
|
|
|
2015-10-28 17:39:40 +03:00
|
|
|
MemPool::Page::Page(std::size_t vSize)
|
|
|
|
:size(vSize)
|
|
|
|
{
|
|
|
|
mem = (uint8_t*) util::MallocOrThrow(size);
|
|
|
|
end = mem + size;
|
|
|
|
}
|
|
|
|
|
|
|
|
MemPool::Page::~Page()
|
|
|
|
{
|
2015-12-04 23:27:56 +03:00
|
|
|
free(mem);
|
2015-10-28 17:39:40 +03:00
|
|
|
}
|
|
|
|
////////////////////////////////////////////////////
|
|
|
|
MemPool::MemPool(size_t initSize)
|
|
|
|
:m_currSize(initSize)
|
|
|
|
,m_currPage(0)
|
|
|
|
{
|
2015-12-04 23:27:56 +03:00
|
|
|
Page *page = new Page(m_currSize);
|
|
|
|
m_pages.push_back(page);
|
2015-12-04 19:08:59 +03:00
|
|
|
|
2015-12-04 23:27:56 +03:00
|
|
|
current_ = page->mem;
|
2015-12-04 22:28:40 +03:00
|
|
|
//cerr << "new memory pool";
|
2015-10-28 17:39:40 +03:00
|
|
|
}
|
|
|
|
|
2015-10-28 21:11:52 +03:00
|
|
|
MemPool::~MemPool()
|
|
|
|
{
|
2015-12-04 22:39:09 +03:00
|
|
|
//cerr << "delete memory pool" << endl;
|
2015-12-04 23:27:56 +03:00
|
|
|
RemoveAllInColl(m_pages);
|
2015-10-28 17:39:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2015-12-24 23:11:28 +03:00
|
|
|
uint8_t *MemPool::More(std::size_t size)
|
2015-10-28 17:39:40 +03:00
|
|
|
{
|
|
|
|
++m_currPage;
|
|
|
|
if (m_currPage >= m_pages.size()) {
|
|
|
|
// add new page
|
|
|
|
m_currSize <<= 1;
|
|
|
|
std::size_t amount = std::max(m_currSize, size);
|
|
|
|
|
2015-12-04 23:27:56 +03:00
|
|
|
Page *page = new Page(amount);
|
|
|
|
m_pages.push_back(page);
|
|
|
|
|
|
|
|
uint8_t *ret = page->mem;
|
2015-10-28 17:39:40 +03:00
|
|
|
current_ = ret + size;
|
|
|
|
return ret;
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
// use existing page
|
2015-12-04 23:27:56 +03:00
|
|
|
Page &page = *m_pages[m_currPage];
|
2015-10-28 17:39:40 +03:00
|
|
|
if (size <= page.size) {
|
|
|
|
uint8_t *ret = page.mem;
|
|
|
|
current_ = ret + size;
|
|
|
|
return ret;
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
// recursive call More()
|
|
|
|
return More(size);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-12-04 22:16:59 +03:00
|
|
|
|
|
|
|
void MemPool::Reset()
|
|
|
|
{
|
|
|
|
m_currPage = 0;
|
2015-12-05 00:37:10 +03:00
|
|
|
current_ = m_pages[0]->mem;
|
2015-12-04 22:16:59 +03:00
|
|
|
}
|
|
|
|
|
2015-12-10 23:49:30 +03:00
|
|
|
}
|
|
|
|
|