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
use crate::tx2::tx2_utils::*;
use crate::*;
use std::future::Future;
use futures::future::FutureExt;
use tokio::sync::mpsc::{channel, Receiver, Sender};
pub fn t_chan<T: 'static + Send>(bound: usize) -> (TSender<T>, TReceiver<T>) {
let (s, r) = channel(bound);
(TSender(Arc::new(Share::new(s))), TReceiver(r))
}
pub struct TSender<T: 'static + Send>(Arc<Share<Sender<T>>>);
impl<T: 'static + Send> Clone for TSender<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<T: 'static + Send> PartialEq for TSender<T> {
fn eq(&self, oth: &Self) -> bool {
Arc::ptr_eq(&self.0, &oth.0)
}
}
impl<T: 'static + Send> Eq for TSender<T> {}
impl<T: 'static + Send> std::hash::Hash for TSender<T> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
Arc::as_ptr(&self.0).hash(state);
}
}
impl<T: 'static + Send> TSender<T> {
pub fn send(&self, t: T) -> impl Future<Output = Result<(), T>> + 'static + Send + Unpin {
let sender = match self.0.share_mut(|i, _| Ok(i.clone())) {
Err(_) => return async move { Err(t) }.boxed(),
Ok(s) => s,
};
async move { sender.send(t).await.map_err(|e| e.0) }.boxed()
}
pub fn close_channel(&self) {
let _ = self.0.share_mut(|_, c| {
*c = true;
Ok(())
});
}
}
pub struct TReceiver<T: 'static + Send>(Receiver<T>);
impl<T: 'static + Send> TReceiver<T> {
pub async fn recv(&mut self) -> Option<T> {
self.0.recv().await
}
pub fn poll_recv(&mut self, cx: &mut std::task::Context<'_>) -> std::task::Poll<Option<T>> {
self.0.poll_recv(cx)
}
}
impl<T: 'static + Send> futures::stream::Stream for TReceiver<T> {
type Item = T;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
self.poll_recv(cx)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test(flavor = "multi_thread")]
async fn test_t_chan() {
let (s, r) = t_chan::<u8>(2);
let f = futures::future::try_join_all(vec![s.send(2), s.send(1), s.send(3)]);
let t = metric_task(async move {
let f = futures::future::try_join_all(vec![s.send(5), s.send(4), s.send(6)]);
s.close_channel();
f.await
});
let r = metric_task(async move {
use futures::stream::StreamExt;
KitsuneResult::Ok(r.collect::<Vec<_>>().await)
});
f.await.unwrap();
t.await.unwrap().unwrap();
let mut r = r.await.unwrap().unwrap();
r.sort();
assert_eq!(&[1, 2, 3, 4, 5, 6], r.as_slice());
}
}