Skip to content

Commit

Permalink
Implement generic first parameters for Handler
Browse files Browse the repository at this point in the history
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
  • Loading branch information
TTWNO committed Mar 21, 2024
1 parent 05dd2de commit d19748f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
2 changes: 1 addition & 1 deletion odilia/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
22 changes: 19 additions & 3 deletions odilia/src/tower.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
#![allow(dead_code)]

use odilia_common::errors::OdiliaError;
use std::future::Future;
use std::marker::PhantomData;

use std::task::Context;
use std::task::Poll;

use tower::filter::Filter;
use tower::Service;

type Response = ();
Expand All @@ -19,6 +22,19 @@ pub trait Handler<T, S, E>: Clone {
fn call(self, req: E, state: S) -> Self::Future;
}

fn is_right_type<E: TryFrom<Request, Error = Error>>(req: Request) -> Result<E, Error> {
req.try_into()
}

fn atspi_event_handler<H, T, S, E>(h: HandlerService<H, T, S, E>) -> impl Service<Request>
where
S: Clone,
E: TryFrom<Request, Error = Error>,
H: Handler<T, S, E>,
{
Filter::new(h, is_right_type::<E>)
}

impl<F, Fut, S, E> Handler<((),), S, E> for F
where
F: FnOnce() -> Fut + Clone + Send + 'static,
Expand Down Expand Up @@ -81,7 +97,7 @@ pub struct HandlerService<H, T, S, E> {
_marker: PhantomData<fn(E) -> T>,
}

impl<H, T, S, E> Service<Request> for HandlerService<H, T, S, E>
impl<H, T, S, E> Service<E> for HandlerService<H, T, S, E>
where
H: Handler<T, S, E>,
S: Clone,
Expand All @@ -95,9 +111,9 @@ where
fn poll_ready(&mut self, _ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
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)
}
}

0 comments on commit d19748f

Please sign in to comment.