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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
#![forbid(unsafe_code)]

//! This crate allows asynchronous value exchanges between two endpoints.
//!
//! Conceptually this is similar to having two channels, each with capacity 1.
//!
//! # Example
//!
//! Create an exchange between a client *A* and a server *B* where *A* sends
//! `u32` values to *B* and *B* acknowledges each value with a `bool`, `true`
//! if the value is odd and `false` otherwise.
//!
//! ```rust
//! # async fn doc() {
//! let (mut a, mut b) = scambio::exchange();
//!
//! let client = async move {
//!     for i in 0 .. 10u32 {
//!         assert!(a.send(i).await.is_ok());
//!         assert_eq!(Some(i % 2 == 1), a.receive().await)
//!     }
//! };
//!
//! let server = async move {
//!     while let Some(i) = b.receive().await {
//!         assert!(b.send(i % 2 == 1).await.is_ok())
//!     }
//! };
//!
//! assert_eq!(futures::join!(client, server), ((), ()));
//! # }
//! ```

use parking_lot::Mutex;
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll, Waker};

mod error;
pub use error::Error;

/// An exchange endpoint for value transfers.
///
/// Every exchange consists of two halves, [`Left`] and [`Right`], which can
/// transfer data between each other one by one. At most one data item is
/// stored per endpoint half.
pub struct Left<L, R> {
    data: Arc<Mutex<SharedData<L, R>>>
}

/// An exchange endpoint for value transfers.
///
/// Every exchange consists of two halves, [`Left`] and [`Right`], which can
/// transfer data between each other one by one. At most one data item is
/// stored per endpoint half.
pub struct Right<L, R> {
    data: Arc<Mutex<SharedData<L, R>>>
}

/// Shared data between endpoints.
struct SharedData<L, R> {
    /// Has `Left` not been dropped yet?
    l_alive: bool,
    /// Has `Right` not been dropped yet?
    r_alive: bool,
    /// The value `Left` wants to transfer to `Right`.
    l_offer: Option<L>,
    /// The value `Right` wants to transfer to `Left`.
    r_offer: Option<R>,
    /// If `r_offer` is empty, `Left`'s waker is stored in here and
    /// woken up once `Right` has put a value in `r_offer`, enabling
    /// `Left` to get the value.
    l_waker_r: Option<Waker>,
    /// If `l_offer` is full, `Left`'s waker is stored in here and
    /// woken up once `Right` has accepted `l_offer`, enabling `Left` to
    /// continue.
    l_waker_w: Option<Waker>,
    /// If `l_offer` is empty, `Right`'s waker is stored in here and
    /// woken up once `Left` has put a value in `l_offer`, enabling
    /// `Right` to get the value.
    r_waker_r: Option<Waker>,
    /// If `r_offer` is full, `Right`'s waker is stored in here and
    /// woken up once `Left` has accepted `r_offer`, enabling `Right` to
    /// continue.
    r_waker_w: Option<Waker>
}

/// Create a new exchange between `Left` and `Right`.
pub fn exchange<L, R>() -> (Left<L, R>, Right<L, R>) {
    let d = SharedData {
        l_alive: true,
        r_alive: true,
        l_offer: None,
        r_offer: None,
        l_waker_r: None,
        l_waker_w: None,
        r_waker_r: None,
        r_waker_w: None
    };
    let l = Left {
        data: Arc::new(Mutex::new(d))
    };
    let r = Right {
        data: l.data.clone()
    };
    (l, r)
}

impl<L, R> Left<L, R> {
    /// Has the other end been dropped?
    pub fn is_closed(&self) -> bool {
        !self.data.lock().r_alive
    }

    /// Send a value to [`Right`].
    ///
    /// If `Right` has been dropped, the value will be returned.
    pub async fn send(&mut self, value: L) -> Result<(), L> {
        SendReadyL(self).await;
        self.send_now(value).map_err(Error::into_data)
    }

    /// Receive a value from [`Right`].
    ///
    /// If `Right` has been dropped, `None` will be returned.
    pub async fn receive(&mut self) -> Option<R> {
        ReceiveR2L(self).await
    }

    /// Receive a value from [`Right`] if available.
    ///
    /// If `Right` has been dropped, `Poll::Ready(None)` will be returned.
    /// If no value is available, `Poll::Pending` will be returned and `Left` will
    /// be woken up once a value can be received for `Right`.
    pub fn poll_receive(&mut self, cx: &mut Context) -> Poll<Option<R>> {
        let mut data = self.data.lock();
        if let Some(val) = data.r_offer.take() {
            if let Some(w) = data.r_waker_w.take() {
                w.wake()
            }
            return Poll::Ready(Some(val))
        }
        if !data.r_alive {
            return Poll::Ready(None)
        }
        if !data.l_waker_r.as_ref().map_or(false, |w| w.will_wake(cx.waker())) {
            data.l_waker_r = Some(cx.waker().clone())
        }
        Poll::Pending
    }

    /// Check if there is capacity to send a data item to [`Right`].
    pub fn poll_send_ready(&mut self, cx: &mut Context) -> Poll<()> {
        let mut data = self.data.lock();
        if data.l_offer.is_none() {
            return Poll::Ready(())
        }
        if !data.l_waker_w.as_ref().map_or(false, |w| w.will_wake(cx.waker())) {
            data.l_waker_w = Some(cx.waker().clone())
        }
        Poll::Pending
    }

