pstack.c 1.4 KB

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