list.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. #pragma once
  2. #include <common/stddef.h>
  3. #if ARCH(I386) || ARCH(X86_64)
  4. #include <arch/x86_64/asm.h>
  5. #else
  6. #error Arch not supported.
  7. #endif
  8. //链表数据结构
  9. struct List
  10. {
  11. struct List *prev, *next;
  12. };
  13. //初始化循环链表
  14. static inline void list_init(struct List *list)
  15. {
  16. list->next = list;
  17. io_mfence();
  18. list->prev = list;
  19. }
  20. /**
  21. * @brief
  22. * @param entry 给定的节点
  23. * @param node 待插入的节点
  24. **/
  25. static inline void list_add(struct List *entry, struct List *node)
  26. {
  27. node->next = entry->next;
  28. barrier();
  29. node->prev = entry;
  30. barrier();
  31. node->next->prev = node;
  32. barrier();
  33. entry->next = node;
  34. }
  35. /**
  36. * @brief 将node添加到给定的list的结尾(也就是当前节点的前面)
  37. * @param entry 列表的入口
  38. * @param node 待添加的节点
  39. */
  40. static inline void list_append(struct List *entry, struct List *node)
  41. {
  42. struct List *tail = entry->prev;
  43. list_add(tail, node);
  44. }
  45. /**
  46. * @brief 从列表中删除节点
  47. * @param entry 待删除的节点
  48. */
  49. static inline void list_del(struct List *entry)
  50. {
  51. entry->next->prev = entry->prev;
  52. entry->prev->next = entry->next;
  53. }
  54. /**
  55. * @brief
  56. *
  57. */
  58. #define list_del_init(entry) \
  59. list_del(entry); \
  60. list_init(entry);
  61. /**
  62. * @brief 将新的链表结点替换掉旧的链表结点,并使得旧的结点的前后指针均为NULL
  63. *
  64. * @param old 要被替换的结点
  65. * @param new 新的要换上去的结点
  66. */
  67. static inline void list_replace(struct List *old, struct List *new)
  68. {
  69. if (old->prev != NULL)
  70. old->prev->next = new;
  71. new->prev = old->prev;
  72. if (old->next != NULL)
  73. old->next->prev = new;
  74. new->next = old->next;
  75. old->prev = NULL;
  76. old->next = NULL;
  77. }
  78. static inline bool list_empty(struct List *entry)
  79. {
  80. /**
  81. * @brief 判断循环链表是否为空
  82. * @param entry 入口
  83. */
  84. if (entry == entry->next && entry->prev == entry)
  85. return true;
  86. else
  87. return false;
  88. }
  89. /**
  90. * @brief 获取链表的上一个元素
  91. *
  92. * @param entry
  93. * @return 链表的上一个元素
  94. */
  95. static inline struct List *list_prev(struct List *entry)
  96. {
  97. if (entry->prev != NULL)
  98. return entry->prev;
  99. else
  100. return NULL;
  101. }
  102. /**
  103. * @brief 获取链表的下一个元素
  104. *
  105. * @param entry
  106. * @return 链表的下一个元素
  107. */
  108. static inline struct List *list_next(struct List *entry)
  109. {
  110. if (entry->next != NULL)
  111. return entry->next;
  112. else
  113. return NULL;
  114. }