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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
use crate::scheduler::LocalStaticScheduler;

use super::{Future, JoinHandle, Schedule, Storage, TaskRef};
use core::panic::Location;

/// Builds a new [`Task`] prior to spawning it.
///
/// [`Task`]: crate::task::Task
#[derive(Debug, Clone)]
pub struct Builder<'a, S> {
    scheduler: S,
    settings: Settings<'a>,
}

/// Configures settings for new tasks.
#[derive(Debug, Clone)]
// These fields are currently only read when tracing is enabled.
#[cfg_attr(
    not(any(feature = "tracing-01", feature = "tracing-02", test)),
    allow(dead_code)
)]
pub(crate) struct Settings<'a> {
    pub(super) name: Option<&'a str>,
    pub(super) kind: &'static str,
    pub(super) location: Option<Location<'a>>,
}

impl<'a, S: Schedule + 'static> Builder<'a, S> {
    pub(crate) const fn new(scheduler: S) -> Self {
        Self {
            scheduler,
            settings: Settings::new(),
        }
    }

    /// Adds a name to the tasks produced by this builder.
    ///
    /// This will set the `task.name` `tracing` field of spans generated for
    /// this task, if the "tracing-01" or "tracing-02" feature flags are
    /// enabled.
    ///
    /// By default, tasks are unnamed.
    pub fn name(self, name: &'a str) -> Self {
        Self {
            settings: Settings {
                name: Some(name),
                ..self.settings
            },
            ..self
        }
    }

    /// Adds a static string which describes the type of the configured task.
    ///
    /// Generally, this is set by the runtime, rather than by user code &mdash;
    /// `kind`s should describe general categories of task, such as "local" or
    /// "blocking", rather than identifying specific tasks in an application. The
    /// [`name`] field should be used instead for naming specific tasks within
    /// an application.
    ///
    /// This will set the `task.kind` `tracing` field of spans generated for
    /// this task, if the "tracing-01" or "tracing-02" feature flags are
    /// enabled.
    ///
    /// By default, tasks will have the kind "task".
    ///
    /// [`name`]: Self::name
    pub fn kind(self, kind: &'static str) -> Self {
        Self {
            settings: Settings {
                kind,
                ..self.settings
            },
            ..self
        }
    }

    /// Overrides the task's source code location.
    ///
    /// By default, tasks will be recorded as having the location from which
    /// they are spawned. This may be overriden by the runtime if needed.
    pub fn location(self, location: Location<'a>) -> Self {
        Self {
            settings: Settings {
                location: Some(location),
                ..self.settings
            },
            ..self
        }
    }

    /// Spawns a new task in a custom allocation, with this builder's configured settings.
    ///
    /// Note that the `StoredTask` *must* be bound to the same scheduler
    /// instance as this task's scheduler!
    ///
    /// This method returns a [`JoinHandle`] that can be used to await the
    /// task's output. Dropping the [`JoinHandle`] _detaches_ the spawned task,
    /// allowing it to run in the background without awaiting its output.
    #[inline]
    #[track_caller]
    pub fn spawn_allocated<STO, F>(&self, task: STO::StoredTask) -> JoinHandle<F::Output>
    where
        F: Future + Send + 'static,
        F::Output: Send + 'static,
        STO: Storage<S, F>,
    {
        let (task, join) = TaskRef::build_allocated::<S, F, STO>(&self.settings, task);
        self.scheduler.schedule(task);
        join
    }
}

impl Builder<'_, &'static LocalStaticScheduler> {
    /// Spawns a new `!`[`Send`] task in a custom allocation, with this
    /// builder's configured settings.
    ///
    /// This method is capable of spawning futures which do not implement
    /// `Send`. Therefore, it is only available when this [`Builder`] was
    /// returned by a [`LocalStaticScheduler`]
    ///
    /// Note that the `StoredTask` *must* be bound to the same scheduler
    /// instance as this task's scheduler!
    ///
    /// This method returns a [`JoinHandle`] that can be used to await the
    /// task's output. Dropping the [`JoinHandle`] _detaches_ the spawned task,
    /// allowing it to run in the background without awaiting its output.
    #[inline]
    #[track_caller]
    pub fn spawn_local_allocated<STO, F>(&self, task: STO::StoredTask) -> JoinHandle<F::Output>
    where
        F: Future + 'static,
        F::Output: 'static,
        STO: Storage<&'static LocalStaticScheduler, F>,
    {
        let (task, join) =
            TaskRef::build_allocated::<&'static LocalStaticScheduler, F, STO>(&self.settings, task);
        self.scheduler.schedule(task);
        join
    }
}

