一些基础组件
This commit is contained in:
@@ -0,0 +1 @@
|
||||
#include <c_ArenaAllocator.h>
|
||||
@@ -0,0 +1,82 @@
|
||||
#ifndef INCLUDED_C_ARENAALLOCATOR_H
|
||||
#define INCLUDED_C_ARENAALLOCATOR_H
|
||||
|
||||
#ifndef INCLUDED_C_ALLOCATOR_H
|
||||
#include <c_Allocator.h>
|
||||
#endif /*INCLUDED_C_ALLOCATOR_H*/
|
||||
|
||||
|
||||
#ifndef INCLUDED_C_ARENA_H
|
||||
#include <c_Arena.h>
|
||||
#endif /*INCLUDED_C_ARENA_H*/
|
||||
|
||||
|
||||
/* ------------------------------------------------------------------------------------------------------------------ */
|
||||
/* */
|
||||
|
||||
typedef struct {
|
||||
c_Arena_t* arena;
|
||||
}c_ArenaAllocator_t;
|
||||
|
||||
/* ------------------------------------------------------------------------------------------------------------------ */
|
||||
/* */
|
||||
|
||||
C_STATIC_FORCE_INLINE
|
||||
void c_ArenaAllocator_Init(c_ArenaAllocator_t* self, c_Arena_t* arena) {
|
||||
self->arena = arena;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------------------------------------------ */
|
||||
/* */
|
||||
|
||||
|
||||
C_STATIC_FORCE_INLINE
|
||||
C_ALLOCATOR_ALLOC_FN(c_ArenaAllocator_Alloc) {
|
||||
c_ArenaAllocator_t* self = (c_ArenaAllocator_t*)ud;
|
||||
if (!self || !self->arena) return NULL;
|
||||
return c_Arena_Alloc(self->arena, (int)nBytes);
|
||||
}
|
||||
|
||||
C_STATIC_FORCE_INLINE
|
||||
C_ALLOCATOR_FREE_FN(c_ArenaAllocator_Free) {
|
||||
c_ArenaAllocator_t* self = (c_ArenaAllocator_t*)ud;
|
||||
if (!self || !self->arena) return;
|
||||
c_Arena_Free(self->arena, ptr);
|
||||
}
|
||||
|
||||
C_STATIC_FORCE_INLINE
|
||||
C_ALLOCATOR_REALLOC_FN(c_ArenaAllocator_Realloc) {
|
||||
c_ArenaAllocator_t* self = (c_ArenaAllocator_t*)ud;
|
||||
if (!self || !self->arena) return NULL;
|
||||
|
||||
// 情况 1: 指针为空,直接分配新内存
|
||||
if (!ptr) {
|
||||
return c_Arena_Alloc(self->arena, (int)nNewSize);
|
||||
}
|
||||
|
||||
// 情况 2: 新大小为 0,直接释放内存
|
||||
if (nNewSize==0) {
|
||||
c_Arena_Free(self->arena, ptr);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
|
||||
// 情况 3: 伙伴块大小不匹配(需要升级或降级阶数),申请新块
|
||||
return c_Arena_Resize(self->arena, ptr, nOldSize, nNewSize);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------------------------------------------ */
|
||||
/* */
|
||||
|
||||
C_STATIC_FORCE_INLINE
|
||||
c_Allocator_t c_ArenaAllocator_Build(c_ArenaAllocator_t* self, c_Arena_t* arena) {
|
||||
c_ArenaAllocator_Init(self, arena);
|
||||
c_Allocator_t allocator={0};
|
||||
allocator.ud = self;
|
||||
allocator.alloc = c_ArenaAllocator_Alloc;
|
||||
allocator.free = c_ArenaAllocator_Free;
|
||||
allocator.realloc = c_ArenaAllocator_Realloc;
|
||||
return allocator;
|
||||
}
|
||||
|
||||
#endif /*INCLUDED_C_ARENAALLOCATOR_H*/
|
||||
Reference in New Issue
Block a user