Use an intermediate function to build the handlers

Such a function may later be generated using a procedural macro.
This commit is contained in:
Rodolphe Breard 2019-01-05 13:59:29 +01:00
parent 98dd194dca
commit d05423edba
2 changed files with 27 additions and 4 deletions

View file

@ -1,14 +1,21 @@
use log::debug; use log::debug;
use env_logger::{Builder, Env}; use env_logger::{Builder, Env};
use opensmtpd::{Entry, EventHandler, MatchEvent, SmtpIn}; use opensmtpd::{handlers, Entry, EventHandler, MatchEvent, SmtpIn};
fn on_event(entry: &Entry) -> bool { fn on_event(entry: &Entry) -> bool {
debug!("Event received: {:?}", entry); debug!("Event received: {:?}", entry);
true true
} }
// This function should be replaced by a procedural macro on
// the `on_event` function.
fn on_event_builder() -> EventHandler {
EventHandler::new(MatchEvent::All, on_event)
}
fn main() { fn main() {
Builder::from_env(Env::default().default_filter_or("debug")).init(); Builder::from_env(Env::default().default_filter_or("debug")).init();
let h = vec![EventHandler::new(MatchEvent::All, on_event)]; SmtpIn::new()
SmtpIn::new().event_handlers(h).run(); .event_handlers(handlers!(on_event_builder))
.run();
} }

View file

@ -12,6 +12,19 @@ pub use crate::entry::{Entry, Event};
pub use crate::errors::Error; pub use crate::errors::Error;
pub use crate::event_handlers::{EventHandler, MatchEvent}; pub use crate::event_handlers::{EventHandler, MatchEvent};
#[macro_export]
macro_rules! handlers {
( $( $x:expr ),* ) => {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push(($x)());
)*
temp_vec
}
};
}
struct SessionHandler { struct SessionHandler {
entry_rx: mpsc::Receiver<Entry>, entry_rx: mpsc::Receiver<Entry>,
event_handlers: Vec<EventHandler>, event_handlers: Vec<EventHandler>,
@ -19,7 +32,10 @@ struct SessionHandler {
impl SessionHandler { impl SessionHandler {
fn new(entry_rx: mpsc::Receiver<Entry>, handlers_rx: mpsc::Receiver<EventHandler>) -> Self { fn new(entry_rx: mpsc::Receiver<Entry>, handlers_rx: mpsc::Receiver<EventHandler>) -> Self {
debug!("New thread for session {}", thread::current().name().unwrap()); debug!(
"New thread for session {}",
thread::current().name().unwrap()
);
let mut event_handlers = Vec::new(); let mut event_handlers = Vec::new();
for h in handlers_rx.iter() { for h in handlers_rx.iter() {
debug!("Event handler registered"); debug!("Event handler registered");