feature! {
    #![feature = "alloc"]
    use alloc::boxed::Box;
    use super::{BoxStorage, Task};
    use crate::scheduler::LocalScheduler;

    impl<S: Schedule + 'static> Builder<'_, S> {
        /// Spawns a new task with this builder's configured settings.
        ///
        /// This method returns a [`JoinHandle`] that can be used to await the
        /// task's output. Dropping the [`JoinHandle`] _detaches_ the spawned task,
        /// allowing it to run in the background without awaiting its output.
        #[inline]
        #[track_caller]
        pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
        where
            F: Future + Send + 'static,
            F::Output: Send + 'static,
        {
            let mut task = Box::new(Task::<S, _, BoxStorage>::new(future));
            task.bind(self.scheduler.clone());
            let (task, join) = TaskRef::build_allocated::<S, _, BoxStorage>(&self.settings, task);
            self.scheduler.schedule(task);
            join
        }
    }

    impl Builder<'_, &'static LocalStaticScheduler> {
        /// Spawns a new `!`[`Send`] task with this builder's configured settings.
        ///
        /// This method is capable of spawning futures which do not implement
        /// [`Send`]. Therefore, it is only available when this [`Builder`] was
        /// returned by a [`LocalStaticScheduler`]
        ///
        /// This method returns a [`JoinHandle`] that can be used to await the
        /// task's output. Dropping the [`JoinHandle`] _detaches_ the spawned task,
        /// allowing it to run in the background without awaiting its output.
        #[inline]
        #[track_caller]
        pub fn spawn_local<F>(&self, future: F) -> JoinHandle<F::Output>
        where
            F: Future + 'static,
            F::Output: 'static,
        {
            let mut task = Box::new(Task::<&'static LocalStaticScheduler, _, BoxStorage>::new(future));
            task.bind(self.scheduler);
            let (task, join) = TaskRef::build_allocated::<&'static LocalStaticScheduler, _, BoxStorage>(&self.settings, task);
            self.scheduler.schedule(task);
            join
        }
    }

    impl Builder<'_, LocalScheduler> {
        /// Spawns a new `!`[`Send`] task with this builder's configured settings.
        ///
        /// This method is capable of spawning futures which do not implement
        /// [`Send`]. Therefore, it is only available when this [`Builder`] was
        /// returned by a [`LocalScheduler`]
        ///
        /// This method returns a [`JoinHandle`] that can be used to await the
        /// task's output. Dropping the [`JoinHandle`] _detaches_ the spawned task,
        /// allowing it to run in the background without awaiting its output.
        #[inline]
        #[track_caller]
        pub fn spawn_local<F>(&self, future: F) -> JoinHandle<F::Output>
        where
            F: Future + 'static,
            F::Output: 'static,
        {
            let mut task = Box::new(Task::<LocalScheduler, _, BoxStorage>::new(future));
            task.bind(self.scheduler.clone());
            let (task, join) = TaskRef::build_allocated::<LocalScheduler, _, BoxStorage>(&self.settings, task);
            self.scheduler.schedule(task);
            join
        }

        /// Spawns a new `!`[`Send`] task in a custom allocation, with this
        /// builder's configured settings.
        ///
        /// This method is capable of spawning futures which do not implement
        /// `Send`. Therefore, it is only available when this [`Builder`] was
        /// returned by a [`LocalStaticScheduler`]
        ///
        /// Note that the `StoredTask` *must* be bound to the same scheduler
        /// instance as this task's scheduler!
        ///
        /// This method returns a [`JoinHandle`] that can be used to await the
        /// task's output. Dropping the [`JoinHandle`] _detaches_ the spawned task,
        /// allowing it to run in the background without awaiting its output.
        #[inline]
        #[track_caller]
        pub fn spawn_local_allocated<STO, F>(&self, task: STO::StoredTask) -> JoinHandle<F::Output>
        where
            F: Future + 'static,
            F::Output: 'static,
            STO: Storage<LocalScheduler, F>,
        {
            let (task, join) = TaskRef::build_allocated::<LocalScheduler, F, STO>(&self.settings, task);
            self.scheduler.schedule(task);
            join
        }
    }
}

// === impl Settings ===

impl<'a> Settings<'a> {
    /// Returns a new, empty task builder with no settings configured.
    #[must_use]
    pub(crate) const fn new() -> Self {
        Self {
            name: None,
            location: None,
            kind: "task",
        }
    }
}

impl Default for Settings<'_> {
    fn default() -> Self {
        Self::new()
    }
}