summaryrefslogtreecommitdiff
path: root/src/code/listalloc.c
blob: 20cc88e1c170ae70b26f303ce1deebd415f237e6 (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
#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;
    ListAlloc* next;
    
    ptr = SystemArena_MallocDebug(size + sizeof(ListAlloc), "../listalloc.c", 40);
    if (!ptr)
        return NULL;

    next = this->next;

    if (next)
        next->next = ptr;
    
    ptr->prev = next;
    ptr->next = NULL;
    this->next = ptr;

    if (!this->prev)
        this->prev = ptr;

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

void ListAlloc_Free(ListAlloc* this, void* data)
{
    ListAlloc* ptr;

    ptr = &((ListAlloc*)data)[-1];

    if (ptr->prev)
        ptr->prev->next = ptr->next;

    if (ptr->next)
        ptr->next->prev = ptr->prev;

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

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

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

void ListAlloc_FreeAll(ListAlloc* this)
{
    ListAlloc* iter;

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