maycoon_core/tasks/
mod.rs

1use crate::tasks::runner::TaskRunner;
2use crate::tasks::task::Task;
3use std::sync::OnceLock;
4
5/// Contains the [TaskRunner] and related structures.
6pub mod runner;
7
8/// Contains the [Task] and [task::LocalTask] traits.
9pub mod task;
10
11/// Contains a dummy implementation of a waker. Used in [Task::take].
12pub mod waker;
13
14/// Contains the [fetcher::Fetcher] structure.
15pub mod fetcher;
16
17/// The global task runner.
18static RUNNER: OnceLock<TaskRunner> = OnceLock::new();
19
20/// Tries to initialize the task runner, if it isn't yet.
21pub fn try_init(runner: TaskRunner) {
22    RUNNER.get_or_init(move || runner);
23}
24
25/// Initializes the global task runner.
26///
27/// Panics if the task runner is already initialized.
28#[inline(always)]
29pub fn init(runner: TaskRunner) {
30    RUNNER.set(runner).expect("Task runner already initialized");
31}
32
33/// Try to get the global task runner.
34/// Returns [None] if the task runner is not initialized.
35#[inline(always)]
36pub fn try_runner<'a>() -> Option<&'a TaskRunner> {
37    RUNNER.get()
38}
39
40/// Get the global task runner.
41///
42/// Panics if the task runner is not initialized.
43#[inline(always)]
44pub fn runner<'a>() -> &'a TaskRunner {
45    RUNNER.get().expect("Task runner not initialized")
46}
47
48/// Spawns a task on the global task runner.
49///
50/// If this actually spawns a task on a background task or just spawns a local task,
51/// depends on the [TaskRunner] type that is in use.
52#[inline(always)]
53pub fn spawn<Fut>(future: Fut) -> Box<dyn Task<Fut::Output>>
54where
55    Fut: Future + Send + 'static,
56    Fut::Output: Send + 'static,
57{
58    runner().spawn(future)
59}
60
61/// Spawns a blocking task on the global task runner.
62///
63/// This will always spawn a task in a background thread,
64/// as local spawning would block the thread.
65///
66/// Only available on native platforms.
67#[inline(always)]
68#[cfg(native)]
69pub fn spawn_blocking<R, F>(func: F) -> Box<dyn Task<R>>
70where
71    R: Send + 'static,
72    F: FnOnce() -> R + Send + 'static,
73{
74    runner().spawn_blocking(func)
75}
76
77/// Blocks the current thread on the global task runner until the future is ready.
78///
79/// Only available on native platforms.
80#[inline(always)]
81#[cfg(native)]
82pub fn block_on<Fut>(future: Fut) -> Fut::Output
83where
84    Fut: Future,
85{
86    runner().block_on(future)
87}