]> git.lizzy.rs Git - rust.git/blob - src/libsync/comm/duplex.rs
Apply stability attributes to std::comm
[rust.git] / src / libsync / comm / duplex.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 #![deprecated = "This type is replaced by having a pair of channels. This type \
19                  is not fully composable with other channels in terms of \
20                  or possible semantics on a duplex stream. It will be removed \
21                  soon"]
22
23 use core::prelude::*;
24
25 use comm;
26 use comm::{Sender, Receiver, channel};
27
28 /// An extension of `pipes::stream` that allows both sending and receiving.
29 pub struct DuplexStream<S, R> {
30     tx: Sender<S>,
31     rx: Receiver<R>,
32 }
33
34 /// Creates a bidirectional stream.
35 pub fn duplex<S: Send, R: Send>() -> (DuplexStream<S, R>, DuplexStream<R, S>) {
36     let (tx1, rx1) = channel();
37     let (tx2, rx2) = channel();
38     (DuplexStream { tx: tx1, rx: rx2 },
39      DuplexStream { tx: tx2, rx: rx1 })
40 }
41
42 // Allow these methods to be used without import:
43 impl<S:Send,R:Send> DuplexStream<S, R> {
44     pub fn send(&self, x: S) {
45         self.tx.send(x)
46     }
47     pub fn send_opt(&self, x: S) -> Result<(), S> {
48         self.tx.send_opt(x)
49     }
50     pub fn recv(&self) -> R {
51         self.rx.recv()
52     }
53     pub fn try_recv(&self) -> Result<R, comm::TryRecvError> {
54         self.rx.try_recv()
55     }
56     pub fn recv_opt(&self) -> Result<R, ()> {
57         self.rx.recv_opt()
58     }
59 }
60
61 #[cfg(test)]
62 mod test {
63     use std::prelude::*;
64     use comm::{duplex};
65
66     #[test]
67     pub fn duplex_stream_1() {
68         let (left, right) = duplex();
69
70         left.send("abc".to_string());
71         right.send(123i);
72
73         assert!(left.recv() == 123);
74         assert!(right.recv() == "abc".to_string());
75     }
76 }