2020-02-02 17:59:00 +00:00
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <Arduino.h>
|
|
|
|
#include <assert.h>
|
|
|
|
|
2020-02-02 20:45:32 +00:00
|
|
|
#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 {
|
2020-02-02 20:45:32 +00:00
|
|
|
PointerQueue<T> dead;
|
2020-02-02 17:59:00 +00:00
|
|
|
|
|
|
|
T *buf; // our large raw block of memory
|
|
|
|
|
2020-02-02 20:45:32 +00:00
|
|
|
size_t maxElements;
|
2020-02-02 17:59:00 +00:00
|
|
|
public:
|
2020-02-02 20:45:32 +00:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2020-02-06 16:49:33 +00:00
|
|
|
/// 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) {
|
2020-02-02 20:45:32 +00:00
|
|
|
T *p = dead.dequeuePtr(maxWait);
|
|
|
|
|
|
|
|
if(p)
|
|
|
|
memset(p, 0, sizeof(T));
|
|
|
|
return p;
|
|
|
|
}
|
2020-02-02 17:59:00 +00:00
|
|
|
|
2020-02-02 20:45:32 +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 20:45:32 +00:00
|
|
|
|
2020-02-02 17:59:00 +00:00
|
|
|
/// Return a buffer for use by others
|
2020-02-02 20:45:32 +00:00
|
|
|
void release(T *p) {
|
2020-02-02 17:59:00 +00:00
|
|
|
int res = dead.enqueue(p, 0);
|
|
|
|
assert(res == pdTRUE);
|
2020-02-02 20:45:32 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
};
|
|
|
|
|