diff --git a/src/Pool.h b/src/Pool.h new file mode 100644 index 0000000..bb0b468 --- /dev/null +++ b/src/Pool.h @@ -0,0 +1,56 @@ +#ifndef __POOL_H__ +#define __POOL_H__ + +#include +#include + +#include "platform/cm4/InterruptLock.h" + +namespace pinetime +{ + +template +class Pool +{ + union Item + { + uint8_t item[sizeof(T)]; + Item * next; + }; + Item items[sizeT]; + uint8_t map[sizeT]; + +public: + Pool() + { + for(unsigned int i = 0; i < sizeT; i++) { + map[i] = 0; + } + } + + void *alloc() + { + pinetime::platform::cm4::InterruptLock lock; + void * res = nullptr; + for(unsigned int i = 0; i < sizeT; i++) { + if(map[i] == 0) { + map[i] = 0xff; + res = static_cast(items + i); + break; + } + } + return res; + } + + void free(T * ptr) + { + pinetime::platform::cm4::InterruptLock lock; + // ptr is not assumed to be aligned, since the integer based aritmetic provides always the correct index and omits the ramainder. + std::size_t index = (reinterpret_cast(ptr) - reinterpret_cast(items)) / sizeof(Item); + map[index] = 0; + } +}; + +} + +#endif