nblock/
task.rs

1/// Definitions for task-related traits and impls
2
3/// Represents a single non-blocking task to be spawned using [`crate::Runtime::spawn`].
4///
5/// A default [`FnMut`] implementation is provided.
6pub trait Task {
7    type Output: Send + 'static;
8    fn drive(&mut self) -> Nonblock<Self::Output>;
9}
10impl<O, F> Task for F
11where
12    O: Send + 'static,
13    F: FnMut() -> Nonblock<O>,
14{
15    type Output = O;
16    fn drive(&mut self) -> Nonblock<Self::Output> {
17        self()
18    }
19}
20
21/// Something that can be converted into a [`Task`].
22///
23/// [`crate::Runtime::spawn`] requires that implementations be [`Send`], so that it can be dispatched to a non-blocking thread where the [`Task`] will be created.
24///
25/// A default `Task` impl is provided so that any `Task` can `IntoTask`.
26pub trait IntoTask {
27    type Task: Task;
28    fn into_task(self) -> Self::Task;
29}
30impl<T> IntoTask for T
31where
32    T: Task,
33{
34    type Task = T;
35    fn into_task(self) -> Self::Task {
36        self
37    }
38}
39
40/// The result of a single call to [`Task::drive`].
41///
42/// This is similar to a `Future` in async code, except it differentiates between a task being `Idle` or `Working` to impact duty-cycles accordingly.
43pub enum Nonblock<T> {
44    Active,
45    Complete(T),
46    Idle,
47}