2015-11-18 11:53:01 +00:00
|
|
|
#pragma once
|
|
|
|
|
2017-04-01 09:19:00 +00:00
|
|
|
#include <Common/Arena.h>
|
2020-11-06 17:34:14 +00:00
|
|
|
#include <common/unaligned.h>
|
2015-11-18 11:53:01 +00:00
|
|
|
|
|
|
|
|
|
|
|
namespace DB
|
|
|
|
{
|
|
|
|
|
2015-12-07 16:07:02 +00:00
|
|
|
/** Can allocate memory objects of fixed size with deletion support.
|
2020-11-06 17:34:14 +00:00
|
|
|
* For small `object_size`s allocated no less than pointer size.
|
|
|
|
*/
|
2015-11-18 11:53:01 +00:00
|
|
|
class SmallObjectPool
|
|
|
|
{
|
|
|
|
private:
|
2017-07-21 06:35:58 +00:00
|
|
|
const size_t object_size;
|
2017-04-01 07:20:54 +00:00
|
|
|
Arena pool;
|
2020-11-06 17:34:14 +00:00
|
|
|
char * free_list{};
|
2015-11-18 11:53:01 +00:00
|
|
|
|
|
|
|
public:
|
2020-11-06 17:34:14 +00:00
|
|
|
SmallObjectPool(size_t object_size_)
|
|
|
|
: object_size{std::max(object_size_, sizeof(char *))}
|
2017-04-01 07:20:54 +00:00
|
|
|
{
|
|
|
|
if (pool.size() < object_size)
|
|
|
|
return;
|
|
|
|
|
2020-11-06 17:34:14 +00:00
|
|
|
const size_t num_objects = pool.size() / object_size;
|
|
|
|
free_list = pool.alloc(num_objects * object_size);
|
|
|
|
char * head = free_list;
|
2017-04-01 07:20:54 +00:00
|
|
|
|
2020-11-06 17:34:14 +00:00
|
|
|
for (size_t i = 0; i < num_objects - 1; ++i)
|
2017-04-01 07:20:54 +00:00
|
|
|
{
|
2020-11-06 17:34:14 +00:00
|
|
|
char * next = head + object_size;
|
|
|
|
unalignedStore<char *>(head, next);
|
|
|
|
head = next;
|
2017-04-01 07:20:54 +00:00
|
|
|
}
|
|
|
|
|
2020-11-06 17:34:14 +00:00
|
|
|
unalignedStore<char *>(head, nullptr);
|
2017-04-01 07:20:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
char * alloc()
|
|
|
|
{
|
|
|
|
if (free_list)
|
|
|
|
{
|
2020-11-06 17:34:14 +00:00
|
|
|
char * res = free_list;
|
|
|
|
free_list = unalignedLoad<char *>(free_list);
|
2017-04-01 07:20:54 +00:00
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
|
|
|
return pool.alloc(object_size);
|
|
|
|
}
|
|
|
|
|
2020-11-06 17:34:14 +00:00
|
|
|
void free(char * ptr)
|
2017-04-01 07:20:54 +00:00
|
|
|
{
|
2020-11-06 17:34:14 +00:00
|
|
|
unalignedStore<char *>(ptr, free_list);
|
|
|
|
free_list = ptr;
|
2017-04-01 07:20:54 +00:00
|
|
|
}
|
|
|
|
|
2017-05-07 20:25:26 +00:00
|
|
|
/// The size of the allocated pool in bytes
|
2017-04-01 07:20:54 +00:00
|
|
|
size_t size() const
|
|
|
|
{
|
|
|
|
return pool.size();
|
|
|
|
}
|
2015-11-18 11:53:01 +00:00
|
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
}
|