orbital_base_components/
callback.rs1use std::{ops::Deref, sync::Arc};
2
3#[derive(Clone)]
5pub struct Handler<A = (), R = ()>(Arc<dyn Fn(A) -> R + Send + Sync + 'static>);
6
7impl Handler<(), ()> {
8 pub fn new<F>(f: F) -> Self
9 where
10 F: Fn() + Send + Sync + 'static,
11 {
12 Self(Arc::new(move |_| f()))
13 }
14}
15
16impl<A, R> Handler<A, R> {
17 pub fn with<F>(f: F) -> Self
18 where
19 F: Fn(A) -> R + Send + Sync + 'static,
20 {
21 Self(Arc::new(f))
22 }
23
24 pub fn run(&self, arg: A) -> R {
25 (self.0)(arg)
26 }
27}
28
29impl<A> Handler<A, ()> {
30 pub fn on<F>(f: F) -> Self
31 where
32 F: Fn(A) + Send + Sync + 'static,
33 {
34 Self(Arc::new(f))
35 }
36}
37
38impl<A, R> Deref for Handler<A, R> {
39 type Target = Arc<dyn Fn(A) -> R + Send + Sync + 'static>;
40
41 fn deref(&self) -> &Self::Target {
42 &self.0
43 }
44}
45
46impl<F, A> From<F> for Handler<A, ()>
47where
48 F: Fn(A) + Send + Sync + 'static,
49{
50 fn from(value: F) -> Self {
51 Self::on(value)
52 }
53}