Skip to content

Commit

Permalink
Add task::from_fn
Browse files Browse the repository at this point in the history
  • Loading branch information
matthunz committed Feb 18, 2024
1 parent f114b67 commit 3184f27
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/task/from_fn.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use super::Task;
use std::marker::PhantomData;

pub fn from_fn<F, M, O>(f: F) -> FromFn<F, M>
where
F: FnMut(&mut M) -> O,
{
FromFn {
f,
_marker: PhantomData,
}
}

pub struct FromFn<F, M> {
f: F,
_marker: PhantomData<M>,
}

impl<F, M, O> Task<M> for FromFn<F, M>
where
F: FnMut(&mut M) -> O,
{
type Output = O;

type State = ();

fn build(&mut self, _cx: &super::Context<M, ()>, model: &mut M) -> (Self::Output, Self::State) {
((self.f)(model), ())
}

fn rebuild(
&mut self,
_cx: &super::Context<M, ()>,
model: &mut M,
_state: &mut Self::State,
) -> Self::Output {
(self.f)(model)
}
}
9 changes: 9 additions & 0 deletions src/task/mod.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
use std::rc::Rc;

mod from_fn;
pub use self::from_fn::{from_fn, FromFn};

mod then;
pub use self::then::Then;

pub struct Context<M, A> {
waker: Rc<dyn Fn(Rc<dyn Fn(&mut M) -> Option<A>>)>,
}

impl<M, A> Context<M, A> {
pub fn update(&self, f: impl Fn(&mut M) -> Option<A> + 'static) {
(self.waker)(Rc::new(f))
}
}

pub trait Task<M, A = ()> {
type Output;

Expand Down

0 comments on commit 3184f27

Please sign in to comment.