From 703b7fa892e6cf48a178a401ca37695b9aeff820 Mon Sep 17 00:00:00 2001 From: Jesse Luehrs Date: Thu, 4 Sep 2014 19:05:30 -0400 Subject: callbacks wip (non-working) wouldn't that mean i couldn't use closures then? yupp ): they just can't do what you want really well yet need to wait for the "closures that are quantified over lifetimes" thing mentioned here https://github.com/rust-lang/rfcs/blob/master/active/0044-closures.md to be implemented --- examples/client.rs | 11 +++++------ src/client.rs | 36 +++++++++++++++++++++++++++++++++++- src/constants.rs | 2 +- 3 files changed, 41 insertions(+), 8 deletions(-) diff --git a/examples/client.rs b/examples/client.rs index 98900ef..ac2c420 100644 --- a/examples/client.rs +++ b/examples/client.rs @@ -1,10 +1,9 @@ extern crate irc; fn main () { - let mut client = irc::ClientBuilder::new("doytest", "chat.freenode.net").connect(); - - loop { - let res = client.read(); - println!("{}", res); - } + let mut client = irc::ClientBuilder::new("doytest", "chat.freenode.net") + .add_callback(irc::Client::AnyMessageEvent, |client, m| { + println!("{}", m) + }) + .connect(); } diff --git a/src/client.rs b/src/client.rs index d9d4076..0e7407f 100644 --- a/src/client.rs +++ b/src/client.rs @@ -6,9 +6,10 @@ use message::Message; type Callback<'a, 'b> = Box, &'b Message), ()> + 'static>; -#[deriving(PartialEq, Eq, Hash)] +#[deriving(PartialEq, Eq, Hash, Clone)] pub enum CallbackEvent { MessageEvent(MessageType), + AnyMessageEvent, // XXX timer? connect/disconnect? } @@ -86,6 +87,17 @@ impl<'a, 'b> ClientBuilder<'a, 'b> { self } + pub fn remove_all_callbacks (&mut self) -> &mut ClientBuilder<'a, 'b> { + self.callbacks.clear(); + self + } + + pub fn add_callback (&mut self, cb_type: CallbackEvent, cb: Callback<'a, 'b>) -> &mut ClientBuilder<'a, 'b> { + self.callbacks.find_or_insert(cb_type.clone(), vec![]); + self.callbacks.get_mut(&cb_type).push(cb); + self + } + pub fn connect (self) -> Client<'a, 'b> { let nick = self.nick.clone(); let pass = self.pass.clone(); @@ -142,4 +154,26 @@ impl<'a, 'b> Client<'a, 'b> { pub fn write (&mut self, msg: Message) { msg.write_protocol_string(&mut self.conn); } + + pub fn run_loop (&'a mut self) { + loop { + let res = self.read(); + match self.callbacks.find(&AnyMessageEvent) { + Some(cbs) => { + for cb in cbs.iter() { + (*cb).call((self, &res)); + } + }, + None => {}, + } + match self.callbacks.find(&MessageEvent(res.message_type().clone())) { + Some(cbs) => { + for cb in cbs.iter() { + (*cb).call((self, &res)); + } + }, + None => {}, + } + } + } } diff --git a/src/constants.rs b/src/constants.rs index b3cb9ce..836846a 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -3,7 +3,7 @@ use std::fmt::{FormatError, Formatter, Show}; use std::from_str::FromStr; -#[deriving(PartialEq, Eq, Hash)] +#[deriving(PartialEq, Eq, Hash, Clone)] pub enum MessageType { Pass, Nick, -- cgit v1.2.3