Created
April 27, 2018 21:58
-
-
Save rust-play/e524254713e76dbe7e756464a7b8932a to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub struct MultiAddrTcpStream { | |
addrs: Vec<SocketAddr>, | |
future: Option<IoFuture<TcpStream>>, | |
timeout: Option<time::Duration>, | |
last_err: Option<io::Error>, | |
} | |
impl MultiAddrTcpStream { | |
pub fn connect(mut addrs: Vec<SocketAddr>) -> MultiAddrTcpStream { | |
Self::new(addrs, None) | |
} | |
pub fn connect_timeout(mut addrs: Vec<SocketAddr>, timeout: time::Duration) -> MultiAddrTcpStream { | |
Self::new(addrs, Some(timeout)) | |
} | |
fn new(mut addrs: Vec<SocketAddr>, timeout: Option<time::Duration>) -> MultiAddrTcpStream { | |
addrs.reverse(); | |
MultiAddrTcpStream { | |
addrs, | |
future: None, | |
timeout, | |
last_err: None, | |
} | |
} | |
} | |
impl Future for MultiAddrTcpStream { | |
type Item = TcpStream; | |
type Error = io::Error; | |
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { | |
loop { | |
if self.future.is_none() { | |
if let Some(addr) = self.addrs.pop() { | |
let connect_process = TcpStream::connect(&addr); | |
if let Some(timeout) = self.timeout.as_ref() { | |
let deadline_process = timer::Deadline::new(connect_process, Instant::now() + *timeout).map_err(|err| { | |
match err.into_inner() { | |
Some(err) => err, | |
None => io::ErrorKind::TimedOut.into() | |
} | |
}); | |
self.future = Some(Box::new(deadline_process)); | |
} else { | |
self.future = Some(Box::new(connect_process)); | |
} | |
} else { | |
if let Some(err) = self.last_err.take() { | |
return Err(err); | |
} else { | |
return Err(io::ErrorKind::InvalidInput.into()); | |
} | |
} | |
} | |
let mut f = self.future.take().unwrap(); | |
match f.poll() { | |
Ok(Async::Ready(socket)) => return Ok(Async::Ready(socket)), | |
Ok(Async::NotReady) => { | |
self.future = Some(f); | |
return Ok(Async::NotReady); | |
} | |
Err(err) => { | |
self.last_err = Some(err); | |
continue; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More generic version: