Wrap libc memory functions in Allocator interface

This commit is contained in:
Abdelrahman Said 2024-03-24 19:25:07 +00:00
parent 9ec123c41b
commit 5b8e9f8be6
2 changed files with 61 additions and 0 deletions

View File

@ -0,0 +1,15 @@
#ifndef MEM_LIBC_H
#define MEM_LIBC_H
#include "mem_allocator.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
Allocator wapp_mem_libc_allocator(void);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // !MEM_LIBC_H

46
mem/src/libc/mem_libc.c Normal file
View File

@ -0,0 +1,46 @@
#include "mem_libc.h"
#include "aliases.h"
#include "mem_allocator.h"
#include <stdlib.h>
#include <string.h>
internal void *mem_libc_alloc(u64 size, void *alloc_obj);
internal void *mem_libc_alloc_aligned(u64 size, u64 alignment, void *alloc_obj);
internal void *mem_libc_realloc(void *ptr, u64 size, void *alloc_obj);
internal void mem_libc_free(void *ptr, void *alloc_obj);
Allocator wapp_mem_libc_allocator(void) {
return (Allocator){
.obj = NULL,
.alloc = mem_libc_alloc,
.alloc_aligned = mem_libc_alloc_aligned,
.realloc = mem_libc_realloc,
.realloc_aligned = NULL,
.free = mem_libc_free,
};
}
internal void *mem_libc_alloc(u64 size, void *alloc_obj) {
return calloc(1, size);
}
internal void *mem_libc_alloc_aligned(u64 size, u64 alignment,
void *alloc_obj) {
void *output = aligned_alloc(alignment, size);
if (output) {
memset(output, 0, size);
}
return output;
}
internal void *mem_libc_realloc(void *ptr, u64 size, void *alloc_obj) {
void *output = realloc(ptr, size);
if (output) {
memset(output, 0, size);
}
return output;
}
internal void mem_libc_free(void *ptr, void *alloc_obj) { free(ptr); }