From eee1ad355a3bb1dab09c7ab6fe486595163c8dc8 Mon Sep 17 00:00:00 2001 From: Matt McCoy Date: Sun, 5 Jun 2016 19:41:36 -0400 Subject: [PATCH] Simplify login using ToSocketAddrs --- example.rs | 6 +++--- src/client.rs | 28 ++++++++++++---------------- 2 files changed, 15 insertions(+), 19 deletions(-) diff --git a/example.rs b/example.rs index c86379c..894af51 100644 --- a/example.rs +++ b/example.rs @@ -6,7 +6,7 @@ use imap::client::IMAPStream; use imap::client::IMAPMailbox; fn main() { - let mut imap_socket = match IMAPStream::connect("imap.gmail.com", 993, Some(SslContext::new(SslMethod::Sslv23).unwrap())) { + let mut imap_socket = match IMAPStream::connect(("imap.gmail.com", 993), Some(SslContext::new(SslMethod::Sslv23).unwrap())) { Ok(s) => s, Err(e) => panic!("{}", e) }; @@ -14,7 +14,7 @@ fn main() { if let Err(e) = imap_socket.login("username", "password") { println!("Error: {}", e) }; - + match imap_socket.capability() { Ok(capabilities) => { for capability in capabilities.iter() { @@ -42,5 +42,5 @@ fn main() { if let Err(e) = imap_socket.logout() { println!("Error: {}", e) - }; + }; } diff --git a/src/client.rs b/src/client.rs index 01f4abd..0b425ec 100644 --- a/src/client.rs +++ b/src/client.rs @@ -1,4 +1,4 @@ -use std::net::TcpStream; +use std::net::{TcpStream, ToSocketAddrs}; use openssl::ssl::{SslContext, SslStream}; use std::io::{Error, ErrorKind, Read, Result, Write}; use regex::Regex; @@ -10,8 +10,6 @@ enum IMAPStreamTypes { pub struct IMAPStream { stream: IMAPStreamTypes, - pub host: String, - pub port: u16, tag: u32, tag_prefix: &'static str } @@ -28,21 +26,19 @@ pub struct IMAPMailbox { impl IMAPStream { - pub fn connect>(host: S, port: u16, ssl_context: Option) -> Result { - let host_string = host.into(); - let connect_string = format!("{}:{}", host_string, port); - let tcp_stream = try!(TcpStream::connect(&*connect_string)); - let mut socket = match ssl_context { - Some(context) => IMAPStream { stream: IMAPStreamTypes::Ssl(SslStream::connect(&context, tcp_stream).unwrap()), host: host_string, port: port, tag: 1, tag_prefix: "a"}, - None => IMAPStream { stream: IMAPStreamTypes::Basic(tcp_stream), host: host_string, port: port, tag: 1, tag_prefix: "a"}, - }; + pub fn connect(addr: A, ssl_context: Option) -> Result { + match TcpStream::connect(addr) { + Ok(stream) => { + let mut socket = match ssl_context { + Some(context) => IMAPStream { stream: IMAPStreamTypes::Ssl(SslStream::connect(&context, stream).unwrap()), tag: 1, tag_prefix: "a"}, + None => IMAPStream { stream: IMAPStreamTypes::Basic(stream), tag: 1, tag_prefix: "a"}, + }; - match socket.read_greeting() { - Ok(_) => (), - Err(_) => return Err(Error::new(ErrorKind::Other, "Failed to read greet response")) + try!(socket.read_greeting()); + Ok(socket) + }, + Err(e) => Err(e) } - - Ok(socket) } //LOGIN