pstack.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 "debug.h"
  9. #include <linux/kernel.h>
  10. #include <stdlib.h>
  11. struct pstack {
  12. unsigned short top;
  13. unsigned short max_nr_entries;
  14. void *entries[0];
  15. };
  16. struct pstack *pstack__new(unsigned short max_nr_entries)
  17. {
  18. struct pstack *pstack = zalloc((sizeof(*pstack) +
  19. max_nr_entries * sizeof(void *)));
  20. if (pstack != NULL)
  21. pstack->max_nr_entries = max_nr_entries;
  22. return pstack;
  23. }
  24. void pstack__delete(struct pstack *pstack)
  25. {
  26. free(pstack);
  27. }
  28. bool pstack__empty(const struct pstack *pstack)
  29. {
  30. return pstack->top == 0;
  31. }
  32. void pstack__remove(struct pstack *pstack, void *key)
  33. {
  34. unsigned short i = pstack->top, last_index = pstack->top - 1;
  35. while (i-- != 0) {
  36. if (pstack->entries[i] == key) {
  37. if (i < last_index)
  38. memmove(pstack->entries + i,
  39. pstack->entries + i + 1,
  40. (last_index - i) * sizeof(void *));
  41. --pstack->top;
  42. return;
  43. }
  44. }
  45. pr_err("%s: %p not on the pstack!\n", __func__, key);
  46. }
  47. void pstack__push(struct pstack *pstack, void *key)
  48. {
  49. if (pstack->top == pstack->max_nr_entries) {
  50. pr_err("%s: top=%d, overflow!\n", __func__, pstack->top);
  51. return;
  52. }
  53. pstack->entries[pstack->top++] = key;
  54. }
  55. void *pstack__pop(struct pstack *pstack)
  56. {
  57. void *ret;
  58. if (pstack->top == 0) {
  59. pr_err("%s: underflow!\n", __func__);
  60. return NULL;
  61. }
  62. ret = pstack->entries[--pstack->top];
  63. pstack->entries[pstack->top] = NULL;
  64. return ret;
  65. }
  66. void *pstack__peek(struct pstack *pstack)
  67. {
  68. if (pstack->top == 0)
  69. return NULL;
  70. return pstack->entries[pstack->top - 1];
  71. }