Connections now support non-cloneable Readers (read: all of them). Thanks, @retep998.

This commit is contained in:
Aaron Weiss 2014-10-08 20:57:23 -04:00
parent 7efe3f3fdf
commit f6915e2e53
3 changed files with 50 additions and 43 deletions

View file

@ -1,34 +1,44 @@
use std::io::{BufferedWriter, IoResult, TcpStream, Writer};
use std::cell::{RefCell, RefMut};
use std::io::{BufferedReader, BufferedWriter, IoResult, TcpStream, Writer};
use data::{IrcReader, IrcWriter, Message};
pub enum Connection<T, U> where T: IrcWriter, U: IrcReader {
Conn(T, U),
pub struct Connection<T, U> where T: IrcWriter, U: IrcReader {
writer: RefCell<T>,
reader: RefCell<U>,
}
impl Connection<BufferedWriter<TcpStream>, TcpStream> {
pub fn connect(host: &str, port: u16) -> IoResult<Connection<BufferedWriter<TcpStream>, TcpStream>> {
impl Connection<BufferedWriter<TcpStream>, BufferedReader<TcpStream>> {
pub fn connect(host: &str, port: u16) -> IoResult<Connection<BufferedWriter<TcpStream>, BufferedReader<TcpStream>>> {
let socket = try!(TcpStream::connect(host, port));
Ok(Conn(BufferedWriter::new(socket.clone()), socket.clone()))
Connection::new(BufferedWriter::new(socket.clone()), BufferedReader::new(socket.clone()))
}
}
impl<T, U> Connection<T, U> where T: IrcWriter, U: IrcReader {
fn send_internal(conn: &mut Connection<T, U>, msg: &str) -> IoResult<()> {
match conn {
&Conn(ref mut send, _) => {
try!(send.write_str(msg));
send.flush()
}
}
fn new(writer: T, reader: U) -> IoResult<Connection<T, U>> {
Ok(Connection {
writer: RefCell::new(writer),
reader: RefCell::new(reader),
})
}
pub fn send(conn: &mut Connection<T, U>, msg: Message) -> IoResult<()> {
fn send_internal(&self, msg: &str) -> IoResult<()> {
let mut send = self.writer.borrow_mut();
try!(send.write_str(msg));
send.flush()
}
pub fn send(&self, 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())
self.send_internal(send.as_slice())
}
pub fn reader<'a>(&'a self) -> RefMut<'a, U> {
self.reader.borrow_mut()
}
}