From 17d4ee8ff92b9a3cc1aa99739da5af6ab766d99e Mon Sep 17 00:00:00 2001 From: Thomas Klaehn Date: Tue, 14 Apr 2020 12:57:01 +0200 Subject: [PATCH] Add memory pool --- src/Pool.h | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/Pool.h 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