#![allow(unreachable_pub)]
use crate::{
runtime::Handle,
task::{JoinHandle, LocalSet},
};
use std::{future::Future, io};
#[derive(Default, Debug)]
#[cfg_attr(docsrs, doc(cfg(all(tokio_unstable, feature = "tracing"))))]
pub struct Builder<'a> {
name: Option<&'a str>,
}
impl<'a> Builder<'a> {
pub fn new() -> Self {
Self::default()
}
pub fn name(&self, name: &'a str) -> Self {
Self { name: Some(name) }
}
#[track_caller]
pub fn spawn<Fut>(self, future: Fut) -> io::Result<JoinHandle<Fut::Output>>
where
Fut: Future + Send + 'static,
Fut::Output: Send + 'static,
{
Ok(super::spawn::spawn_inner(future, self.name))
}
#[track_caller]
pub fn spawn_on<Fut>(self, future: Fut, handle: &Handle) -> io::Result<JoinHandle<Fut::Output>>
where
Fut: Future + Send + 'static,
Fut::Output: Send + 'static,
{
Ok(handle.spawn_named(future, self.name))
}
#[track_caller]
pub fn spawn_local<Fut>(self, future: Fut) -> io::Result<JoinHandle<Fut::Output>>
where
Fut: Future + 'static,
Fut::Output: 'static,
{
Ok(super::local::spawn_local_inner(future, self.name))
}
#[track_caller]
pub fn spawn_local_on<Fut>(
self,
future: Fut,
local_set: &LocalSet,
) -> io::Result<JoinHandle<Fut::Output>>
where
Fut: Future + 'static,
Fut::Output: 'static,
{
Ok(local_set.spawn_named(future, self.name))
}
#[track_caller]
pub fn spawn_blocking<Function, Output>(
self,
function: Function,
) -> io::Result<JoinHandle<Output>>
where
Function: FnOnce() -> Output + Send + 'static,
Output: Send + 'static,
{
let handle = Handle::current();
self.spawn_blocking_on(function, &handle)
}
#[track_caller]
pub fn spawn_blocking_on<Function, Output>(
self,
function: Function,
handle: &Handle,
) -> io::Result<JoinHandle<Output>>
where
Function: FnOnce() -> Output + Send + 'static,
Output: Send + 'static,
{
use crate::runtime::Mandatory;
let (join_handle, spawn_result) = handle.inner.blocking_spawner().spawn_blocking_inner(
function,
Mandatory::NonMandatory,
self.name,
handle,
);
spawn_result?;
Ok(join_handle)
}
}