Skip to main content

asyncio/local/
connect_pair.rs

1use ffi::socketpair;
2use core::{IoContext, Socket};
3use local::LocalProtocol;
4
5use std::io;
6
7/// Returns a pair of connected UNIX domain sockets.
8///
9/// # Example
10///
11/// ```
12/// use std::thread;
13/// use asyncio::{IoContext, Stream};
14/// use asyncio::local::{LocalStream, LocalStreamSocket, connect_pair};
15///
16/// const MESSAGE: &'static str = "hello";
17///
18/// let ctx = &IoContext::new().unwrap();
19/// let (tx, rx) = connect_pair(ctx, LocalStream).unwrap();
20///
21/// let thrd = thread::spawn(move|| {
22///     let mut buf = [0; 32];
23///     let len = rx.read_some(&mut buf).unwrap();
24///     assert_eq!(len, MESSAGE.len());
25///     assert_eq!(&buf[..len], MESSAGE.as_bytes());
26/// });
27///
28/// tx.write_some(MESSAGE.as_bytes()).unwrap();
29/// thrd.join().unwrap();
30/// ```
31pub fn connect_pair<P>(ctx: &IoContext, pro: P) -> io::Result<(P::Socket, P::Socket)>
32    where P: LocalProtocol,
33{
34    let (s1, s2) = try!(socketpair(&pro));
35    Ok((
36        unsafe { P::Socket::from_raw_fd(ctx, pro.clone(), s1) },
37        unsafe { P::Socket::from_raw_fd(ctx, pro, s2) }
38    ))
39}