1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#![deny(missing_docs)]
#![warn(rust_2018_idioms)]
#![doc(html_root_url = "https://docs.rs/amq-protocol-tcp/2.0.0-rc15/")]
use amq_protocol_uri::{AMQPScheme, AMQPUri};
use tcp_stream::HandshakeError;
use std::io;
pub use tcp_stream::TcpStream;
pub trait AMQPUriTcpExt {
fn connect<S, F: FnOnce(TcpStream, AMQPUri) -> S>(self, f: F) -> io::Result<S>;
}
impl AMQPUriTcpExt for AMQPUri {
fn connect<S, F: FnOnce(TcpStream, AMQPUri) -> S>(self, f: F) -> io::Result<S> {
if let Ok(sockaddr) = format!("{}:{}", self.authority.host, self.authority.port).parse() {
let stream = TcpStream::connect(&sockaddr)?;
match self.scheme {
AMQPScheme::AMQP => Ok(stream),
AMQPScheme::AMQPS => stream.into_tls(&self.authority.host).or_else(retry_handshake),
}.map(|s| f(s, self))
} else {
Err(io::Error::new(io::ErrorKind::AddrNotAvailable, format!("cannot resolve {}", &self.authority.host)))
}
}
}
fn retry_handshake(error: HandshakeError) -> io::Result<TcpStream> {
match error {
HandshakeError::Failure(io_err) => Err(io_err),
HandshakeError::WouldBlock(mid) => mid.handshake().or_else(retry_handshake),
}
}
impl AMQPUriTcpExt for &str {
fn connect<S, F: FnOnce(TcpStream, AMQPUri) -> S>(self, f: F) -> io::Result<S> {
self.parse::<AMQPUri>().map_err(|e| io::Error::new(io::ErrorKind::Other, e))?.connect(f)
}
}