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
//! # relay
//!
//! A light-weight channel using `Future`. A relay channel does not implement
//! `Send`, and so is not meant for synchronizing between threads. Instead,
//! its used to send message between tasks that live in the same thread.
//!
//! It is similar to the `oneshot` channel in the `futures` crate, but since
//! it is not meant for sending across threads, it performs about twice as
//! fast.
//!
//! ## Example
//!
//! ```rust
//! # extern crate futures;
//! # extern crate relay;
//! # use futures::Future;
//! # fn main() {
//! let (tx, rx) = relay::channel();
//! tx.complete("foo");
//! assert_eq!(rx.wait().unwrap(), "foo");
//! # }
//! ```
#![deny(warnings)]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
extern crate futures;

use std::cell::RefCell;
use std::fmt;
use std::rc::Rc;

use futures::{Future, Poll, Async};
use futures::task::{self, Task};

/// Create a new channel to send a message.
pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
    let inner = Rc::new(RefCell::new(Inner {
        value: None,
        complete: false,
        tx_task: None,
        rx_task: None,
    }));
    let tx = Sender {
        inner: inner.clone(),
    };
    let rx = Receiver {
        inner: inner,
    };
    (tx, rx)
}

/// The Sender portion of a channel.
pub struct Sender<T> {
    inner: Rc<RefCell<Inner<T>>>,
}

impl<T> Sender<T> {
    /// Sends the message to the `Receiver`.
    pub fn complete(self, val: T) {
        let mut borrow = self.inner.borrow_mut();
        borrow.value = Some(val);
    }

    /// Returns true if the `Receiver` has been dropped.
    pub fn is_canceled(&self) -> bool {
        self.inner.borrow().complete
    }

    /// Creates a `Future` that waits until someone is waiting on the `Receiver`.
    pub fn waiting(self) -> Waiting<T> {
        Waiting {
            tx: Some(self),
        }
    }
}

impl<T> Drop for Sender<T> {
    fn drop(&mut self) {
        let rx_task = {
            let mut borrow = self.inner.borrow_mut();
            borrow.complete = true;
            borrow.tx_task.take();
            borrow.rx_task.take()
        };
        if let Some(task) = rx_task {
            task.notify();
        }
    }
}

impl<T> fmt::Debug for Sender<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.pad("Sender")
    }
}

/// The receiver end of the channel.
///
/// The Receiver is a `Future` that resolves to the sent message.
pub struct Receiver<T> {
    inner: Rc<RefCell<Inner<T>>>,
}

impl<T> Receiver<T> {
    /// Returns true if the `Sender` was dropped without sending a message.
    pub fn is_canceled(&self) -> bool {
        let borrow = self.inner.borrow();
        borrow.complete && borrow.value.is_none()
    }

    /// Tries to receive the value if completed.
    ///
    /// - Ok(Some(T)): Success.
    /// - Ok(None): Not ready yet.
    /// - Err(Canceled): The sender dropped without sending a value.
    ///
    /// It is safe to call this when not in a futures task context.
    pub fn try_recv(&mut self) -> Result<Option<T>, Canceled> {
        self.recv_inner(false)
    }

    fn recv_inner(&mut self, should_park: bool) -> Result<Option<T>, Canceled> {
        let mut borrow = self.inner.borrow_mut();
        if let Some(val) = borrow.value.take() {
            Ok(Some(val))
        } else if borrow.complete {
            Err(Canceled)
        } else {
            if should_park {
                borrow.rx_task = Some(task::current());
            }
            if let Some(task) = borrow.tx_task.take() {
                task.notify();
            }
            Ok(None)
        }
    }
}

impl<T> Future for Receiver<T> {
    type Item = T;
    type Error = Canceled;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        self.recv_inner(true).map(|opt| match opt {
            Some(t) => Async::Ready(t),
            None => Async::NotReady,
        })
    }
}

impl<T> Drop for Receiver<T> {
    fn drop(&mut self) {
        let tx_task = {
            let mut borrow = self.inner.borrow_mut();
            borrow.complete = true;
            borrow.rx_task.take();
            borrow.tx_task.take()
        };
        if let Some(task) = tx_task {
            task.notify();
        }
    }
}

