iroh_blobs/util/
channel.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
pub mod oneshot {
    use std::{
        future::Future,
        pin::Pin,
        task::{Context, Poll},
    };

    pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
        let (tx, rx) = tokio::sync::oneshot::channel::<T>();
        (Sender::Tokio(tx), Receiver::Tokio(rx))
    }

    #[derive(Debug)]
    pub enum Sender<T> {
        Tokio(tokio::sync::oneshot::Sender<T>),
    }

    impl<T> From<Sender<T>> for irpc::channel::oneshot::Sender<T> {
        fn from(sender: Sender<T>) -> Self {
            match sender {
                Sender::Tokio(tx) => tx.into(),
            }
        }
    }

    impl<T> Sender<T> {
        pub fn send(self, value: T) {
            match self {
                Self::Tokio(tx) => tx.send(value).ok(),
            };
        }
    }

    pub enum Receiver<T> {
        Tokio(tokio::sync::oneshot::Receiver<T>),
    }

    impl<T> Future for Receiver<T> {
        type Output = std::result::Result<T, tokio::sync::oneshot::error::RecvError>;

        fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
            match self.as_mut().get_mut() {
                Self::Tokio(rx) => {
                    if rx.is_terminated() {
                        // don't panic when polling a terminated receiver
                        Poll::Pending
                    } else {
                        Future::poll(Pin::new(rx), cx)
                    }
                }
            }
        }
    }
}