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
#![allow(missing_doc)]
use core::prelude::*;
use comm;
use comm::{Sender, Receiver, channel};
pub struct DuplexStream<S, R> {
tx: Sender<S>,
rx: Receiver<R>,
}
pub fn duplex<S: Send, R: Send>() -> (DuplexStream<S, R>, DuplexStream<R, S>) {
let (tx1, rx1) = channel();
let (tx2, rx2) = channel();
(DuplexStream { tx: tx1, rx: rx2 },
DuplexStream { tx: tx2, rx: rx1 })
}impl<S:Send,R:Send> DuplexStream<S, R> {
pub fn send(&self, x: S) {
self.tx.send(x)
}
pub fn send_opt(&self, x: S) -> Result<(), S> {
self.tx.send_opt(x)
}
pub fn recv(&self) -> R {
self.rx.recv()
}
pub fn try_recv(&self) -> Result<R, comm::TryRecvError> {
self.rx.try_recv()
}
pub fn recv_opt(&self) -> Result<R, ()> {
self.rx.recv_opt()
}
}
#[cfg(test)]
mod test {
use std::prelude::*;
use comm::{duplex};
#[test]
pub fn duplex_stream_1() {
let (left, right) = duplex();
left.send("abc".to_string());
right.send(123);
assert!(left.recv() == 123);
assert!(right.recv() == "abc".to_string());
}
}