lib.rs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #![no_std]
  2. use core::ptr::NonNull;
  3. pub struct List {
  4. head: Link,
  5. count: usize,
  6. }
  7. pub struct Link {
  8. prev: Option<NonNull<Link>>,
  9. next: Option<NonNull<Link>>,
  10. }
  11. impl List {
  12. pub const fn new() -> Self {
  13. Self {
  14. head: Link::new(),
  15. count: 0,
  16. }
  17. }
  18. pub const fn count(&self) -> usize {
  19. self.count
  20. }
  21. pub fn insert(&mut self, node: &mut Link) {
  22. self.head.insert(node);
  23. self.count += 1;
  24. }
  25. pub fn remove(&mut self, node: &mut Link) {
  26. node.remove();
  27. self.count -= 1;
  28. }
  29. pub fn pop(&mut self) -> Option<&mut Link> {
  30. self.head.next_mut().map(|node| {
  31. self.count -= 1;
  32. node.remove();
  33. node
  34. })
  35. }
  36. pub fn is_empty(&self) -> bool {
  37. self.count == 0
  38. }
  39. pub fn head(&mut self) -> Option<&mut Link> {
  40. self.head.next_mut()
  41. }
  42. }
  43. impl Link {
  44. pub const fn new() -> Self {
  45. Self {
  46. prev: None,
  47. next: None,
  48. }
  49. }
  50. pub fn insert(&mut self, node: &mut Self) {
  51. unsafe {
  52. let insert_node = NonNull::new(&raw mut *node);
  53. if let Some(next) = self.next {
  54. (*next.as_ptr()).prev = insert_node;
  55. }
  56. node.next = self.next;
  57. node.prev = NonNull::new(&raw mut *self);
  58. self.next = insert_node;
  59. }
  60. }
  61. pub fn remove(&mut self) {
  62. if let Some(next) = self.next {
  63. unsafe { (*next.as_ptr()).prev = self.prev };
  64. }
  65. if let Some(prev) = self.prev {
  66. unsafe { (*prev.as_ptr()).next = self.next };
  67. }
  68. self.prev = None;
  69. self.next = None;
  70. }
  71. pub fn next(&self) -> Option<&Self> {
  72. self.next.map(|node| unsafe { &*node.as_ptr() })
  73. }
  74. pub fn next_mut(&mut self) -> Option<&mut Self> {
  75. self.next.map(|node| unsafe { &mut *node.as_ptr() })
  76. }
  77. }
  78. #[macro_export]
  79. macro_rules! container_of {
  80. ($ptr:expr, $type:ty, $($f:tt)*) => {{
  81. let ptr = $ptr as *const _ as *const u8;
  82. let offset: usize = ::core::mem::offset_of!($type, $($f)*);
  83. ::core::ptr::NonNull::new_unchecked(ptr.sub(offset) as *mut $type)
  84. }}
  85. }