Skip to main content

moirai_core/task/
ext.rs

1use super::builder::Mapped;
2use super::id_and_context::TaskContext;
3use super::traits::Task;
4
5/// Extension methods for tasks.
6pub trait TaskExt: Task + Sized {
7    /// Transform the output of this task.
8    fn map<F, R>(self, mapper: F) -> Mapped<Self, F>
9    where
10        F: FnOnce(Self::Output) -> R,
11    {
12        Mapped::new(self, mapper)
13    }
14
15    /// Convert this task into a task with the given context.
16    fn with_context(self, context: TaskContext) -> ContextualTask<Self> {
17        ContextualTask::new(self, context)
18    }
19}
20
21// Blanket implementation for all Task implementors.
22impl<T: Task> TaskExt for T {}
23
24/// A task with an explicit context.
25pub struct ContextualTask<T> {
26    task: T,
27    context: TaskContext,
28}
29
30impl<T: Task> ContextualTask<T> {
31    /// Create a new contextual task.
32    pub fn new(task: T, context: TaskContext) -> Self {
33        Self { task, context }
34    }
35}
36
37impl<T: Task> Task for ContextualTask<T> {
38    type Output = T::Output;
39
40    fn execute(self) -> Self::Output {
41        self.task.execute()
42    }
43
44    fn context(&self) -> &TaskContext {
45        &self.context
46    }
47}