use super::stored::StoredValue;
pub struct Callback<In: 'static = (), Out: 'static = ()> {
inner: StoredValue<Box<dyn Fn(In) -> Out>>,
}
impl<In: 'static, Out: 'static> Clone for Callback<In, Out> {
fn clone(&self) -> Self {
*self
}
}
impl<In: 'static, Out: 'static> Copy for Callback<In, Out> {}
impl<In: 'static, Out: 'static> Callback<In, Out> {
pub fn new(f: impl Fn(In) -> Out + 'static) -> Self {
Self {
inner: StoredValue::new(Box::new(f) as Box<dyn Fn(In) -> Out>),
}
}
pub fn run(&self, input: In) -> Out {
self.inner.with(|f| f(input))
}
}
impl<Out: 'static> Callback<(), Out> {
pub fn call(&self) -> Out {
self.run(())
}
}
impl<F, In, Out> From<F> for Callback<In, Out>
where
F: Fn(In) -> Out + 'static,
In: 'static,
Out: 'static,
{
fn from(f: F) -> Self {
Callback::new(f)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::reactive::__reset_for_tests;
use std::cell::Cell;
use std::rc::Rc;
#[test]
fn callback_is_copy() {
__reset_for_tests();
fn assert_copy<C: Copy>(_: &C) {}
let cb: Callback<(), i32> = Callback::new(|_| 1);
assert_copy(&cb);
let first = move || cb.run(());
let second = move || cb.run(());
assert_eq!(first(), 1);
assert_eq!(second(), 1);
}
#[test]
fn run_forwards_input_and_returns_output() {
__reset_for_tests();
let cb: Callback<i32, i32> = Callback::new(|x| x * 2);
assert_eq!(cb.run(21), 42);
}
#[test]
fn call_is_run_with_unit_input() {
__reset_for_tests();
let log = Rc::new(Cell::new(0));
let log2 = log.clone();
let cb: Callback<()> = Callback::new(move |()| {
log2.set(log2.get() + 1);
});
cb.call();
cb.call();
assert_eq!(log.get(), 2);
}
#[test]
fn closure_converts_via_into() {
__reset_for_tests();
fn takes_callback(cb: impl Into<Callback<i32, i32>>) -> Callback<i32, i32> {
cb.into()
}
let cb = takes_callback(|x| x + 1);
assert_eq!(cb.run(9), 10);
}
#[test]
fn each_clone_shares_the_same_underlying_closure() {
__reset_for_tests();
let log = Rc::new(Cell::new(0));
let log2 = log.clone();
let cb: Callback<()> = Callback::new(move |()| log2.set(log2.get() + 1));
let a = cb;
let b = cb;
a.call();
b.call();
assert_eq!(log.get(), 2);
}
}