bh_list.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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. #if BH_DEBUG != 0
  7. /**
  8. * Test whether a pointer value has exist in given list.
  9. *
  10. * @param list pointer to list.
  11. * @param elem pointer to elem that will be inserted into list.
  12. * @return <code>true</code> if the pointer has been in the list;
  13. * <code>false</code> otherwise.
  14. */
  15. static bool
  16. bh_list_is_elem_exist(bh_list *list, void *elem);
  17. #endif
  18. bh_list_status
  19. bh_list_init(bh_list *list)
  20. {
  21. if (!list)
  22. return BH_LIST_ERROR;
  23. (list->head).next = NULL;
  24. list->len = 0;
  25. return BH_LIST_SUCCESS;
  26. }
  27. bh_list_status
  28. bh_list_insert(bh_list *list, void *elem)
  29. {
  30. bh_list_link *p = NULL;
  31. if (!list || !elem)
  32. return BH_LIST_ERROR;
  33. #if BH_DEBUG != 0
  34. bh_assert(!bh_list_is_elem_exist(list, elem));
  35. #endif
  36. p = (bh_list_link *)elem;
  37. p->next = (list->head).next;
  38. (list->head).next = p;
  39. list->len++;
  40. return BH_LIST_SUCCESS;
  41. }
  42. bh_list_status
  43. bh_list_remove(bh_list *list, void *elem)
  44. {
  45. bh_list_link *cur = NULL;
  46. bh_list_link *prev = NULL;
  47. if (!list || !elem)
  48. return BH_LIST_ERROR;
  49. cur = (list->head).next;
  50. while (cur) {
  51. if (cur == elem) {
  52. if (prev)
  53. prev->next = cur->next;
  54. else
  55. (list->head).next = cur->next;
  56. list->len--;
  57. return BH_LIST_SUCCESS;
  58. }
  59. prev = cur;
  60. cur = cur->next;
  61. }
  62. return BH_LIST_ERROR;
  63. }
  64. uint32
  65. bh_list_length(bh_list *list)
  66. {
  67. return (list ? list->len : 0);
  68. }
  69. void *
  70. bh_list_first_elem(bh_list *list)
  71. {
  72. return (list ? (list->head).next : NULL);
  73. }
  74. void *
  75. bh_list_elem_next(void *node)
  76. {
  77. return (node ? ((bh_list_link *)node)->next : NULL);
  78. }
  79. #if BH_DEBUG != 0
  80. static bool
  81. bh_list_is_elem_exist(bh_list *list, void *elem)
  82. {
  83. bh_list_link *p = NULL;
  84. if (!list || !elem)
  85. return false;
  86. p = (list->head).next;
  87. while (p && p != elem)
  88. p = p->next;
  89. return (p != NULL);
  90. }
  91. #endif