Use procedural macros to define events
The construction of an EventHandler object should not be directly done by the client. Instead, it is easier to use procedural macro to automatize the process, hence exposing a nice and simple interface. Such use of procedural macros requires to crate an additional crate.
This commit is contained in:
parent
ccda4b1517
commit
789455668c
17 changed files with 1190 additions and 76 deletions
51
opensmtpd/src/event_handlers.rs
Normal file
51
opensmtpd/src/event_handlers.rs
Normal file
|
@ -0,0 +1,51 @@
|
|||
use crate::entry::{Entry, Event};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum MatchEvent {
|
||||
Evt(Vec<Event>),
|
||||
All,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct EventHandler {
|
||||
event: MatchEvent,
|
||||
callback: (fn(&Entry) -> bool),
|
||||
}
|
||||
|
||||
impl EventHandler {
|
||||
fn get_events_from_string(event_str: &String) -> MatchEvent {
|
||||
let mut events = Vec::new();
|
||||
for name in event_str.split(" , ") {
|
||||
match name {
|
||||
"Any" | "All" => {
|
||||
return MatchEvent::All;
|
||||
}
|
||||
_ => match Event::from_str(name) {
|
||||
Ok(e) => {
|
||||
events.push(e);
|
||||
}
|
||||
Err(_) => {}
|
||||
},
|
||||
}
|
||||
}
|
||||
MatchEvent::Evt(events)
|
||||
}
|
||||
|
||||
pub fn new(event_str: String, callback: (fn(&Entry) -> bool)) -> Self {
|
||||
EventHandler {
|
||||
event: EventHandler::get_events_from_string(&event_str),
|
||||
callback,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_callable(&self, event: Event) -> bool {
|
||||
match &self.event {
|
||||
MatchEvent::All => true,
|
||||
MatchEvent::Evt(v) => v.contains(&event),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn call(&self, entry: &Entry) -> bool {
|
||||
(self.callback)(entry)
|
||||
}
|
||||
}
|
Reference in a new issue