aboutsummaryrefslogtreecommitdiff
path: root/libs/libc/stack.c
blob: 6f1670964b92163510fe08a46fc46ac43d3427ca (plain) (blame)
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
// MIT License, Copyright (c) 2020 Marvin Borner

#include <def.h>
#include <mem.h>
#include <stack.h>

static int nonce = 0;

struct stack *stack_new(void)
{
	struct stack *stack = malloc(sizeof(*stack));
	stack->tail = NULL;
	return stack;
}

void stack_destroy(struct stack *stack)
{
	struct stack_node *iterator = stack->tail;
	while (iterator) {
		if (!iterator->prev) {
			free(iterator);
			break;
		}
		iterator = iterator->prev;
		free(iterator->next);
	}
	stack->tail = NULL;
	free(stack);
	stack = NULL;
}

static struct stack_node *stack_new_node(void)
{
	struct stack_node *node = malloc(sizeof(*node));
	node->data = NULL;
	node->prev = NULL;
	node->next = NULL;
	node->nonce = nonce++;
	return node;
}

NONNULL static u32 stack_push_bot_node(struct stack *stack, struct stack_node *node)
{
	if (stack->tail) {
		struct stack_node *iterator = stack->tail;
		while (iterator) {
			if (!iterator->prev)
				break;
			iterator = iterator->prev;
		}
		iterator->prev = node;
		node->next = iterator;
	} else {
		stack->tail = node;
	}

	return 1;
}

NONNULL static u32 stack_push_node(struct stack *stack, struct stack_node *node)
{
	if (stack->tail) {
		stack->tail->next = node;
		node->prev = stack->tail;
		stack->tail = node;
	} else {
		stack->tail = node;
	}

	return 1;
}

u32 stack_empty(struct stack *stack)
{
	return !stack->tail;
}

u32 stack_push_bot(struct stack *stack, void *data)
{
	struct stack_node *node = stack_new_node();
	node->data = data;
	return stack_push_bot_node(stack, node);
}

u32 stack_push(struct stack *stack, void *data)
{
	struct stack_node *node = stack_new_node();
	node->data = data;
	return stack_push_node(stack, node);
}

void *stack_pop(struct stack *stack)
{
	if (!stack->tail)
		return NULL;

	struct stack_node *prev = stack->tail;

	if (stack->tail->prev)
		stack->tail->prev->next = NULL;
	stack->tail = stack->tail->prev;

	void *data = prev->data;
	free(prev);
	return data;
}

void *stack_peek(struct stack *stack)
{
	if (!stack->tail)
		return NULL;

	return stack->tail->data;
}

void stack_clear(struct stack *stack)
{
	while (stack_pop(stack))
		;
}