diff --git a/framework/allocator.cpp b/framework/allocator.cpp new file mode 100644 index 0000000..8f47b0a --- /dev/null +++ b/framework/allocator.cpp @@ -0,0 +1,54 @@ +/* + * allocator.cpp + * + * Created on: Jan 28, 2020 + * Author: nnosov + */ + +#include +#include + +#include "allocator.h" + +void heap_free(pst_allocator& alloc, void* buff) +{ + alloc.size -= malloc_usable_size(buff); + free(buff); +} + +void* heap_alloc(pst_allocator& alloc, uint32_t size) +{ + void* buff = malloc(size); + alloc.size += malloc_usable_size(buff); + + return buff; +} + +void* heap_realloc(pst_allocator& alloc, void* buff, uint32_t new_size) +{ + alloc.size -= malloc_usable_size(buff); + void* new_buff = realloc(buff, new_size); + alloc.size += malloc_usable_size(new_buff); + + return new_buff; +} + +void pst_alloc_init(pst_allocator& alloc) +{ + alloc.type = ALLOC_HEAP; + alloc.base = NULL; + alloc.size = 0; + + alloc.alloc = heap_alloc; + alloc.free = heap_free; + alloc.realloc = heap_realloc; + + return; +} + +void pst_allocator_init_custom(pst_allocator& alloc, void* buff, uint32_t size) +{ + // TBD to implement custom allocator + return; +} + diff --git a/framework/allocator.h b/framework/allocator.h new file mode 100644 index 0000000..dbb38a7 --- /dev/null +++ b/framework/allocator.h @@ -0,0 +1,38 @@ +/* + * allocator.h + * + * Created on: Jan 28, 2020 + * Author: nnosov + */ + +#ifndef FRAMEWORK_ALLOCATOR_H_ +#define FRAMEWORK_ALLOCATOR_H_ + +#include +#include + +typedef struct __pst_allocator pst_allocator; + +typedef void* (*pst_alloc_def)(pst_allocator& alloc, uint32_t size); +typedef void (*pst_free_def)(pst_allocator& alloc, void* buff); +typedef void* (*pst_realloc_def)(pst_allocator& alloc, void* buff, uint32_t new_size); + +typedef enum { + ALLOC_HEAP = 1, // use libc memory allocator + ALLOC_CUSTOM // use custom allocator in predefined range of memory +} pst_alloc_type; + +typedef struct __pst_allocator { + int type; + void* base; + uint32_t size; + // routines + pst_alloc_def alloc; + pst_free_def free; + pst_realloc_def realloc; +} pst_allocator; + +void pst_alloc_init(pst_allocator& alloc); +void pst_allocator_init_custom(pst_allocator& alloc, void* buff, uint32_t size); + +#endif /* FRAMEWORK_ALLOCATOR_H_ */