use std::any::Any;
use std::error::Error;
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;
use std::sync::Mutex;
use crate::ContractCheckId;
#[must_use]
pub struct ContractFailure {
check: Option<ContractCheckId>,
message: String,
source: Option<Box<dyn Error + Send + Sync>>,
panic: Mutex<Option<Box<dyn Any + Send>>>,
}
impl ContractFailure {
#[inline]
pub const fn check(&self) -> Option<ContractCheckId> {
self.check
}
#[must_use]
#[inline]
pub fn message(&self) -> &str {
&self.message
}
pub fn take_panic_payload(&self) -> Option<Box<dyn Any + Send>> {
self.panic.lock().unwrap_or_else(|poison| poison.into_inner()).take()
}
pub(crate) fn message_only(message: impl Into<String>) -> Self {
Self {
check: None,
message: message.into(),
source: None,
panic: Mutex::new(None),
}
}
pub(crate) fn with_source(message: impl Into<String>, source: impl Error + Send + Sync + 'static) -> Self {
Self {
check: None,
message: message.into(),
source: Some(Box::new(source)),
panic: Mutex::new(None),
}
}
pub(crate) fn with_owned_source(message: impl Into<String>, source: impl Error + Send + 'static) -> Self {
Self::with_source(message, crate::ContractSource::new(source))
}
pub(crate) fn panicked(context: &str, payload: Box<dyn Any + Send>) -> Self {
let detail = payload
.downcast_ref::<String>()
.map(String::as_str)
.or_else(|| payload.downcast_ref::<&str>().copied());
let message = match detail {
Some(detail) => format!("{context}: {detail}"),
None => format!("{context}: non-string panic payload retained"),
};
Self {
check: None,
message,
source: None,
panic: Mutex::new(Some(payload)),
}
}
pub(crate) fn at(mut self, check: ContractCheckId) -> Self {
self.check = Some(check);
self
}
}
impl Debug for ContractFailure {
fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
formatter
.debug_struct("ContractFailure")
.field("check", &self.check)
.field("message", &self.message)
.finish_non_exhaustive()
}
}
impl Display for ContractFailure {
fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
if let Some(check) = self.check {
write!(formatter, "{check}: ")?;
}
formatter.write_str(&self.message)
}
}
impl Error for ContractFailure {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.source.as_deref().map(|source| source as &(dyn Error + 'static))
}
}
#[cfg(test)]
mod tests {
use std::panic::AssertUnwindSafe;
use super::ContractFailure;
#[test]
fn test_poisoned_panic_lock_still_allows_payload_transfer() {
let failure = ContractFailure::panicked("contract", Box::new(String::from("retained panic")));
let _ = std::panic::catch_unwind(AssertUnwindSafe(|| {
let _guard = failure.panic.lock().unwrap();
panic!("poison panic lock");
}));
assert_eq!(
failure
.take_panic_payload()
.unwrap()
.downcast::<String>()
.unwrap()
.as_str(),
"retained panic"
);
assert!(failure.take_panic_payload().is_none());
}
}