use core::future::{poll_fn, Future};
use core::marker::PhantomData;
use core::mem;
use core::sync::atomic::Ordering;
use core::task::Poll;
use super::raw;
#[cfg(feature = "trace")]
use crate::raw::trace::TaskRefTrace;
#[must_use = "Calling a task function does nothing on its own. You must spawn the returned SpawnToken, typically with Spawner::spawn()"]
pub struct SpawnToken<S> {
pub(crate) raw_task: Option<raw::TaskRef>,
phantom: PhantomData<*mut S>,
}
impl<S> SpawnToken<S> {
pub(crate) unsafe fn new(raw_task: raw::TaskRef) -> Self {
Self {
raw_task: Some(raw_task),
phantom: PhantomData,
}
}
pub fn id(&self) -> u32 {
match self.raw_task {
None => 0,
Some(t) => t.as_ptr() as u32,
}
}
pub fn new_failed() -> Self {
Self {
raw_task: None,
phantom: PhantomData,
}
}
}
impl<S> Drop for SpawnToken<S> {
fn drop(&mut self) {
panic!("SpawnToken instances may not be dropped. You must pass them to Spawner::spawn()")
}
}
#[derive(Copy, Clone)]
pub enum SpawnError {
Busy,
}
impl core::fmt::Debug for SpawnError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
core::fmt::Display::fmt(self, f)
}
}
impl core::fmt::Display for SpawnError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
SpawnError::Busy => write!(f, "Busy - Too many instances of this task are already running. Check the `pool_size` attribute of the task."),
}
}
}
#[cfg(feature = "defmt")]
impl defmt::Format for SpawnError {
fn format(&self, f: defmt::Formatter) {
match self {
SpawnError::Busy => defmt::write!(f, "Busy - Too many instances of this task are already running. Check the `pool_size` attribute of the task."),
}
}
}
impl core::error::Error for SpawnError {}
#[derive(Copy, Clone)]
pub struct Spawner {
pub(crate) executor: &'static raw::Executor,
not_send: PhantomData<*mut ()>,
}
impl Spawner {
pub(crate) fn new(executor: &'static raw::Executor) -> Self {
Self {
executor,
not_send: PhantomData,
}
}
pub unsafe fn for_current_executor() -> impl Future<Output = Self> {
poll_fn(|cx| {
let task = raw::task_from_waker(cx.waker());
let executor = unsafe {
task.header()
.executor
.load(Ordering::Relaxed)
.as_ref()
.unwrap_unchecked()
};
let executor = unsafe { raw::Executor::wrap(executor) };
Poll::Ready(Self::new(executor))
})
}
pub fn spawn<S>(&self, token: SpawnToken<S>) -> Result<(), SpawnError> {
let task = token.raw_task;
mem::forget(token);
match task {
Some(task) => {
unsafe { self.executor.spawn(task) };
Ok(())
}
None => Err(SpawnError::Busy),
}
}
pub fn must_spawn<S>(&self, token: SpawnToken<S>) {
unwrap!(self.spawn(token));
}
pub fn make_send(&self) -> SendSpawner {
SendSpawner::new(&self.executor.inner)
}
pub fn executor_id(&self) -> usize {
self.executor.id()
}
}
pub trait SpawnerTraceExt {
fn spawn_named<S>(&self, name: &'static str, token: SpawnToken<S>) -> Result<(), SpawnError>;
}
#[cfg(feature = "trace")]
impl SpawnerTraceExt for Spawner {
fn spawn_named<S>(&self, name: &'static str, token: SpawnToken<S>) -> Result<(), SpawnError> {
let task = token.raw_task;
core::mem::forget(token);
match task {
Some(task) => {
task.set_name(Some(name));
let task_id = task.as_ptr() as u32;
task.set_id(task_id);
unsafe { self.executor.spawn(task) };
Ok(())
}
None => Err(SpawnError::Busy),
}
}
}
#[cfg(not(feature = "trace"))]
impl SpawnerTraceExt for Spawner {
fn spawn_named<S>(&self, _name: &'static str, token: SpawnToken<S>) -> Result<(), SpawnError> {
self.spawn(token)
}
}
#[derive(Copy, Clone)]
pub struct SendSpawner {
executor: &'static raw::SyncExecutor,
}
impl SendSpawner {
pub(crate) fn new(executor: &'static raw::SyncExecutor) -> Self {
Self { executor }
}
pub fn for_current_executor() -> impl Future<Output = Self> {
poll_fn(|cx| {
let task = raw::task_from_waker(cx.waker());
let executor = unsafe {
task.header()
.executor
.load(Ordering::Relaxed)
.as_ref()
.unwrap_unchecked()
};
Poll::Ready(Self::new(executor))
})
}
pub fn spawn<S: Send>(&self, token: SpawnToken<S>) -> Result<(), SpawnError> {
let header = token.raw_task;
mem::forget(token);
match header {
Some(header) => {
unsafe { self.executor.spawn(header) };
Ok(())
}
None => Err(SpawnError::Busy),
}
}
pub fn must_spawn<S: Send>(&self, token: SpawnToken<S>) {
unwrap!(self.spawn(token));
}
}