zengine-old/engine/3rdparty/zlib/include/zstd/pool.h

51 lines
1012 B
C
Raw Normal View History

2024-03-13 22:29:47 +08:00
#include <concepts>
2024-02-07 16:24:11 +08:00
namespace zstd {
template<std::move_constructible T>
2024-03-13 22:29:47 +08:00
class pool {
using NewFn = std::function<T()>;
2024-02-07 16:24:11 +08:00
protected:
int m_tail;
int m_head;
int m_size;
T* m_buf;
2024-03-13 22:29:47 +08:00
NewFn newT;
2024-02-07 16:24:11 +08:00
public:
2024-03-13 22:29:47 +08:00
~pool() {
2024-02-07 16:24:11 +08:00
reset();
free(m_buf);
}
2024-03-13 22:29:47 +08:00
pool(NewFn newT, int size = 1) : newT(newT), m_tail(0), m_head(0), m_buf((T*)malloc(sizeof(T)* size)), m_size(size) {}
2024-02-07 16:24:11 +08:00
int head() {
return m_head;
}
int tail() {
return m_tail;
}
int count() {
return m_head - m_tail;
}
void reset() {
for (int i = m_tail; i < m_head; i++) {
std::destroy_at(m_buf + (m_tail % m_size));
}
m_tail = 0;
m_head = 0;
}
template<typename... Args>
void release(Args... args) {
2024-03-13 22:29:47 +08:00
if (m_head >= m_tail + m_size) {
return;
2024-02-07 16:24:11 +08:00
}
std::construct_at(m_buf + m_head % m_size, std::forward<Args>(args)...);
2024-03-13 22:29:47 +08:00
m_head++;
2024-02-07 16:24:11 +08:00
};
2024-03-13 22:29:47 +08:00
T acquire() {
if (m_tail == m_head) {
2024-03-14 12:10:37 +08:00
return newT();
2024-02-07 16:24:11 +08:00
}
int tail = m_tail % m_size;
2024-03-13 22:29:47 +08:00
m_tail++;
2024-02-07 16:24:11 +08:00
return std::move(*(m_buf + tail));
};
};
}