use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
use std::io;
pub use crate::join_set::JoinSet;
pub mod coop {
pub use crate::coop::{
BUDGET, Cooperative, Unconstrained, consume_budget, cooperative, has_budget_remaining,
unconstrained,
};
}
pub use crate::rt::task::{AbortHandle, FallibleTask, Id, Join, JoinError, Task};
pub use crate::runtime::{spawn, spawn_blocking, spawn_local};
pub use crate::task_local::{AccessError, LocalKey, TaskLocalFuture};
#[expect(
clippy::expect_used,
reason = "documented under `# Panics`; `try_id` answers `None` instead"
)]
pub fn id() -> Id {
try_id().expect("`nuclei::task::id` called outside a task")
}
pub fn try_id() -> Option<Id> {
crate::rt::task::current_id()
}
pub async fn yield_now() {
YieldNow { yielded: false }.await
}
struct YieldNow {
yielded: bool,
}
impl Future for YieldNow {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if self.yielded {
return Poll::Ready(());
}
self.yielded = true;
cx.waker().wake_by_ref();
Poll::Pending
}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct Builder<'a> {
name: Option<&'a str>,
}
impl<'a> Builder<'a> {
pub fn new() -> Self {
Self { name: None }
}
pub fn name(self, name: &'a str) -> Self {
Self { name: Some(name) }
}
pub fn spawn<F>(self, future: F) -> io::Result<Task<F::Output>>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
Ok(self.named(spawn(future)))
}
pub fn spawn_local<F>(self, future: F) -> io::Result<Task<F::Output>>
where
F: Future + 'static,
F::Output: 'static,
{
Ok(self.named(spawn_local(future)))
}
pub fn spawn_blocking<F, T>(self, f: F) -> io::Result<Task<T>>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
Ok(self.named(spawn_blocking(f)))
}
pub fn spawn_on<F>(
self,
future: F,
handle: &crate::runtime::RuntimeHandle,
) -> io::Result<Task<F::Output>>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
Ok(self.named(handle.spawn(future)))
}
fn named<T>(self, task: Task<T>) -> Task<T> {
if let Some(name) = self.name {
crate::rt::task::names::set(task.id(), name);
}
task
}
}
#[cfg(all(test, not(loom)))]
mod tests {
use super::*;
use crate::rt::task::names;
#[test]
fn names_live_exactly_as_long_as_their_tasks() {
crate::block_on(async {
let done = Builder::new().name("done").spawn(async { 1 }).unwrap();
let id = done.id();
assert_eq!(names::get(id).as_deref(), Some("done"));
assert_eq!(done.await, 1);
let cancelled = Builder::new()
.name("cancelled")
.spawn(core::future::pending::<()>())
.unwrap();
cancelled.abort();
assert!(cancelled.join().await.unwrap_err().is_cancelled());
let blocking = Builder::new()
.name("blocking")
.spawn_blocking(|| 2)
.unwrap();
assert_eq!(blocking.await, 2);
let unnamed = Builder::new().spawn(async { 3 }).unwrap();
assert_eq!(names::get(unnamed.id()), None);
assert_eq!(unnamed.await, 3);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while names::count() != 0 && std::time::Instant::now() < deadline {
yield_now().await;
}
assert_eq!(names::count(), 0, "a destroyed task kept its name");
assert_eq!(names::get(id), None);
});
}
}