bh_list.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include "bh_list.h"
  6. #include "bh_assert.h"
  7. #ifdef BH_DEBUG
  8. /**
  9. * Test whehter a pointer value has exist in given list.
  10. *
  11. * @param list pointer to list.
  12. * @param elem pointer to elem that will be inserted into list.
  13. * @return <code>true</code> if the pointer has been in the list;
  14. * <code>false</code> otherwise.
  15. */
  16. BH_STATIC bool bh_list_is_elem_exist(bh_list *list, void *elem);
  17. #endif
  18. bh_list_status bh_list_init(bh_list *list)
  19. {
  20. if (!list)
  21. return BH_LIST_ERROR;
  22. (list->head).next = NULL;
  23. list->len = 0;
  24. return BH_LIST_SUCCESS;
  25. }
  26. bh_list_status _bh_list_insert(bh_list *list, void *elem)
  27. {
  28. bh_list_link *p = NULL;
  29. if (!list || !elem)
  30. return BH_LIST_ERROR;
  31. #ifdef BH_DEBUG
  32. bh_assert (!bh_list_is_elem_exist(list, elem));
  33. #endif
  34. p = (bh_list_link *) elem;
  35. p->next = (list->head).next;
  36. (list->head).next = p;
  37. list->len++;
  38. return BH_LIST_SUCCESS;
  39. }
  40. bh_list_status bh_list_remove(bh_list *list, void *elem)
  41. {
  42. bh_list_link *cur = NULL;
  43. bh_list_link *prev = NULL;
  44. if (!list || !elem)
  45. return BH_LIST_ERROR;
  46. cur = (list->head).next;
  47. while (cur) {
  48. if (cur == elem) {
  49. if (prev)
  50. prev->next = cur->next;
  51. else
  52. (list->head).next = cur->next;
  53. list->len--;
  54. return BH_LIST_SUCCESS;
  55. }
  56. prev = cur;
  57. cur = cur->next;
  58. }
  59. return BH_LIST_ERROR;
  60. }
  61. uint32 bh_list_length(bh_list *list)
  62. {
  63. return (list ? list->len : 0);
  64. }
  65. void* bh_list_first_elem(bh_list *list)
  66. {
  67. return (list ? (list->head).next : NULL);
  68. }
  69. void* bh_list_elem_next(void *node)
  70. {
  71. return (node ? ((bh_list_link *) node)->next : NULL);
  72. }
  73. #ifdef BH_DEBUG
  74. BH_STATIC bool bh_list_is_elem_exist(bh_list *list, void *elem)
  75. {
  76. bh_list_link *p = NULL;
  77. if (!list || !elem) return false;
  78. p = (list->head).next;
  79. while (p && p != elem) p = p->next;
  80. return (p != NULL);
  81. }
  82. #endif