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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
use core::ptr::NonNull;
use branches::likely;
use crate::Signal;
pub(crate) struct SignalQueue {
first: Option<NonNull<Signal>>,
last: Option<NonNull<Signal>>,
}
unsafe impl Send for SignalQueue {}
impl SignalQueue {
/// Creates a new empty SignalQueue.
#[inline(always)]
pub const fn new() -> Self {
Self {
first: None,
last: None,
}
}
/// Pushes a signal entry into the queue.
/// returns true if the queue was previously empty as a hint for spinning.
///
/// # Safety
///
/// The caller must ensure that the entry lives long enough in the
/// queue or is removed from the queue on drop, caller must guarantee
/// entry.next is None.
#[inline(always)]
pub unsafe fn push(&mut self, entry: NonNull<Signal>) -> bool {
match self.last.replace(entry) {
Some(mut old) => {
// SAFETY: self.last was guaranteed to be valid
unsafe {
old.as_mut().next = Some(entry);
}
false
}
None => {
self.first = Some(entry);
true
}
}
}
/// Pops a signal entry from the front of the queue.
#[inline(always)]
pub fn pop(&mut self) -> Option<NonNull<Signal>> {
// Take the first element; return None if the queue is empty.
let first = self.first?;
// SAFETY: `first` is a valid `NonNull<Signal>` because it came from the queue.
let entry = unsafe { first.as_ref() };
let next = entry.next;
if let Some(next_nn) = next {
// There is a next element; update the head of the queue.
self.first = Some(next_nn);
} else {
// Queue becomes empty; clear both pointers.
self.first = None;
self.last = None;
}
// Return the raw pointer to the popped signal.
Some(first)
}
/// Removes a specific signal entry from the queue.
/// Returns true if the entry was found and removed, false otherwise.
#[inline(always)]
pub fn remove(&mut self, entry: NonNull<Signal>) -> bool {
let mut cur = self.first;
let mut prev: Option<NonNull<Signal>> = None;
while likely(cur.is_some()) {
let mut cur_ptr = cur.unwrap();
if cur_ptr == entry {
if let Some(mut prev) = prev {
unsafe {
// SAFETY: prev is not null and guaranteed to be valid
prev.as_mut().next = cur_ptr.as_mut().next;
}
} else {
self.first = unsafe { cur_ptr.as_mut().next };
}
if self.last == Some(cur_ptr) {
self.last = prev;
}
return true;
}
prev = Some(cur_ptr);
cur = unsafe {
// SAFETY: current is not null and guaranteed to be valid
cur_ptr.as_mut().next
};
}
false
}
}