]> git.lizzy.rs Git - rust.git/blob - src/libsync/comm.rs
comm: Implement synchronous channels
[rust.git] / src / libsync / comm.rs
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     priv tx: Sender<S>,
24     priv 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 try_send(&self, x: S) -> bool {
41         self.tx.try_send(x)
42     }
43     pub fn recv(&self) -> R {
44         self.rx.recv()
45     }
46     pub fn try_recv(&self) -> comm::TryRecvResult<R> {
47         self.rx.try_recv()
48     }
49     pub fn recv_opt(&self) -> Option<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");
64         right.send(123);
65
66         assert!(left.recv() == 123);
67         assert!(right.recv() == ~"abc");
68     }
69 }