Skip to content

Instantly share code, notes, and snippets.

@nothke
Created September 19, 2020 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nothke/0d6017ef87a31e4000cd0185524296a9 to your computer and use it in GitHub Desktop.
Save nothke/0d6017ef87a31e4000cd0185524296a9 to your computer and use it in GitHub Desktop.
template <typename T>
class SwappingPool
{
public:
const size_t size;
private:
size_t headi{ 0 };
T* data;
public:
SwappingPool(size_t size)
: size(size)
{
data = new T[size];
}
T& operator [] (size_t i)
{
return data[i];
}
T& get()
{
if (headi == size)
return data[0];
return data[headi++]; // increments after get
}
void release(T& e)
{
release(&e);
}
void release(T* eptr)
{
if (headi == 0)
return;
headi--;
if (headi == 0)
return;
ptrdiff_t index = eptr - &data[0];
// put last element into the one on the index
//data[index] = data[headi];
memcpy(&data[index], &data[headi], sizeof(T));
}
const bool isFull() const
{
return headi >= size;
}
const size_t aliveCount() const { return headi; }
~SwappingPool()
{
delete[] data;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment