summaryrefslogtreecommitdiff
path: root/src/code/gamealloc.c
blob: 33ad848a175eafb8f842c8d4baf454284cf5d56d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include "libc64/malloc.h"
#include "libu64/debug.h"
#include "gamealloc.h"
#include "printf.h"

#include "macros.h"

void GameAlloc_Log(GameAlloc* this) {
    GameAllocEntry* iter;

    PRINTF("this = %08x\n", this);

    iter = this->base.next;
    while (iter != &this->base) {
        PRINTF("ptr = %08x size = %d\n", iter, iter->size);
        iter = iter->next;
    }
}

#if DEBUG_FEATURES
void* GameAlloc_MallocDebug(GameAlloc* this, u32 size, const char* file, int line) {
    GameAllocEntry* ptr = SystemArena_MallocDebug(size + sizeof(GameAllocEntry), file, line);

    if (ptr != NULL) {
        ptr->size = size;
        ptr->prev = this->head;
        this->head->next = ptr;
        this->head = ptr;
        ptr->next = &this->base;
        this->base.prev = this->head;
        return ptr + 1;
    } else {
        return NULL;
    }
}
#endif

void* GameAlloc_Malloc(GameAlloc* this, u32 size) {
    GameAllocEntry* ptr = SYSTEM_ARENA_MALLOC(size + sizeof(GameAllocEntry), "../gamealloc.c", 93);

    if (ptr != NULL) {
        ptr->size = size;
        ptr->prev = this->head;
        this->head->next = ptr;
        this->head = ptr;
        ptr->next = &this->base;
        this->base.prev = this->head;
        return ptr + 1;
    } else {
        return NULL;
    }
}

void GameAlloc_Free(GameAlloc* this, void* data) {
    GameAllocEntry* ptr;

    if (data != NULL) {
        ptr = &((GameAllocEntry*)data)[-1];
        LOG_UTILS_CHECK_NULL_POINTER("ptr->prev", ptr->prev, "../gamealloc.c", 120);
        LOG_UTILS_CHECK_NULL_POINTER("ptr->next", ptr->next, "../gamealloc.c", 121);
        ptr->prev->next = ptr->next;
        ptr->next->prev = ptr->prev;
        this->head = this->base.prev;
        SYSTEM_ARENA_FREE(ptr, "../gamealloc.c", 125);
    }
}

void GameAlloc_Cleanup(GameAlloc* this) {
    GameAllocEntry* next = this->base.next;
    GameAllocEntry* cur;

    while (&this->base != next) {
        cur = next;
        next = next->next;
        SYSTEM_ARENA_FREE(cur, "../gamealloc.c", 145);
    }

    this->head = &this->base;
    this->base.next = &this->base;
    this->base.prev = &this->base;
}

void GameAlloc_Init(GameAlloc* this) {
    this->head = &this->base;
    this->base.next = &this->base;
    this->base.prev = &this->base;
}