1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use std::fmt;
use std::rc::Rc;
pub struct Callback<IN>(Rc<dyn Fn(IN)>);
impl<IN, F: Fn(IN) + 'static> From<F> for Callback<IN> {
fn from(func: F) -> Self {
Callback(Rc::new(func))
}
}
impl<IN> Clone for Callback<IN> {
fn clone(&self) -> Self {
Callback(self.0.clone())
}
}
impl<IN> PartialEq for Callback<IN> {
fn eq(&self, other: &Callback<IN>) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
impl<IN> fmt::Debug for Callback<IN> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Callback<_>")
}
}
impl<IN> Callback<IN> {
pub fn emit(&self, value: IN) {
(self.0)(value);
}
pub fn noop() -> Self {
Self::from(|_| {})
}
}
impl<IN: 'static> Callback<IN> {
pub fn reform<F, T>(&self, func: F) -> Callback<T>
where
F: Fn(T) -> IN + 'static,
{
let this = self.clone();
let func = move |input| {
let output = func(input);
this.emit(output);
};
Callback::from(func)
}
}