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
use core::{
marker::PhantomData,
mem,
ops::DerefMut,
};
use std::sync::{
Arc,
Mutex,
};
use ipc_channel::ipc;
use serde::{
self,
Deserialize,
Serialize,
};
use tokio::sync::{
mpsc,
oneshot,
Mutex as AsyncMutex,
};
pub struct Value<T>(pub T);
pub struct Sender<T>(pub mpsc::UnboundedSender<T>);
pub struct Receiver<T>(pub Arc<AsyncMutex<mpsc::UnboundedReceiver<T>>>);
pub struct SenderOnce<T>(pub oneshot::Sender<T>);
pub struct ReceiverOnce<T>(pub oneshot::Receiver<T>);
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct OpaqueReceiver(pub Arc<Mutex<Option<ipc::OpaqueIpcReceiver>>>);
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct OpaqueSender(pub Arc<Mutex<Option<ipc::OpaqueIpcSender>>>);
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct IpcSender<T>
{
pub sender: OpaqueSender,
pub phantom: PhantomData<T>,
}
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct IpcReceiver<T>
{
pub receiver: OpaqueReceiver,
pub phantom: PhantomData<T>,
}
#[derive(Debug)]
pub struct SendError(pub String);
impl<T> Receiver<T>
{
pub async fn recv(&self) -> Option<T>
{
self.0.lock().await.recv().await
}
}
impl<T> SenderOnce<T>
{
pub fn send(
self,
msg: T,
) -> Result<(), SendError>
{
self
.0
.send(msg)
.map_err(|_| SendError(String::from("failed to send")))
}
}
impl<T> ReceiverOnce<T>
{
pub async fn recv(self) -> Result<T, oneshot::error::RecvError>
{
self.0.await
}
pub async fn close(mut self)
{
self.0.close()
}
}
impl<T> IpcSender<T>
where
T: for<'de> Deserialize<'de> + Serialize,
{
pub fn send(
&self,
data: T,
)
{
self.sender.send(data)
}
}
impl<T> IpcReceiver<T>
where
T: for<'de> Deserialize<'de> + Serialize,
{
pub fn recv(&self) -> Option<T>
{
self.receiver.recv()
}
}
impl OpaqueSender
{
pub fn send<T>(
&self,
val: T,
) where
T: for<'de> Deserialize<'de> + Serialize,
{
let mut cell = self.0.lock().unwrap();
let sender1 = mem::take(cell.deref_mut()).unwrap();
let sender2 = sender1.to();
sender2.send(val).unwrap();
let _ = mem::replace(cell.deref_mut(), Some(sender2.to_opaque()));
}
}
impl OpaqueReceiver
{
pub fn recv<T>(&self) -> Option<T>
where
T: for<'de> Deserialize<'de> + Serialize,
{
let mut cell = self.0.lock().unwrap();
let receiver1 = mem::take(cell.deref_mut()).unwrap();
let receiver2 = receiver1.to();
let val = receiver2.recv().ok();
let _ = mem::replace(cell.deref_mut(), Some(receiver2.to_opaque()));
val
}
}