use std::fmt;
use crate::double_checked::{CallbackError, ExecutorError};
#[derive(Debug)]
pub enum ExecutionResult<T, E> {
Success(T),
ConditionNotMet,
Failed(ExecutorError<E>),
}
impl<T, E> ExecutionResult<T, E> {
#[inline]
pub fn success(value: T) -> Self {
ExecutionResult::Success(value)
}
#[inline]
pub fn unmet() -> Self {
ExecutionResult::ConditionNotMet
}
#[inline]
pub fn task_failed(err: E) -> Self {
ExecutionResult::Failed(ExecutorError::TaskFailed(err))
}
#[inline]
pub fn prepare_failed(msg: impl fmt::Display) -> Self {
ExecutionResult::Failed(ExecutorError::PrepareFailed(CallbackError::from_display(
msg,
)))
}
#[inline]
pub fn prepare_commit_failed(msg: impl fmt::Display) -> Self {
ExecutionResult::Failed(ExecutorError::PrepareCommitFailed(
CallbackError::from_display(msg),
))
}
#[inline]
pub fn prepare_failed_with_type(
callback_type: &'static str,
msg: impl std::fmt::Display,
) -> Self {
ExecutionResult::Failed(ExecutorError::PrepareFailed(CallbackError::with_type(
callback_type,
msg,
)))
}
#[inline]
pub fn prepare_rollback_failed(
original: impl Into<String>,
rollback: impl Into<String>,
) -> Self {
ExecutionResult::Failed(ExecutorError::PrepareRollbackFailed {
original: CallbackError::from_display(original.into()),
rollback: CallbackError::from_display(rollback.into()),
})
}
#[inline]
pub fn from_executor_error(err: ExecutorError<E>) -> Self {
ExecutionResult::Failed(err)
}
#[inline]
pub fn is_success(&self) -> bool {
matches!(self, ExecutionResult::Success(_))
}
#[inline]
pub fn is_unmet(&self) -> bool {
matches!(self, ExecutionResult::ConditionNotMet)
}
#[inline]
pub fn is_failed(&self) -> bool {
matches!(self, ExecutionResult::Failed(_))
}
#[inline]
pub fn into_result(self) -> Result<Option<T>, ExecutorError<E>> {
match self {
ExecutionResult::Success(v) => Ok(Some(v)),
ExecutionResult::ConditionNotMet => Ok(None),
ExecutionResult::Failed(e) => Err(e),
}
}
}
impl<T, E> ExecutionResult<T, E>
where
E: fmt::Display,
{
#[inline]
pub fn unwrap(self) -> T {
match self {
ExecutionResult::Success(v) => v,
ExecutionResult::ConditionNotMet => {
panic!("Called unwrap on ExecutionResult::ConditionNotMet")
}
ExecutionResult::Failed(e) => {
panic!("Called unwrap on ExecutionResult::Failed: {}", e)
}
}
}
}