list.c 1.41 KB
Newer Older
Jacob Vosmaer's avatar
Jacob Vosmaer committed
1 2
#include "list.h"

3
uint8_t
4
l_succ(struct list *l, uint8_t x)
5 6 7 8
{
	return l->array[x];
}

Jacob Vosmaer's avatar
Jacob Vosmaer committed
9 10 11
void
l_push(struct list *l, uint8_t x)
{
12 13 14 15 16
	if (x >= l->sup) {
		return;
	}

	l_delete(l, x);
Jacob Vosmaer's avatar
Jacob Vosmaer committed
17 18 19 20
	l->array[x] = l->head;
	l->head = x;
}

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
void
l_append(struct list *l, uint8_t x)
{
	if (x >= l->sup) {
		return;
	}

	if (l_empty(l)) {
		l_push(l, x);
		return;
	}

	l_delete(l, x);

	uint8_t i = l->head;
	for (; l_succ(l, i) != l->sup; i = l_succ(l, i)) {
		// nop
	}

	l->array[i] = x;
	l->array[x] = l->sup;
}


Jacob Vosmaer's avatar
Jacob Vosmaer committed
45 46 47
void
l_delete(struct list *l, uint8_t x)
{
48 49 50 51
	if (l_empty(l) || x >= l->sup) {
		return;
	}

Jacob Vosmaer's avatar
Jacob Vosmaer committed
52
	if (l->head == x) {
53
		l->head = l_succ(l, x);
Jacob Vosmaer's avatar
Jacob Vosmaer committed
54 55 56
		return;
	}

57 58 59
	for (uint8_t i = l->head; i != l->sup; i = l_succ(l, i)) {
		if (l_succ(l, i) == x) {
			l->array[i] = l_succ(l, x);
Jacob Vosmaer's avatar
Jacob Vosmaer committed
60 61 62 63 64
			return;
		}
	}
}

65 66 67 68 69 70
uint8_t
l_first(struct list *l)
{
	return l->head;
}

Jacob Vosmaer's avatar
Jacob Vosmaer committed
71 72 73
uint8_t
l_last(struct list *l)
{
74 75
	if (l_empty(l)) {
		return l->sup;
Jacob Vosmaer's avatar
Jacob Vosmaer committed
76 77
	}

78
	uint8_t x = l->head;
79
	for (; l_succ(l, x) != l->sup; x = l_succ(l, x)) {
Jacob Vosmaer's avatar
Jacob Vosmaer committed
80 81 82 83 84 85 86 87 88 89
		// walk the list
	}
	return x;
}

void
l_flush(struct list *l)
{
	l->head = l->sup;
}
90 91 92 93 94 95

uint8_t
l_empty(struct list *l)
{
	return l->head == l->sup;
}
96 97 98

uint8_t
l_contains(struct list *l, uint8_t x)
99 100 101 102 103 104
{
	return l_index(l, x) < l->sup;
}

uint8_t
l_index(struct list *l, uint8_t x)
105 106
{
	if (x >= l->sup) {
107
		return l->sup;
108 109
	}

110 111
	uint8_t j = 0;
	for (uint8_t i = l->head; i != l->sup; i = l_succ(l, i)) {
112
		if (i == x) {
113
			return j;
114
		}
115
		j++;
116 117
	}

118
	return l->sup;
119
}