1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#![no_std]
use ach_cell::Cell;
use core::marker::PhantomPinned;
use core::ops::Deref;
use core::ptr;
use core::sync::atomic::{AtomicPtr, Ordering::SeqCst};
pub struct Node<T: 'static> {
val: Cell<T>,
next: AtomicPtr<Node<T>>,
_pin: PhantomPinned,
}
impl<T> Node<T> {
pub const fn new() -> Self {
Self {
val: Cell::new(),
next: AtomicPtr::new(ptr::null_mut()),
_pin: PhantomPinned,
}
}
pub const fn new_with(val: T) -> Self {
Self {
val: Cell::new_with(val),
next: AtomicPtr::new(ptr::null_mut()),
_pin: PhantomPinned,
}
}
}
impl<T> Deref for Node<T> {
type Target = Cell<T>;
fn deref(&self) -> &Self::Target {
&self.val
}
}
pub struct LinkedList<T: 'static> {
root: AtomicPtr<Node<T>>,
}
impl<T> LinkedList<T> {
pub const fn new() -> Self {
Self {
root: AtomicPtr::new(ptr::null_mut()),
}
}
pub fn push(&self, node: &'static mut Node<T>) {
if !node.next.load(SeqCst).is_null() {
return;
}
let _ = self.root.fetch_update(SeqCst, SeqCst, |old| {
node.next.store(old, SeqCst);
Some(node)
});
}
pub fn iter(&self) -> LinkedIterator<T> {
LinkedIterator {
next: unsafe { self.root.swap(ptr::null_mut(), SeqCst).as_mut() },
}
}
}
pub struct LinkedIterator<T: 'static> {
next: Option<&'static mut Node<T>>,
}
impl<T> Iterator for LinkedIterator<T> {
type Item = &'static mut Node<T>;
fn next(&mut self) -> Option<Self::Item> {
let ret = self.next.take()?;
self.next = unsafe { ret.next.swap(ptr::null_mut(), SeqCst).as_mut() };
Some(ret)
}
}