cbase 1.50.0
C/C++ Static Template
Loading...
Searching...
No Matches
mem_allocator.h
Go to the documentation of this file.
1
49
50#ifndef MEM_ALLOCATOR_H
51#define MEM_ALLOCATOR_H
52
53#include "base/base_macros.h"
54#include "base/base_types.h"
55
57
63
71
80typedef void *(*MemAllocFn)(MemAllocMode mode, void *ctx, usize size, void *old_ptr);
81
87
89
104function inline void *
106{
107 return alloc->fn(MEM_ALLOC_MODE_ALLOC, alloc->ctx, size, NULL);
108}
109
134function inline void *
135mem_realloc(MemAllocator *alloc, void *old_ptr, usize old_size, usize new_size)
136{
137 // A proper realloc implementation using the vtable
138 void *new_ptr = alloc->fn(MEM_ALLOC_MODE_REALLOC, alloc->ctx, new_size, old_ptr);
139 if (new_ptr != NULL && new_ptr != old_ptr) {
140 MEM_COPY(new_ptr, old_ptr, MIN(old_size, new_size));
141 if (old_size > 0) {
142 alloc->fn(MEM_ALLOC_MODE_FREE, alloc->ctx, old_size, old_ptr);
143 }
144 }
145 return new_ptr;
146}
147
165function inline void
166mem_free(MemAllocator *alloc, void *ptr, usize size)
167{
168 alloc->fn(MEM_ALLOC_MODE_FREE, alloc->ctx, size, ptr);
169}
170
180function inline void
182{
183 alloc->fn(MEM_ALLOC_MODE_FREE_ALL, alloc->ctx, 0, NULL);
184}
185
187
193
208#define MAKE(type, count, alloc) ((type *)mem_alloc((alloc), sizeof(type) * (count)))
209
223#define MAKE_STRUCT(type, alloc) ((type *)mem_alloc((alloc), sizeof(type)))
224
235#define RELEASE(type, count, ptr, alloc) mem_free((alloc), (ptr), sizeof(type) * (count))
236
238
240
241#endif // MEM_ALLOCATOR_H
Context detection, compiler abstractions, utility macros, and data structures.
Core fixed-width type aliases and memory size constants.
#define function
File-scoped function (invisible to the linker).
#define C_LINKAGE_END
Closes a C linkage block for C++ compilers (Empty in C).
#define C_LINKAGE_BEGIN
Opens a C linkage block for C++ compilers (Empty in C).
void *(* MemAllocFn)(MemAllocMode mode, void *ctx, usize size, void *old_ptr)
The core function signature for an abstract allocator.
MemAllocMode
Describes the type of memory operation being requested.
function void mem_free_all(MemAllocator *alloc)
Clears the entire allocator in one shot (e.g. arena reset, pool reset).
function void mem_free(MemAllocator *alloc, void *ptr, usize size)
Frees a previously allocated block through the allocator.
function void * mem_alloc(MemAllocator *alloc, usize size)
Allocator Helper Functions.
function void * mem_realloc(MemAllocator *alloc, void *old_ptr, usize old_size, usize new_size)
Resizes a previously allocated block through the allocator.
@ MEM_ALLOC_MODE_FREE_ALL
@ MEM_ALLOC_MODE_ALLOC
@ MEM_ALLOC_MODE_REALLOC
@ MEM_ALLOC_MODE_FREE
#define MEM_COPY(dst, src, size)
Copies memory using memmove (overlap-safe).
size_t usize
Definition base_types.h:68
#define MIN(a, b)
Returns the minimum of two values (Standard C fallback).
An abstract allocator interface.
MemAllocFn fn