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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
use std::{
cell::{Cell, RefCell},
error::Error,
fmt,
rc::Rc,
task::{Context, Poll, Waker},
};
use super::{block::Queue, semaphore::Semaphore};
pub(crate) fn channel<T, S>(semaphore: S) -> (Tx<T, S>, Rx<T, S>)
where
S: Semaphore,
{
let chan = Rc::new(Chan::new(semaphore));
let tx = Tx::new(chan.clone());
let rx = Rx::new(chan);
(tx, rx)
}
pub(crate) struct Chan<T, S: Semaphore> {
queue: RefCell<Queue<T>>,
pub(crate) semaphore: S,
rx_waker: Cell<Option<Waker>>,
tx_count: Cell<usize>,
}
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum TryRecvError {
Empty,
Disconnected,
}
impl fmt::Display for TryRecvError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
TryRecvError::Empty => "receiving on an empty channel".fmt(fmt),
TryRecvError::Disconnected => "receiving on a closed channel".fmt(fmt),
}
}
}
impl Error for TryRecvError {}
impl<T, S> Chan<T, S>
where
S: Semaphore,
{
pub(crate) fn new(semaphore: S) -> Self {
let queue = RefCell::new(Queue::new());
Self {
queue,
semaphore,
rx_waker: Cell::new(None),
tx_count: Cell::new(0),
}
}
}
impl<T, S> Drop for Chan<T, S>
where
S: Semaphore,
{
fn drop(&mut self) {
let mut queue = self.queue.borrow_mut();
while !queue.is_empty() {
drop(unsafe { queue.pop_unchecked() });
}
unsafe { queue.free_blocks() }
}
}
pub(crate) struct Tx<T, S>
where
S: Semaphore,
{
pub(crate) chan: Rc<Chan<T, S>>,
}
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum SendError {
RxClosed,
}
pub(crate) struct Rx<T, S>
where
S: Semaphore,
{
chan: Rc<Chan<T, S>>,
}
impl<T, S> Tx<T, S>
where
S: Semaphore,
{
pub(crate) fn new(chan: Rc<Chan<T, S>>) -> Self {
chan.tx_count.set(chan.tx_count.get() + 1);
Self { chan }
}
pub(crate) fn send(&self, value: T) -> Result<(), SendError> {
if self.chan.semaphore.is_closed() {
return Err(SendError::RxClosed);
}
unsafe {
self.chan.queue.borrow_mut().push_unchecked(value);
}
if let Some(w) = self.chan.rx_waker.replace(None) {
w.wake();
}
Ok(())
}
pub fn is_closed(&self) -> bool {
self.chan.semaphore.is_closed()
}
pub(crate) fn same_channel(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.chan, &other.chan)
}
}
impl<T, S> Clone for Tx<T, S>
where
S: Semaphore,
{
fn clone(&self) -> Self {
self.chan.tx_count.set(self.chan.tx_count.get() + 1);
Self {
chan: self.chan.clone(),
}
}
}
impl<T, S> Drop for Tx<T, S>
where
S: Semaphore,
{
fn drop(&mut self) {
self.chan.tx_count.set(self.chan.tx_count.get() - 1);
}
}
impl<T, S> Rx<T, S>
where
S: Semaphore,
{
pub(crate) fn new(chan: Rc<Chan<T, S>>) -> Self {
Self { chan }
}
pub(crate) fn try_recv(&mut self) -> Result<T, TryRecvError> {
let mut queue = self.chan.queue.borrow_mut();
if !queue.is_empty() {
let val = unsafe { queue.pop_unchecked() };
self.chan.semaphore.add_permits(1);
return Ok(val);
}
if self.chan.tx_count.get() == 0 {
Err(TryRecvError::Disconnected)
} else {
Err(TryRecvError::Empty)
}
}
pub(crate) fn recv(&mut self, cx: &mut Context<'_>) -> Poll<Option<T>> {
let mut queue = self.chan.queue.borrow_mut();
if !queue.is_empty() {
let val = unsafe { queue.pop_unchecked() };
self.chan.semaphore.add_permits(1);
return Poll::Ready(Some(val));
}
if self.chan.tx_count.get() == 0 {
return Poll::Ready(None);
}
self.chan.rx_waker.replace(Some(cx.waker().clone()));
Poll::Pending
}
pub(crate) fn close(&mut self) {
self.chan.semaphore.close();
}
}
impl<T, S> Drop for Rx<T, S>
where
S: Semaphore,
{
fn drop(&mut self) {
self.chan.semaphore.close();
let mut queue = self.chan.queue.borrow_mut();
let len = queue.len();
while !queue.is_empty() {
drop(unsafe { queue.pop_unchecked() });
}
self.chan.semaphore.add_permits(len);
}
}
#[cfg(test)]
mod tests {
use super::channel;
use crate::semaphore::Inner;
use futures_util::future::poll_fn;
#[monoio::test]
async fn test_chan() {
let semaphore = Inner::new(1);
let (tx, mut rx) = channel::<u32, _>(semaphore);
assert!(tx.send(1).is_ok());
assert_eq!(poll_fn(|cx| rx.recv(cx)).await, Some(1));
rx.close();
assert!(tx.is_closed());
}
}