summaryrefslogtreecommitdiff
path: root/src/code/listalloc.c
blob: 7560c20c6490fcec46fdf82e045c5516f1fb0176 (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
#include "global.h"

ListAlloc* ListAlloc_Init(ListAlloc* this) {
    this->prev = NULL;
    this->next = NULL;
    return this;
}

void* ListAlloc_Alloc(ListAlloc* this, u32 size) {
    ListAlloc* ptr = SYSTEM_ARENA_MALLOC(size + sizeof(ListAlloc), "../listalloc.c", 40);
    ListAlloc* next;

    if (ptr == NULL) {
        return NULL;
    }

    next = this->next;
    if (next != NULL) {
        next->next = ptr;
    }

    ptr->prev = next;
    ptr->next = NULL;
    this->next = ptr;

    if (this->prev == NULL) {
        this->prev = ptr;
    }

    return (u8*)ptr + sizeof(ListAlloc);
}

void ListAlloc_Free(ListAlloc* this, void* data) {
    ListAlloc* ptr = &((ListAlloc*)data)[-1];

    if (ptr->prev != NULL) {
        ptr->prev->next = ptr->next;
    }

    if (ptr->next != NULL) {
        ptr->next->prev = ptr->prev;
    }

    if (this->prev == ptr) {
        this->prev = ptr->next;
    }

    if (this->next == ptr) {
        this->next = ptr->prev;
    }

    SYSTEM_ARENA_FREE(ptr, "../listalloc.c", 72);
}

void ListAlloc_FreeAll(ListAlloc* this) {
    ListAlloc* iter = this->prev;

    while (iter != NULL) {
        ListAlloc_Free(this, (u8*)iter + sizeof(ListAlloc));
        iter = this->prev;
    }
}