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
100
101
102
103
104
use core::{
cell::Cell,
future::{self, Future},
pin::Pin,
task::{Context, Poll},
};
use crate::{mutex::Mutex, wake_list::WakeHandle};
pub struct Queue<T = (), U: ?Sized = ()> {
pub(crate) data: Mutex<T>,
pub(crate) user: U,
}
impl<T, U: ?Sized> core::fmt::Debug for Queue<T, U> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Queue").finish_non_exhaustive()
}
}
impl<T, U: ?Sized> core::ops::Deref for Queue<T, U> {
type Target = U;
fn deref(&self) -> &Self::Target {
&self.user
}
}
impl<T, U: ?Sized + Default> Default for Queue<T, U> {
fn default() -> Self {
Self::with(U::default())
}
}
impl<T> Queue<T> {
#[inline]
pub const fn new() -> Self {
Self::with(())
}
}
impl<T, U> Queue<T, U> {
#[inline]
pub const fn with(user_data: U) -> Self {
Self {
data: Mutex::new(),
user: user_data,
}
}
}
impl<T, U: ?Sized> Queue<T, U> {
#[inline(always)]
pub async fn send(&self, message: T) {
Message(self, Cell::new(Some(message)), WakeHandle::new()).await
}
#[inline(always)]
pub async fn recv(&self) -> T {
let mut wh = WakeHandle::new();
future::poll_fn(|cx| self.data.take(cx, &mut wh)).await
}
}
struct Message<'a, T, U: ?Sized>(&'a Queue<T, U>, Cell<Option<T>>, WakeHandle);
#[allow(unsafe_code)]
impl<T, U: ?Sized> Message<'_, T, U> {
#[inline(always)]
fn pin_get_wh(self: Pin<&mut Self>) -> Pin<&mut WakeHandle> {
unsafe { self.map_unchecked_mut(|s| &mut s.2) }
}
}
impl<T, U: ?Sized> Future for Message<'_, T, U> {
type Output = ();
#[inline]
fn poll(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Self::Output> {
let mut wh = WakeHandle::new();
core::mem::swap(&mut wh, self.as_mut().pin_get_wh().get_mut());
let ret = self.0.data.store(&self.1, cx, &mut wh);
core::mem::swap(&mut wh, self.as_mut().pin_get_wh().get_mut());
ret
}
}