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