lib: add basic stack type

I can't believe I've made it this far without needing one
This commit is contained in:
Michael Shaw 2024-01-30 22:08:36 -05:00
commit a6b7d9b42d
3 changed files with 85 additions and 0 deletions

24
include/lib/stack.h Normal file
View file

@ -0,0 +1,24 @@
/* SPDX-License-Identifier: GPL-2.0-only */
#ifndef _STACK_H_
#define _STACK_H_
#include <stddef.h>
struct stack_node {
struct stack_node *next;
void *data;
};
struct stack {
struct stack_node *top;
size_t size;
};
void stack_init();
struct stack *stack_create();
void stack_destroy(struct stack *stack);
void stack_push(struct stack *stack, void *data);
void *stack_pop(struct stack *stack);
void *stack_peek(struct stack *stack);
#endif /* _STACK_H_ */

View file

@ -16,6 +16,8 @@
#include <dev/ahci.h>
#include <dev/apic.h>
#include <lib/stack.h>
#include <fs/vfs.h>
#define LIMINE_INTERNAL_MODULE_REQUIRED (1 << 0)
@ -124,6 +126,7 @@ void kmain()
char kmem[one_gb] ALIGN(0x1000);
mem_early_init(kmem, one_gb);
stack_init();
gdt_init();
idt_init();

View file

@ -1,3 +1,61 @@
/* SPDX-License-Identifier: GPL-2.0-only */
#include <kernel/slab.h>
#include <lib/stack.h>
slab_t *stack_slab;
void stack_init()
{
stack_slab = slab_create(sizeof(struct stack_node), 16 * KB, 0);
}
struct stack *stack_create()
{
struct stack *stack = kmalloc(sizeof(struct stack), ALLOC_KERN);
if (!stack)
return NULL;
stack->top = NULL;
return stack;
}
void stack_push(struct stack *stack, void *data)
{
struct stack_node *node = slab_alloc(stack_slab);
if (!node)
return;
node->data = data;
node->next = stack->top;
stack->top = node;
}
void *stack_pop(struct stack *stack)
{
if (!stack->top)
return NULL;
struct stack_node *node = stack->top;
stack->top = node->next;
void *data = node->data;
slab_free(stack_slab, node);
return data;
}
void *stack_peek(struct stack *stack)
{
if (!stack->top)
return NULL;
return stack->top->data;
}
void stack_destroy(struct stack *stack)
{
while (stack->top)
stack_pop(stack);
kfree(stack);
}