45 lines
1.7 KiB
C
45 lines
1.7 KiB
C
#ifndef _LIBC_STDLIB__MEM_
|
|
#define _LIBC_STDLIB__MEM_
|
|
|
|
#include <stddef.h>
|
|
|
|
struct mem_node {
|
|
size_t free; // Amount of free space in this node. When equal to size, the entire node is free.
|
|
|
|
size_t size; // Total size of this memory node.
|
|
|
|
struct mem_node* last; // Pointer to the previous memory node in the linked list.
|
|
struct mem_node* next; // Pointer to the next memory node in the linked list.
|
|
};
|
|
|
|
struct mem_block {
|
|
size_t size; // Size of the allocated memory block.
|
|
};
|
|
|
|
// Macro to get a pointer to the user data area from a mem_node pointer.
|
|
// This is done by adding the size of the mem_node structure to the mem_node pointer.
|
|
#define GET_MEM_NODE_PTR(node) (char*)((char*)(node) + sizeof(struct mem_node))
|
|
|
|
// Macro to check if a memory node is completely free.
|
|
#define MEM_NODE_IS_FREE(node) (node->free == node->size)
|
|
|
|
// Macro to get the amount of used memory in a memory node.
|
|
#define GET_MEM_NODE_USED_MEM(node) (node->size - node->free)
|
|
|
|
// Macro to get a pointer to the mem_node structure from a user data pointer.
|
|
// This is done by subtracting the size of the mem_node structure from the user data pointer.
|
|
#define GET_MEM_NODE_HEADER(ptr) ((struct mem_node*)((char*)ptr - sizeof(struct mem_node)))
|
|
|
|
// Macro to check if two adjacent memory nodes are in the same block.
|
|
// Checks if the end of the left node's allocated space is the start of the right node.
|
|
#define MEM_NODES_ARE_IN_ONE_BLOCK(left, right) (GET_MEM_NODE_PTR(left) + left->size == (char*)right)
|
|
|
|
// Size of the blocks allocated at a time.
|
|
#define ALLOC_BLOCK_SIZE 4096
|
|
|
|
// Static pointer to the first memory node in the linked list.
|
|
// This acts as the head of the memory pool.
|
|
static struct mem_node* __mem_node = NULL;
|
|
|
|
#endif // _LIBC_STDLIB_MEM_
|