pstack.c 1.6 KB

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