2010-05-15 06:05:21 +07:00
|
|
|
/*
|
|
|
|
* Simple pointer stack
|
|
|
|
*
|
|
|
|
* (c) 2010 Arnaldo Carvalho de Melo <acme@redhat.com>
|
|
|
|
*/
|
|
|
|
|
|
|
|
#include "util.h"
|
|
|
|
#include "pstack.h"
|
|
|
|
#include <linux/kernel.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
|
|
|
|
struct pstack {
|
|
|
|
unsigned short top;
|
|
|
|
unsigned short max_nr_entries;
|
|
|
|
void *entries[0];
|
|
|
|
};
|
|
|
|
|
|
|
|
struct pstack *pstack__new(unsigned short max_nr_entries)
|
|
|
|
{
|
2012-11-11 05:41:15 +07:00
|
|
|
struct pstack *pstack = zalloc((sizeof(*pstack) +
|
|
|
|
max_nr_entries * sizeof(void *)));
|
|
|
|
if (pstack != NULL)
|
|
|
|
pstack->max_nr_entries = max_nr_entries;
|
|
|
|
return pstack;
|
2010-05-15 06:05:21 +07:00
|
|
|
}
|
|
|
|
|
2012-11-11 05:41:15 +07:00
|
|
|
void pstack__delete(struct pstack *pstack)
|
2010-05-15 06:05:21 +07:00
|
|
|
{
|
2012-11-11 05:41:15 +07:00
|
|
|
free(pstack);
|
2010-05-15 06:05:21 +07:00
|
|
|
}
|
|
|
|
|
2012-11-11 05:41:15 +07:00
|
|
|
bool pstack__empty(const struct pstack *pstack)
|
2010-05-15 06:05:21 +07:00
|
|
|
{
|
2012-11-11 05:41:15 +07:00
|
|
|
return pstack->top == 0;
|
2010-05-15 06:05:21 +07:00
|
|
|
}
|
|
|
|
|
2012-11-11 05:41:15 +07:00
|
|
|
void pstack__remove(struct pstack *pstack, void *key)
|
2010-05-15 06:05:21 +07:00
|
|
|
{
|
2012-11-11 05:41:15 +07:00
|
|
|
unsigned short i = pstack->top, last_index = pstack->top - 1;
|
2010-05-15 06:05:21 +07:00
|
|
|
|
|
|
|
while (i-- != 0) {
|
2012-11-11 05:41:15 +07:00
|
|
|
if (pstack->entries[i] == key) {
|
2010-05-15 06:05:21 +07:00
|
|
|
if (i < last_index)
|
2012-11-11 05:41:15 +07:00
|
|
|
memmove(pstack->entries + i,
|
|
|
|
pstack->entries + i + 1,
|
2010-05-15 06:05:21 +07:00
|
|
|
(last_index - i) * sizeof(void *));
|
2012-11-11 05:41:15 +07:00
|
|
|
--pstack->top;
|
2010-05-15 06:05:21 +07:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
pr_err("%s: %p not on the pstack!\n", __func__, key);
|
|
|
|
}
|
|
|
|
|
2012-11-11 05:41:15 +07:00
|
|
|
void pstack__push(struct pstack *pstack, void *key)
|
2010-05-15 06:05:21 +07:00
|
|
|
{
|
2012-11-11 05:41:15 +07:00
|
|
|
if (pstack->top == pstack->max_nr_entries) {
|
|
|
|
pr_err("%s: top=%d, overflow!\n", __func__, pstack->top);
|
2010-05-15 06:05:21 +07:00
|
|
|
return;
|
|
|
|
}
|
2012-11-11 05:41:15 +07:00
|
|
|
pstack->entries[pstack->top++] = key;
|
2010-05-15 06:05:21 +07:00
|
|
|
}
|
|
|
|
|
2012-11-11 05:41:15 +07:00
|
|
|
void *pstack__pop(struct pstack *pstack)
|
2010-05-15 06:05:21 +07:00
|
|
|
{
|
|
|
|
void *ret;
|
|
|
|
|
2012-11-11 05:41:15 +07:00
|
|
|
if (pstack->top == 0) {
|
2010-05-15 06:05:21 +07:00
|
|
|
pr_err("%s: underflow!\n", __func__);
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
2012-11-11 05:41:15 +07:00
|
|
|
ret = pstack->entries[--pstack->top];
|
|
|
|
pstack->entries[pstack->top] = NULL;
|
2010-05-15 06:05:21 +07:00
|
|
|
return ret;
|
|
|
|
}
|