    /// Try to send data to [`Right`].
    ///
    /// If `Right` has been dropped or there is already a pending data item for
    /// `Right` the data will be returned to the caller.
    ///
    /// Use [`Left::poll_send_ready`] to ensure there is capacity available.
    pub fn send_now(&mut self, value: L) -> Result<(), Error<L>> {
        let mut data = self.data.lock();
        if !data.r_alive {
            return Err(Error::Closed(value))
        }
        if data.l_offer.is_some() {
            return Err(Error::AtCapacity(value))
        }
        data.l_offer = Some(value);
        if let Some(w) = data.r_waker_r.take() {
            w.wake()
        }
        Ok(())
    }
}

impl<L, R> Right<L, R> {
    /// Has the other end been dropped?
    pub fn is_closed(&self) -> bool {
        !self.data.lock().l_alive
    }

    /// Send a value to [`Left`].
    ///
    /// If `Left` has been dropped, the value will be returned.
    pub async fn send(&mut self, value: R) -> Result<(), R> {
        SendReadyR(self).await;
        self.send_now(value).map_err(Error::into_data)
    }

    /// Receive a value from [`Left`].
    ///
    /// If `Left` has been dropped, `None` will be returned.
    pub async fn receive(&mut self) -> Option<L> {
        ReceiveL2R(self).await
    }

    /// Receive a value from [`Left`] if available.
    ///
    /// If `Left` has been dropped, `Poll::Ready(None)` will be returned.
    /// If no value is available, `Poll::Pending` will be returned and `Right` will
    /// be woken up once a value can be received for `Left`.
    pub fn poll_receive(&mut self, cx: &mut Context) -> Poll<Option<L>> {
        let mut data = self.data.lock();
        if let Some(val) = data.l_offer.take() {
            if let Some(w) = data.l_waker_w.take() {
                w.wake()
            }
            return Poll::Ready(Some(val))
        }
        if !data.l_alive {
            return Poll::Ready(None)
        }
        if !data.r_waker_r.as_ref().map_or(false, |w| w.will_wake(cx.waker())) {
            data.r_waker_r = Some(cx.waker().clone())
        }
        Poll::Pending
    }

    /// Check if there is capacity to send a data item to [`Left`].
    pub fn poll_send_ready(&mut self, cx: &mut Context) -> Poll<()> {
        let mut data = self.data.lock();
        if data.r_offer.is_none() {
            return Poll::Ready(())
        }
        if !data.r_waker_w.as_ref().map_or(false, |w| w.will_wake(cx.waker())) {
            data.r_waker_w = Some(cx.waker().clone())
        }
        Poll::Pending
    }

    /// Try to send data to [`Left`].
    ///
    /// If `Left` has been dropped or there is already a pending data item for
    /// `Left` the data will be returned to the caller.
    ///
    /// Use [`Right::poll_send_ready`] to ensure there is capacity available.
    pub fn send_now(&mut self, value: R) -> Result<(), Error<R>> {
        let mut data = self.data.lock();
        if !data.l_alive {
            return Err(Error::Closed(value))
        }
        if data.r_offer.is_some() {
            return Err(Error::AtCapacity(value))
        }
        data.r_offer = Some(value);
        if let Some(w) = data.l_waker_r.take() {
            w.wake()
        }
        Ok(())
    }
}

impl<L, R> Unpin for Left<L, R> {}
impl<L, R> Unpin for Right<L, R> {}

impl<L, R> fmt::Debug for Left<L, R> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("Left")
    }
}

impl<L, R> fmt::Debug for Right<L, R> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("Right")
    }
}

impl<L, R> Drop for Left<L, R> {
    fn drop(&mut self) {
        let mut data = self.data.lock();
        data.l_alive = false;
        if let Some(w) = data.r_waker_r.take() {
            w.wake()
        }
        if let Some(w) = data.r_waker_w.take() {
            w.wake()
        }
    }
}

impl<L, R> Drop for Right<L, R> {
    fn drop(&mut self) {
        let mut data = self.data.lock();
        data.r_alive = false;
        if let Some(w) = data.l_waker_r.take() {
            w.wake()
        }
        if let Some(w) = data.l_waker_w.take() {
            w.wake()
        }
    }
}

/// A future receiving a value from `Right`.
struct ReceiveR2L<'a, L, R>(&'a mut Left<L, R>);

/// A future receiving a value from `Left`.
struct ReceiveL2R<'b, L, R>(&'b mut Right<L, R>);

/// A future checking if there is capacity for `Left` to send data.
struct SendReadyL<'a, L, R>(&'a mut Left<L, R>);

/// A future checking if there is capacity for `Right` to send data.
struct SendReadyR<'b, L, R>(&'b mut Right<L, R>);

impl<L, R> Future for ReceiveR2L<'_, L, R> {
    type Output = Option<R>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        self.0.poll_receive(cx)
    }
}

impl<L, R> Future for ReceiveL2R<'_, L, R> {
    type Output = Option<L>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        self.0.poll_receive(cx)
    }
}

impl<L, R> Future for SendReadyL<'_, L, R> {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        self.0.poll_send_ready(cx)
    }
}

impl<L, R> Future for SendReadyR<'_, L, R> {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        self.0.poll_send_ready(cx)
    }
}