From d19748f3d18c739a469e68f6c381bf7917acccd5 Mon Sep 17 00:00:00 2001 From: Tait Hoyem Date: Thu, 21 Mar 2024 10:37:20 -0600 Subject: [PATCH] Implement generic first parameters for Handler Combined with the new atspi_event_handler function, automatically convert a HandlerService for a specific event type, into a generic event handler, which checks if the event type matches before passing it into the inner event handler. It will either: transform the event into its specific type, or abort the calling of the service with an `OdiliaError::AtspiError(AtspiError::Conversion(...))` Clipppy and fmt --- odilia/Cargo.toml | 2 +- odilia/src/tower.rs | 22 +++++++++++++++++++--- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/odilia/Cargo.toml b/odilia/Cargo.toml index 9f0e8e60..f864bba4 100644 --- a/odilia/Cargo.toml +++ b/odilia/Cargo.toml @@ -56,7 +56,7 @@ zbus.workspace = true odilia-notify = { version = "0.1.0", path = "../odilia-notify" } clap = { version = "4.5.1", features = ["derive"] } tokio-util.workspace=true -tower = { version = "0.4.13", features = ["util"] } +tower = { version = "0.4.13", features = ["util", "filter"] } [dev-dependencies] lazy_static = "1.4.0" diff --git a/odilia/src/tower.rs b/odilia/src/tower.rs index 7a77762c..064a8c89 100644 --- a/odilia/src/tower.rs +++ b/odilia/src/tower.rs @@ -1,3 +1,5 @@ +#![allow(dead_code)] + use odilia_common::errors::OdiliaError; use std::future::Future; use std::marker::PhantomData; @@ -5,6 +7,7 @@ use std::marker::PhantomData; use std::task::Context; use std::task::Poll; +use tower::filter::Filter; use tower::Service; type Response = (); @@ -19,6 +22,19 @@ pub trait Handler: Clone { fn call(self, req: E, state: S) -> Self::Future; } +fn is_right_type>(req: Request) -> Result { + req.try_into() +} + +fn atspi_event_handler(h: HandlerService) -> impl Service +where + S: Clone, + E: TryFrom, + H: Handler, +{ + Filter::new(h, is_right_type::) +} + impl Handler<((),), S, E> for F where F: FnOnce() -> Fut + Clone + Send + 'static, @@ -81,7 +97,7 @@ pub struct HandlerService { _marker: PhantomData T>, } -impl Service for HandlerService +impl Service for HandlerService where H: Handler, S: Clone, @@ -95,9 +111,9 @@ where fn poll_ready(&mut self, _ctx: &mut Context<'_>) -> Poll> { Poll::Ready(Ok(())) } - fn call(&mut self, req: Request) -> Self::Future { + fn call(&mut self, req: E) -> Self::Future { let handler = self.handler.clone(); let state = self.state.clone(); - handler.call(req.try_into().expect("Must be converted from a certain type"), state) + handler.call(req, state) } }