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
use crate::*;
use event_listener as el;
use futures::Stream;
use std::{fmt::Debug, sync::Arc};

pub struct Inbox<M> {
    // The underlying channel
    channel: Arc<Channel<M>>,
    // The listener for receiving events
    listener: Option<el::EventListener>,
    // Whether this inbox has signaled halt yet
    signaled_halt: bool,
}

impl<M> Inbox<M> {
    /// This does not increment the inbox_count.
    pub(crate) fn from_channel(channel: Arc<Channel<M>>) -> Self {
        Inbox {
            channel,
            listener: None,
            signaled_halt: false,
        }
    }

    /// This will attempt to receive a message from the [Inbox]. If there is no message, this
    /// will return `None`.
    pub fn try_recv(&mut self) -> Result<Option<M>, RecvError> {
        self.channel.try_recv(&mut self.signaled_halt)
    }

    /// Wait until there is a message in the [Inbox].
    pub fn recv(&mut self) -> Rcv<'_, M> {
        self.channel
            .recv(&mut self.signaled_halt, &mut self.listener)
    }

    gen::send_methods!();
    gen::any_channel_methods!();
}

// It should be fine to share the same event-listener between inbox-stream and
// rcv-future, as long as both clean up properly after returning Poll::Ready.
// (Always remove the event-listener from the Option)
impl<M> Stream for Inbox<M> {
    type Item = Result<M, Halted>;

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        let mut_self = &mut *self.as_mut();
        poll_recv(
            &mut_self.channel,
            &mut mut_self.signaled_halt,
            &mut mut_self.listener,
            cx,
        )
        .map(|res| match res {
            Ok(msg) => Some(Ok(msg)),
            Err(e) => match e {
                RecvError::Halted => Some(Err(Halted)),
                RecvError::ClosedAndEmpty => None,
            },
        })
    }
}

impl<M> Drop for Inbox<M> {
    fn drop(&mut self) {
        self.channel.remove_inbox();
    }
}

impl<M> Debug for Inbox<M> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Inbox")
            .field("listener", &self.listener)
            .field("signaled_halt", &self.signaled_halt)
            .finish()
    }
}