use std::any::Any;
use std::fmt;
use std::panic::{UnwindSafe, catch_unwind};
use std::sync::{Mutex, PoisonError};
use crate::DecodeError;
pub const NON_STRING_PAYLOAD: &str = "non-string panic payload";
pub const MESSAGE_BYTES: usize = 1024;
pub fn contain<T, F>(f: F) -> Result<T, DecodeError>
where
F: FnOnce() -> Result<T, DecodeError> + UnwindSafe,
{
match catch_unwind(f) {
Ok(result) => result,
Err(payload) => Err(DecodeError::Panicked {
payload: Payload::new(payload),
}),
}
}
pub struct Payload(Kept);
#[allow(clippy::redundant_allocation, clippy::box_collection)]
enum Kept {
Str(Box<&'static str>),
String(Box<String>),
Other(Mutex<Box<dyn Any + Send>>),
}
const _: () = crate::send_sync::<Payload>();
impl Payload {
fn new(payload: Box<dyn Any + Send>) -> Self {
let payload = match payload.downcast::<&'static str>() {
Ok(s) => return Self(Kept::Str(s)),
Err(other) => other,
};
match payload.downcast::<String>() {
Ok(s) => Self(Kept::String(s)),
Err(other) => Self(Kept::Other(Mutex::new(other))),
}
}
fn text(&self) -> &str {
match &self.0 {
Kept::Str(s) => s,
Kept::String(s) => s,
Kept::Other(_) => NON_STRING_PAYLOAD,
}
}
#[must_use]
pub fn message(&self) -> &str {
let text = self.text();
text.get(..text.floor_char_boundary(MESSAGE_BYTES))
.unwrap_or(text)
}
#[must_use]
pub fn is_cut(&self) -> bool {
self.text().len() > MESSAGE_BYTES
}
#[must_use]
pub fn into_any(self) -> Box<dyn Any + Send> {
match self.0 {
Kept::Str(s) => s,
Kept::String(s) => s,
Kept::Other(m) => m.into_inner().unwrap_or_else(PoisonError::into_inner),
}
}
}
impl PartialEq for Payload {
fn eq(&self, other: &Self) -> bool {
self.text() == other.text()
}
}
impl Eq for Payload {}
impl fmt::Debug for Payload {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Payload").field(&self.message()).finish()
}
}
impl fmt::Display for Payload {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.message())
}
}
#[cfg(test)]
mod tests {
use super::{MESSAGE_BYTES, NON_STRING_PAYLOAD, Payload, contain};
use crate::DecodeError;
fn payload<T: std::fmt::Debug>(r: Result<T, DecodeError>) -> Payload {
match r {
Err(DecodeError::Panicked { payload }) => payload,
other => panic!("not a panic: {other:?}"),
}
}
#[test]
fn a_panic_is_an_error_with_its_payload() {
let p = payload(contain::<(), _>(|| panic!("boom {}", 7)));
assert_eq!((p.message(), p.is_cut()), ("boom 7", false));
let p = payload(contain::<(), _>(|| panic!("static")));
assert_eq!(p.message(), "static");
let p = payload(contain::<(), _>(|| std::panic::panic_any(42u8)));
assert_eq!(p.message(), NON_STRING_PAYLOAD);
assert_eq!(p.into_any().downcast_ref::<u8>(), Some(&42));
#[allow(clippy::indexing_slicing)]
let r: Result<u8, _> = contain(|| {
let v: Vec<u8> = Vec::new();
Ok(v[3])
});
assert!(matches!(r, Err(DecodeError::Panicked { .. })), "{r:?}");
}
#[test]
fn the_payload_is_kept_and_its_message_cut() {
let text = format!("a{}", "é".repeat(MESSAGE_BYTES));
let at = text.as_ptr();
let p = payload(contain::<(), _>(move || std::panic::panic_any(text)));
assert_eq!(p.message().as_ptr(), at);
assert_eq!(p.message().len(), MESSAGE_BYTES - 1);
assert!(p.is_cut());
assert_eq!(p.to_string(), p.message());
let whole = p.into_any().downcast::<String>().unwrap();
assert_eq!((whole.as_ptr(), whole.len()), (at, 1 + 2 * MESSAGE_BYTES));
let exact = "x".repeat(MESSAGE_BYTES);
let p = payload(contain::<(), _>(move || std::panic::panic_any(exact)));
assert_eq!((p.message().len(), p.is_cut()), (MESSAGE_BYTES, false));
}
#[test]
fn what_is_returned_or_raised_passes_through() {
assert_eq!(contain(|| Ok(5)), Ok(5));
assert_eq!(
contain::<(), _>(|| Err(DecodeError::NoImageData)),
Err(DecodeError::NoImageData)
);
}
}