Made changes to allow library to operate on any type of stream.

This commit is contained in:
Aaron Weiss 2014-10-08 12:57:36 -04:00
parent dc8003c8e3
commit 567074a599
2 changed files with 45 additions and 41 deletions

View file

@ -1,30 +1,34 @@
use std::io::{BufferedWriter, IoResult, TcpStream};
use std::io::{BufferedWriter, IoResult, TcpStream, Writer};
use data::Message;
pub enum Connection {
TcpConn(TcpStream),
pub enum Connection<T, U> where T: Writer + Sized + 'static, U: Reader + Sized + Clone + 'static {
Conn(T, U),
}
pub fn connect(host: &str, port: u16) -> IoResult<Connection> {
let socket = try!(TcpStream::connect(host, port));
Ok(TcpConn(socket))
}
fn send_internal(conn: &Connection, msg: &str) -> IoResult<()> {
match conn {
&TcpConn(ref tcp) => {
let mut writer = BufferedWriter::new(tcp.clone());
writer.write_str(msg)
}
impl Connection<BufferedWriter<TcpStream>, TcpStream> {
pub fn connect(host: &str, port: u16) -> IoResult<Connection<BufferedWriter<TcpStream>, TcpStream>> {
let socket = try!(TcpStream::connect(host, port));
Ok(Conn(BufferedWriter::new(socket.clone()), socket.clone()))
}
}
pub fn send(conn: &Connection, msg: Message) -> IoResult<()> {
let mut send = msg.command.to_string();
send.push_str(" ");
send.push_str(msg.args.init().connect(" ").as_slice());
send.push_str(" :");
send.push_str(*msg.args.last().unwrap());
send.push_str("\r\n");
send_internal(conn, send.as_slice())
impl<T, U> Connection<T, U> where T: Writer + Sized + 'static, U: Reader + Sized + Clone + 'static {
fn send_internal(conn: &mut Connection<T, U>, msg: &str) -> IoResult<()> {
match conn {
&Conn(ref mut send, _) => {
try!(send.write_str(msg));
send.flush()
}
}
}
pub fn send(conn: &mut Connection<T, U>, msg: Message) -> IoResult<()> {
let mut send = msg.command.to_string();
send.push_str(" ");
send.push_str(msg.args.init().connect(" ").as_slice());
send.push_str(" :");
send.push_str(*msg.args.last().unwrap());
send.push_str("\r\n");
Connection::send_internal(conn, send.as_slice())
}
}