// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! Higher level communication abstractions. */ #[allow(missing_doc)]; use std::comm::{GenericChan, GenericSmartChan, GenericPort}; use std::comm::{Chan, Port, Selectable, Peekable}; use std::comm; use std::pipes; /// An extension of `pipes::stream` that allows both sending and receiving. pub struct DuplexStream { priv chan: Chan, priv port: Port, } // Allow these methods to be used without import: impl DuplexStream { pub fn send(&self, x: T) { self.chan.send(x) } pub fn try_send(&self, x: T) -> bool { self.chan.try_send(x) } pub fn recv(&self, ) -> U { self.port.recv() } pub fn try_recv(&self) -> Option { self.port.try_recv() } pub fn peek(&self) -> bool { self.port.peek() } } impl GenericChan for DuplexStream { fn send(&self, x: T) { self.chan.send(x) } } impl GenericSmartChan for DuplexStream { fn try_send(&self, x: T) -> bool { self.chan.try_send(x) } } impl GenericPort for DuplexStream { fn recv(&self) -> U { self.port.recv() } fn try_recv(&self) -> Option { self.port.try_recv() } } impl Peekable for DuplexStream { fn peek(&self) -> bool { self.port.peek() } } impl Selectable for DuplexStream { fn header(&mut self) -> *mut pipes::PacketHeader { self.port.header() } } /// Creates a bidirectional stream. pub fn DuplexStream() -> (DuplexStream, DuplexStream) { let (p1, c2) = comm::stream(); let (p2, c1) = comm::stream(); (DuplexStream { chan: c1, port: p1 }, DuplexStream { chan: c2, port: p2 }) } #[cfg(test)] mod test { use comm::DuplexStream; #[test] pub fn DuplexStream1() { let (left, right) = DuplexStream(); left.send(~"abc"); right.send(123); assert!(left.recv() == 123); assert!(right.recv() == ~"abc"); } }