-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
67 lines (55 loc) · 1.51 KB
/
lib.rs
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
use tokio::time::{timeout, Duration};
pub(crate) use tokio::sync::oneshot::{channel as _res_channel, Sender as _ResTx, Receiver as _ResRx};
pub trait Req {
type Res;
}
pub struct ReqPayload<R: Req> {
pub req: R,
pub res_tx: ResTx<R::Res>,
}
pub struct ResTx<Res> {
res_tx: _ResTx<Res>,
}
pub struct ResRx<Res> {
res_rx: Option<_ResRx<Res>>,
timeout: Option<Duration>,
}
impl<Res> ResTx<Res> {
pub fn send(self, response: Res) -> Result<(), ResSendError<Res>> {
self.res_tx.send(response).map_err(ResSendError)
}
pub fn is_closed(&self) -> bool {
self.res_tx.is_closed()
}
}
impl<Res> ResRx<Res> {
pub async fn recv(&mut self) -> Result<Res, ResRecvError> {
match self.res_rx.take() {
Some(res_rx) => match self.timeout {
Some(duration) => match timeout(duration, res_rx).await {
Ok(response_result) => response_result.map_err(|_| ResRecvError::RecvError),
Err(..) => Err(ResRecvError::RecvTimeout),
},
None => Ok(res_rx.await.map_err(|_| ResRecvError::RecvError)?),
},
None => Err(ResRecvError::RecvError),
}
}
}
#[derive(Debug)]
pub struct ReqSendError<R: Req>(pub R);
#[derive(Debug)]
pub struct ResSendError<Res>(pub Res);
#[derive(Debug)]
pub enum ResRecvError {
RecvError,
RecvTimeout,
}
#[derive(Debug)]
pub enum ReqError<R: Req> {
SendError(R),
RecvError,
RecvTimeout,
}
pub mod bounded;
pub mod unbounded;