pstack.c 1.7 KB

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