Skip to main content

mln_engine/exec/
panic.rs

1//! Panics that the library survives. A panic is a bug in the library: the
2//! work that hit it fails, with the panic's message, instead of the process.
3
4use std::any::Any;
5use std::panic::{AssertUnwindSafe, catch_unwind};
6
7/// Runs `work`, and returns the message of the panic that ended it instead
8/// of its result. The panic hook has reported the panic already.
9///
10/// The state that `work` changed may be half-changed after a panic, so the
11/// caller must not rely on it, such as by failing what owns it.
12///
13/// # Errors
14///
15/// Returns the panic's message when `work` panicked.
16pub fn catch<R>(work: impl FnOnce() -> R) -> Result<R, String> {
17    catch_unwind(AssertUnwindSafe(work)).map_err(|payload| message(&*payload))
18}
19
20/// The message of a panic whose payload is `payload`.
21#[must_use]
22pub fn message(payload: &(dyn Any + Send)) -> String {
23    if let Some(message) = payload.downcast_ref::<&str>() {
24        (*message).to_owned()
25    } else if let Some(message) = payload.downcast_ref::<String>() {
26        message.clone()
27    } else {
28        "a panic without a message".to_owned()
29    }
30}
31
32#[cfg(test)]
33mod tests {
34    use super::*;
35
36    #[test]
37    fn returns_the_result_of_work_that_returns() {
38        assert_eq!(catch(|| 7), Ok(7));
39    }
40
41    #[test]
42    fn returns_the_message_of_a_panic() {
43        assert_eq!(catch(|| panic!("static")), Err::<(), _>("static".to_owned()));
44        let value = 7;
45        assert_eq!(catch(|| panic!("formatted {value}")), Err::<(), _>("formatted 7".to_owned()));
46        assert_eq!(catch(|| std::panic::panic_any(7)), Err::<(), _>("a panic without a message".to_owned()));
47    }
48}