Commit | Line | Data |
---|---|---|
3e1bbdc3 ACM |
1 | /* |
2 | * Simple pointer stack | |
3 | * | |
4 | * (c) 2010 Arnaldo Carvalho de Melo <acme@redhat.com> | |
5 | */ | |
6 | ||
7 | #include "util.h" | |
8 | #include "pstack.h" | |
84f5d36f | 9 | #include "debug.h" |
3e1bbdc3 ACM |
10 | #include <linux/kernel.h> |
11 | #include <stdlib.h> | |
12 | ||
13 | struct pstack { | |
14 | unsigned short top; | |
15 | unsigned short max_nr_entries; | |
16 | void *entries[0]; | |
17 | }; | |
18 | ||
19 | struct pstack *pstack__new(unsigned short max_nr_entries) | |
20 | { | |
61e94515 ACM |
21 | struct pstack *pstack = zalloc((sizeof(*pstack) + |
22 | max_nr_entries * sizeof(void *))); | |
23 | if (pstack != NULL) | |
24 | pstack->max_nr_entries = max_nr_entries; | |
25 | return pstack; | |
3e1bbdc3 ACM |
26 | } |
27 | ||
61e94515 | 28 | void pstack__delete(struct pstack *pstack) |
3e1bbdc3 | 29 | { |
61e94515 | 30 | free(pstack); |
3e1bbdc3 ACM |
31 | } |
32 | ||
61e94515 | 33 | bool pstack__empty(const struct pstack *pstack) |
3e1bbdc3 | 34 | { |
61e94515 | 35 | return pstack->top == 0; |
3e1bbdc3 ACM |
36 | } |
37 | ||
61e94515 | 38 | void pstack__remove(struct pstack *pstack, void *key) |
3e1bbdc3 | 39 | { |
61e94515 | 40 | unsigned short i = pstack->top, last_index = pstack->top - 1; |
3e1bbdc3 ACM |
41 | |
42 | while (i-- != 0) { | |
61e94515 | 43 | if (pstack->entries[i] == key) { |
3e1bbdc3 | 44 | if (i < last_index) |
61e94515 ACM |
45 | memmove(pstack->entries + i, |
46 | pstack->entries + i + 1, | |
3e1bbdc3 | 47 | (last_index - i) * sizeof(void *)); |
61e94515 | 48 | --pstack->top; |
3e1bbdc3 ACM |
49 | return; |
50 | } | |
51 | } | |
52 | pr_err("%s: %p not on the pstack!\n", __func__, key); | |
53 | } | |
54 | ||
61e94515 | 55 | void pstack__push(struct pstack *pstack, void *key) |
3e1bbdc3 | 56 | { |
61e94515 ACM |
57 | if (pstack->top == pstack->max_nr_entries) { |
58 | pr_err("%s: top=%d, overflow!\n", __func__, pstack->top); | |
3e1bbdc3 ACM |
59 | return; |
60 | } | |
61e94515 | 61 | pstack->entries[pstack->top++] = key; |
3e1bbdc3 ACM |
62 | } |
63 | ||
61e94515 | 64 | void *pstack__pop(struct pstack *pstack) |
3e1bbdc3 ACM |
65 | { |
66 | void *ret; | |
67 | ||
61e94515 | 68 | if (pstack->top == 0) { |
3e1bbdc3 ACM |
69 | pr_err("%s: underflow!\n", __func__); |
70 | return NULL; | |
71 | } | |
72 | ||
61e94515 ACM |
73 | ret = pstack->entries[--pstack->top]; |
74 | pstack->entries[pstack->top] = NULL; | |
3e1bbdc3 ACM |
75 | return ret; |
76 | } |