(index<- ) ./libsync/comm.rs
git branch: * master 5200215 auto merge of #14035 : alexcrichton/rust/experimental, r=huonw
modified: Sat Apr 19 11:22:39 2014
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 /*!
12
13 Higher level communication abstractions.
14
15 */
16
17 #![allow(missing_doc)]
18
19 use std::comm;
20
21 /// An extension of `pipes::stream` that allows both sending and receiving.
22 pub struct DuplexStream<S, R> {
23 tx: Sender<S>,
24 rx: Receiver<R>,
25 }
26
27 /// Creates a bidirectional stream.
28 pub fn duplex<S: Send, R: Send>() -> (DuplexStream<S, R>, DuplexStream<R, S>) {
29 let (tx1, rx1) = channel();
30 let (tx2, rx2) = channel();
31 (DuplexStream { tx: tx1, rx: rx2 },
32 DuplexStream { tx: tx2, rx: rx1 })
33 }
34
35 // Allow these methods to be used without import:
36 impl<S:Send,R:Send> DuplexStream<S, R> {
37 pub fn send(&self, x: S) {
38 self.tx.send(x)
39 }
40 pub fn send_opt(&self, x: S) -> Result<(), S> {
41 self.tx.send_opt(x)
42 }
43 pub fn recv(&self) -> R {
44 self.rx.recv()
45 }
46 pub fn try_recv(&self) -> Result<R, comm::TryRecvError> {
47 self.rx.try_recv()
48 }
49 pub fn recv_opt(&self) -> Result<R, ()> {
50 self.rx.recv_opt()
51 }
52 }
53
54 #[cfg(test)]
55 mod test {
56 use comm::{duplex};
57
58
59 #[test]
60 pub fn DuplexStream1() {
61 let (left, right) = duplex();
62
63 left.send("abc".to_owned());
64 right.send(123);
65
66 assert!(left.recv() == 123);
67 assert!(right.recv() == "abc".to_owned());
68 }
69 }