use std::io::{Read, Write, Result, Error, ErrorKind};
use unix_socket::UnixStream;
use std::net::TcpStream;
pub enum Connection {
Unix(UnixStream),
Tcp(TcpStream)
}
impl Connection {
pub fn try_clone(&self) -> Result<Connection> {
match *self {
Connection::Unix(ref stream) => match stream.try_clone() {
Ok(cloned) => Ok(Connection::Unix(cloned)),
Err(e) => Err(e)
},
Connection::Tcp(ref stream) => match stream.try_clone() {
Ok(cloned) => Ok(Connection::Tcp(cloned)),
Err(e) => Err(e)
}
}
}
pub fn from_str(connection_str: &str) -> Result<Connection> {
let splits = connection_str.splitn(2, ':').collect::<Vec<_>>();
if splits.len() == 2 && splits[0] == "unix" {
Ok(Connection::Unix(try!(UnixStream::connect(splits[1]))))
} else if splits.len() == 2 && splits[0] == "tcp" {
Ok(Connection::Tcp(try!(TcpStream::connect(splits[1]))))
} else {
Err(Error::new(ErrorKind::InvalidInput, "Unknown connection type"))
}
}
}
impl Read for Connection {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
match *self {
Connection::Unix(ref mut stream) => stream.read(buf),
Connection::Tcp(ref mut stream) => stream.read(buf),
}
}
}
impl Write for Connection {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
match *self {
Connection::Unix(ref mut stream) => stream.write(buf),
Connection::Tcp(ref mut stream) => stream.write(buf),
}
}
fn flush(&mut self) -> Result<()> {
match *self {
Connection::Unix(ref mut stream) => stream.flush(),
Connection::Tcp(ref mut stream) => stream.flush(),
}
}
}