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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
use async_channel::{TryRecvError, TrySendError};

#[derive(Clone)]
pub struct BidirectionalAsyncChannel<T> {
    incoming: async_channel::Receiver<T>,
    outgoing: async_channel::Sender<T>,
}

impl<T> BidirectionalAsyncChannel<T> {
    /// Creates a pair of connected Peers without limitations on
    /// how many messages can be buffered.
    pub fn create_unbounded_pair() -> (Self, Self) {
        Self::create_pair(async_channel::unbounded(), async_channel::unbounded())
    }

    /// Creates a pair of connected Peers with a limited capacity
    /// for many messages can be buffered in either direction.
    pub fn create_bounded_pair(capacity: usize) -> (Self, Self) {
        Self::create_pair(
            async_channel::bounded(capacity),
            async_channel::bounded(capacity),
        )
    }

    /// Sends a message to the connected peer.
    ///
    /// If the send buffer is full, this method waits until there is
    /// space for a message.
    ///
    /// If the peer is disconnected, this method returns an error.
    #[inline]
    pub fn send(&self, message: T) -> async_channel::Send<'_, T> {
        self.outgoing.send(message)
    }

    /// Receives a message from the connected peer.
    ///
    /// If there is no pending messages, this method waits until there is a
    /// message.
    ///
    /// If the peer is disconnected, this method receives a message or returns
    /// an error if there are no more messages.
    #[inline]
    pub fn recv(&self) -> async_channel::Recv<'_, T> {
        self.incoming.recv()
    }

    /// Attempts to send a message to the connected peer.
    #[inline]
    pub fn try_send(&self, message: T) -> Result<(), TrySendError<T>> {
        self.outgoing.try_send(message)
    }

    /// Attempts to receive a message from the connected peer.
    #[inline]
    pub fn try_recv(&self) -> Result<T, TryRecvError> {
        self.incoming.try_recv()
    }

    /// Returns true if the associated peer is still connected.
    pub fn is_connected(&self) -> bool {
        !self.incoming.is_closed() && !self.outgoing.is_closed()
    }

    /// Disconnects the paired Peers from either end. Any future attempts
    /// to send messages in either direction will fail, but any messages
    /// not yet recieved.
    ///
    /// If the Peer, or it's constituent channels were cloned, all of the
    /// cloned instances will appear disconnected.
    pub fn disconnect(&self) {
        self.outgoing.close();
        self.incoming.close();
    }

    /// Gets the raw sender for the peer.
    pub fn sender(&self) -> async_channel::Sender<T> {
        self.outgoing.clone()
    }

    /// Gets the raw reciever for the peer.
    pub fn reciever(&self) -> async_channel::Receiver<T> {
        self.incoming.clone()
    }

    /// The number of messages that are currently buffered in the
    /// send queue. Returns 0 if the Peer is disconnected.
    pub fn pending_send_count(&self) -> usize {
        self.outgoing.len()
    }

    /// The number of messages that are currently buffered in the
    /// recieve queue. Returns 0 if the Peer is disconnected.
    pub fn pending_recv_count(&self) -> usize {
        self.incoming.len()
    }

    fn create_pair(
        a: (async_channel::Sender<T>, async_channel::Receiver<T>),
        b: (async_channel::Sender<T>, async_channel::Receiver<T>),
    ) -> (Self, Self) {
        let (a_send, a_recv) = a;
        let (b_send, b_recv) = b;
        let a = Self {
            incoming: a_recv,
            outgoing: b_send,
        };
        let b = Self {
            incoming: b_recv,
            outgoing: a_send,
        };
        (a, b)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    static_assertions::assert_impl_all!(BidirectionalAsyncChannel<i32>: Clone);

    #[test]
    pub fn send_works_both_ways() {
        let (a, b) = BidirectionalAsyncChannel::<i32>::create_unbounded_pair();

        assert!(a.try_send(1).is_ok());
        assert!(b.try_send(4).is_ok());
        assert!(a.try_send(2).is_ok());
        assert!(b.try_send(5).is_ok());
        assert!(a.try_send(3).is_ok());
        assert!(b.try_send(6).is_ok());

        assert_eq!(a.pending_send_count(), 3);
        assert_eq!(b.pending_send_count(), 3);
        assert_eq!(a.pending_recv_count(), 3);
        assert_eq!(b.pending_recv_count(), 3);

        assert_eq!(a.try_recv(), Ok(4));
        assert_eq!(a.try_recv(), Ok(5));
        assert_eq!(a.try_recv(), Ok(6));

        assert_eq!(b.try_recv(), Ok(1));
        assert_eq!(b.try_recv(), Ok(2));
        assert_eq!(b.try_recv(), Ok(3));
    }

    #[test]
    pub fn bounded_pairs_error_on_being_full() {
        let (a, b) = BidirectionalAsyncChannel::<i32>::create_bounded_pair(2);

        assert!(a.try_send(1).is_ok());
        assert!(a.try_send(2).is_ok());
        assert!(matches!(a.try_send(3), Err(TrySendError::Full(3))));
        assert!(b.try_send(4).is_ok());
        assert!(b.try_send(5).is_ok());
        assert!(matches!(b.try_send(6), Err(TrySendError::Full(6))));

        assert_eq!(a.try_recv(), Ok(4));
        assert_eq!(a.try_recv(), Ok(5));
        assert_eq!(a.try_recv(), Err(TryRecvError::Empty));

        assert_eq!(b.try_recv(), Ok(1));
        assert_eq!(b.try_recv(), Ok(2));
        assert_eq!(a.try_recv(), Err(TryRecvError::Empty));
    }

    #[test]
    pub fn disconnecting_closes_both_sides() {
        let (a, b) = BidirectionalAsyncChannel::<i32>::create_bounded_pair(2);

        a.disconnect();
        assert!(!a.is_connected());
        assert!(!b.is_connected());

        let (a, b) = BidirectionalAsyncChannel::<i32>::create_bounded_pair(2);

        b.disconnect();
        assert!(!a.is_connected());
        assert!(!b.is_connected());
    }

    #[test]
    pub fn disconnecting_stop_any_future_sends() {
        let (a, b) = BidirectionalAsyncChannel::<i32>::create_bounded_pair(2);

        a.disconnect();
        assert!(!a.is_connected());
        assert!(!b.is_connected());

        assert!(matches!(a.try_send(1), Err(TrySendError::Closed(1))));
        assert!(matches!(b.try_send(1), Err(TrySendError::Closed(1))));
        assert!(matches!(a.try_recv(), Err(TryRecvError::Closed)));
        assert!(matches!(b.try_recv(), Err(TryRecvError::Closed)));
    }

    #[test]
    pub fn disconnecting_allows_existing_items_to_be_flushed() {
        let (a, b) = BidirectionalAsyncChannel::<i32>::create_unbounded_pair();

        assert!(a.try_send(1).is_ok());
        assert!(a.try_send(2).is_ok());
        a.disconnect();
        assert!(matches!(a.try_send(3), Err(TrySendError::Closed(3))));

        assert_eq!(b.try_recv(), Ok(1));
        assert_eq!(b.try_recv(), Ok(2));
        assert_eq!(b.try_recv(), Err(TryRecvError::Closed));
    }

    #[test]
    pub fn dropping_leads_to_disconnect() {
        let (a, b) = BidirectionalAsyncChannel::<i32>::create_unbounded_pair();

        assert!(a.is_connected());
        drop(b);
        assert!(!a.is_connected());

        let (a, b) = BidirectionalAsyncChannel::<i32>::create_unbounded_pair();
        let c = b.clone();

        assert!(a.is_connected());
        drop(b);
        assert!(a.is_connected());
        drop(c);
        assert!(!a.is_connected());
    }
}