impl<T> fmt::Debug for Receiver<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.pad("Receiver")
    }
}

/// A `Future` waiting for interest to be registered on the `Receiver`.
pub struct Waiting<T> {
    tx: Option<Sender<T>>,
}

impl<T> Future for Waiting<T> {
    type Item = Sender<T>;
    type Error = Canceled;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        if self.tx.as_ref().unwrap().is_canceled() {
            Err(Canceled)
        } else if self.tx.as_ref().unwrap().inner.borrow().rx_task.is_some() {
            Ok(Async::Ready(self.tx.take().unwrap()))
        } else {
            self.tx.as_ref().unwrap().inner.borrow_mut().tx_task = Some(task::current());
            Ok(Async::NotReady)
        }
    }
}

impl<T> fmt::Debug for Waiting<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.pad("Waiting")
    }
}

/// Represents that the `Sender` dropped before sending a message.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Canceled;

struct Inner<T> {
    value: Option<T>,
    complete: bool,
    tx_task: Option<Task>,
    rx_task: Option<Task>,
}

#[cfg(test)]
mod tests {
    use futures::Future;
    use super::channel;

    #[test]
    fn test_smoke() {
        let (tx, rx) = channel();
        tx.complete(33);
        assert_eq!(rx.wait().unwrap(), 33);
    }

    #[test]
    fn test_canceled() {
        let (_, rx) = channel::<()>();
        assert_eq!(rx.wait().unwrap_err(), super::Canceled);
    }

    #[test]
    fn test_is_canceled() {
        let (tx, _) = channel::<()>();
        assert!(tx.is_canceled());

        let (_, rx) = channel::<()>();
        assert!(rx.is_canceled());

        let (tx, rx) = channel::<()>();
        assert!(!tx.is_canceled());
        assert!(!rx.is_canceled());

        tx.complete(());
        assert!(!rx.is_canceled());
    }

    #[test]
    fn test_tx_complete_rx_unparked() {
        let (tx, rx) = channel();

        let res = rx.join(::futures::lazy(move || {
            tx.complete(55);
            Ok(11)
        }));
        assert_eq!(res.wait().unwrap(), (55, 11));
    }

    #[test]
    fn test_tx_dropped_rx_unparked() {
        let (tx, rx) = channel::<i32>();

        let res = rx.join(::futures::lazy(move || {
            let _tx = tx;
            Ok(11)
        }));
        assert_eq!(res.wait().unwrap_err(), super::Canceled);
    }

    #[test]
    fn test_waiting_unparked() {
        let (tx, rx) = channel::<i32>();

        let res = tx.waiting().join(::futures::lazy(move || {
            let mut rx = rx;
            let _ = rx.poll(); // unpark
            Ok(rx)
        })).and_then(|(tx, rx)| {
            tx.complete(5);
            rx
        });
        assert_eq!(res.wait().unwrap(), 5);
    }

    #[test]
    fn test_waiting_canceled() {
        let (tx, rx) = channel::<i32>();

        let res = tx.waiting().join(::futures::lazy(move || {
            let _rx = rx;
            Ok(())
        }));
        assert_eq!(res.wait().unwrap_err(), super::Canceled);
    }

    #[test]
    fn try_recv() {
        let (tx, mut rx) = channel::<i32>();

        assert!(rx.try_recv().unwrap().is_none());

        ::futures::lazy(move || {
            tx.complete(5);
            Ok::<(), ()>(())
        }).wait().unwrap();

        assert_eq!(rx.try_recv().unwrap(), Some(5));
    }

    #[test]
    fn try_recv_canceled() {
        let (tx, mut rx) = channel::<i32>();

        assert!(rx.try_recv().unwrap().is_none());

        ::futures::lazy(move || {
            let _tx = tx;
            Ok::<(), ()>(())
        }).wait().unwrap();

        assert!(rx.try_recv().is_err());
    }
}