66 lines
1.2 KiB
C++
66 lines
1.2 KiB
C++
/*
|
||
* Pool.hpp
|
||
*
|
||
* Created on: 12 дек. 2019 г.
|
||
* Author: LeonidTitov
|
||
*/
|
||
|
||
#ifndef LIB_COMMON_POOL_HPP_
|
||
#define LIB_COMMON_POOL_HPP_
|
||
|
||
#include <cstddef>
|
||
#include <bitset>
|
||
|
||
namespace common {
|
||
|
||
template<typename Item>
|
||
struct PoolInterface {
|
||
virtual Item * get() = 0;
|
||
virtual void free( Item * & ) = 0;
|
||
virtual ~PoolInterface() = default;
|
||
};
|
||
|
||
template<typename Item, std::size_t quantity>
|
||
struct Pool : public PoolInterface<Item> {
|
||
|
||
static const std::size_t size = quantity;
|
||
typedef Item ItemType;
|
||
|
||
Item * get();
|
||
void free( Item * & );
|
||
|
||
virtual ~Pool() noexcept {}
|
||
private:
|
||
Item pool[size];
|
||
typedef std::bitset<size> Infos;
|
||
Infos info;
|
||
};
|
||
|
||
}
|
||
|
||
template<typename Item, std::size_t quantity>
|
||
inline Item * common::Pool<Item, quantity>::get() {
|
||
|
||
for( std::size_t index = 0; index < size; ++index )
|
||
if( not info.test(index) ) {
|
||
info.set(index);
|
||
return &pool[index];
|
||
}
|
||
|
||
return nullptr;
|
||
}
|
||
|
||
template<typename Item, std::size_t quantity>
|
||
inline void common::Pool<Item, quantity>::free( Item * & item ) {
|
||
|
||
std::size_t index = item - pool;
|
||
|
||
if( info.test(index) ) {
|
||
item = nullptr;
|
||
info.reset(index);
|
||
}
|
||
|
||
}
|
||
|
||
#endif /* LIB_COMMON_POOL_HPP_ */
|