firmware/src/MemoryPool.h

68 lines
1.7 KiB
C
Raw Normal View History

2020-02-02 17:59:00 +00:00
#pragma once
#include <Arduino.h>
#include <assert.h>
#include "PointerQueue.h"
2020-02-02 17:59:00 +00:00
/**
* A pool based allocator
*
* Eventually this routine will even be safe for ISR use...
*/
template <class T> class MemoryPool {
PointerQueue<T> dead;
2020-02-02 17:59:00 +00:00
T *buf; // our large raw block of memory
size_t maxElements;
2020-02-02 17:59:00 +00:00
public:
MemoryPool(size_t _maxElements): dead(_maxElements), maxElements(_maxElements) {
2020-02-02 17:59:00 +00:00
buf = new T[maxElements];
// prefill dead
for(int i = 0; i < maxElements; i++)
release(&buf[i]);
}
~MemoryPool() {
delete[] buf;
}
/// Return a queable object which has been prefilled with zeros. Panic if no buffer is available
T *allocZeroed() {
T *p = allocZeroed(0);
assert(p); // FIXME panic instead
return p;
}
/// Return a queable object which has been prefilled with zeros - allow timeout to wait for available buffers (you probably don't want this version)
T *allocZeroed(TickType_t maxWait) {
T *p = dead.dequeuePtr(maxWait);
if(p)
memset(p, 0, sizeof(T));
return p;
}
2020-02-02 17:59:00 +00:00
/// Return a queable object which is a copy of some other object
T *allocCopy(const T &src, TickType_t maxWait = portMAX_DELAY) {
T *p = dead.dequeuePtr(maxWait);
if(p)
2020-02-03 18:00:53 +00:00
*p = src;
2020-02-02 17:59:00 +00:00
return p;
}
2020-02-02 17:59:00 +00:00
/// Return a buffer for use by others
void release(T *p) {
2020-02-02 17:59:00 +00:00
int res = dead.enqueue(p, 0);
assert(res == pdTRUE);
assert(p >= buf && (p - buf) < maxElements); // sanity check to make sure a programmer didn't free something that didn't come from this pool
2020-02-02 17:59:00 +00:00
}
};