use std::panic::{
AssertUnwindSafe,
catch_unwind,
};
use qubit_function::Callable;
use super::{
TaskCompletion,
TaskExecutionError,
TaskResult,
};
pub struct TaskRunner<C> {
task: C,
}
impl<C> TaskRunner<C> {
#[inline]
pub const fn new(task: C) -> Self {
Self { task }
}
pub fn call<R, E>(self) -> TaskResult<R, E>
where
C: Callable<R, E>,
{
let mut task = self.task;
match catch_unwind(AssertUnwindSafe(|| task.call())) {
Ok(Ok(value)) => Ok(value),
Ok(Err(err)) => Err(TaskExecutionError::Failed(err)),
Err(_) => Err(TaskExecutionError::Panicked),
}
}
#[inline]
pub fn run<R, E>(self, completion: TaskCompletion<R, E>) -> bool
where
C: Callable<R, E>,
{
completion.start_and_complete(|| self.call())
}
}