EtherLib/memory_pool.h
2022-10-27 21:03:58 +02:00

61 lines
2.1 KiB
C

#ifndef ETHERLIB_MEMORY_POOL_H
#define ETHERLIB_MEMORY_POOL_H
#include <etherlib_options.h>
#include <stdint.h>
/**
* Memory pool state structure.
*/
typedef struct {
uint8_t * p; ///< Pointer to contiguous memory block the pool operates on.
uint32_t totalSize; ///< Total size of the memory pool.
uint32_t blockSize; ///< Single block size.
uint8_t * blockRegistry; ///< Bitfield array in which block allocations are maintained.
uint32_t totalBlocks; ///< Total number of blocks.
uint32_t freeBlocks; ///< Number of free blocks.
} MemoryPool;
/**
* Header inserted at the beginning of each block when allocated. Blocks can
* be forward-chained with this structure used as singly-linked list elements.
*/
typedef struct MemoryPoolBlockHeader_ {
struct MemoryPoolBlockHeader_ * next; ///< Next block in the chain. Zero if chain's last block.
uint8_t * block; ///< Pointer to the data block.
} MemoryPoolBlockHeader;
/**
* Block chain header placed after the first memory block's header.
* Contains fast-accessable information about the full chain.
*/
typedef struct MemoryPoolBlockChainHead_ {
uint32_t totalChainSize; ///< Total memory size allocated in the full chain.
uint16_t chainCntr; ///< Number of chain elements linked together.
uint16_t _spaceholder;
} MemoryPoolBlockChainHead;
/**
* Initialize a new memory pool. MemoryPool object is allocated at the beginning of the given
* area (p).
* @param p memory block the pool is based on
* @param blockSize allocation block size
* @param blockCnt number of available blocks
* @return Pointer to the MemoryPool object handling the newly allocated memory pool, or NULL
* on failure.
*/
MemoryPool * mp_init(uint8_t * p, uint32_t blockSize, uint32_t blockCnt);
/**
* Allocate a memory block chain from memory pool.
* @param mp memory pool the allocation is made from
* @param size requested memory size
* @return pointer to head of allocated memory block chain or NULL on failure
*/
MemoryPoolBlockHeader * mp_alloc(MemoryPool * mp, uint32_t size);
void mp_free(MemoryPool * mp, MemoryPoolBlockHeader )
#endif //ETHERLIB_MEMORY_POOL_H