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
#![cfg(feature = "with-deprecated")]
#![deprecated(since = "0.1.4", note = "use sync::mpsc::channel instead")]
#![allow(deprecated)]
use std::any::Any;
use std::error::Error;
use std::fmt;
use {Poll, Async, Stream, Future, Sink};
use sink::Send;
use sync::mpsc;
pub fn channel<T, E>() -> (Sender<T, E>, Receiver<T, E>) {
let (tx, rx) = mpsc::channel(0);
(Sender { inner: tx }, Receiver { inner: rx })
}
#[derive(Debug)]
pub struct Sender<T, E> {
inner: mpsc::Sender<Result<T, E>>,
}
#[must_use = "streams do nothing unless polled"]
#[derive(Debug)]
pub struct Receiver<T, E> {
inner: mpsc::Receiver<Result<T, E>>,
}
pub struct SendError<T, E>(Result<T, E>);
#[derive(Debug)]
pub struct FutureSender<T, E> {
inner: Send<mpsc::Sender<Result<T, E>>>,
}
impl<T, E> fmt::Debug for SendError<T, E> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_tuple("SendError")
.field(&"...")
.finish()
}
}
impl<T, E> fmt::Display for SendError<T, E> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "send failed because receiver is gone")
}
}
impl<T, E> Error for SendError<T, E>
where T: Any, E: Any
{
fn description(&self) -> &str {
"send failed because receiver is gone"
}
}
impl<T, E> Stream for Receiver<T, E> {
type Item = T;
type Error = E;
fn poll(&mut self) -> Poll<Option<T>, E> {
match self.inner.poll().expect("cannot fail") {
Async::Ready(Some(Ok(e))) => Ok(Async::Ready(Some(e))),
Async::Ready(Some(Err(e))) => Err(e),
Async::Ready(None) => Ok(Async::Ready(None)),
Async::NotReady => Ok(Async::NotReady),
}
}
}
impl<T, E> Sender<T, E> {
pub fn send(self, t: Result<T, E>) -> FutureSender<T, E> {
FutureSender { inner: self.inner.send(t) }
}
}
impl<T, E> Future for FutureSender<T, E> {
type Item = Sender<T, E>;
type Error = SendError<T, E>;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self.inner.poll() {
Ok(a) => Ok(a.map(|a| Sender { inner: a })),
Err(e) => Err(SendError(e.into_inner())),
}
}
}