use std::io::net::tcp::TcpStream;
use std::io::IoResult;
use std::str::from_utf8;
use std::vec::Vec;
use std::error::FromError;
use error::SmtpResult;
use response::Response;
use tools::{escape_crlf, escape_dot};
static BUFFER_SIZE: uint = 1024;
pub trait ClientStream {
fn send_and_get_response(&mut self, string: &str, end: &str) -> SmtpResult;
fn get_reply(&mut self) -> SmtpResult;
fn read_into_string(&mut self) -> IoResult<String>;
}
impl ClientStream for TcpStream {
fn send_and_get_response(&mut self, string: &str, end: &str) -> SmtpResult {
try!(self.write_str(format!("{}{}", escape_dot(string), end).as_slice()));
debug!("Wrote: {}", escape_crlf(escape_dot(string).as_slice()));
self.get_reply()
}
fn read_into_string(&mut self) -> IoResult<String> {
let mut more = true;
let mut result = String::new();
self.set_timeout(Some(1000));
while more {
let mut buf: Vec<u8> = Vec::with_capacity(BUFFER_SIZE);
let response = match self.push(BUFFER_SIZE, &mut buf) {
Ok(bytes_read) => {
more = bytes_read == BUFFER_SIZE;
if bytes_read > 0 {
from_utf8(buf.slice_to(bytes_read)).unwrap()
} else {
""
}
},
Err(..) => {more = false; ""},
};
result.push_str(response);
}
debug!("Read: {}", escape_crlf(result.as_slice()));
return Ok(result);
}
fn get_reply(&mut self) -> SmtpResult {
let response = try!(self.read_into_string());
match from_str::<Response>(response.as_slice()) {
Some(response) => Ok(response),
None => Err(FromError::from_error("Could not parse response"))
}
}
}