//! The last line of defence against bugs: turns a panic at an entry point //! into [`EngineError::Internal`] so that the process, and the user's unsaved //! work, survive. //! //! The guard is for bugs. Expected failures are `Result`s and never reach it. //! Release builds keep `panic = "unwind"`, which this module relies on. use std::any::Any; use std::panic::{AssertUnwindSafe, catch_unwind}; use crate::EngineError; /// Runs `f` and converts a panic inside it into [`EngineError::Internal`]. /// /// The closure is treated as unwind safe: after a panic the engine state may /// hold a half-finished change from the failed command, which is preferable to /// losing every open buffer. /// /// # Errors /// Returns the closure's own error, or [`EngineError::Internal`] with the /// panic message if it panicked. pub fn run(f: impl FnOnce() -> Result) -> Result { catch_unwind(AssertUnwindSafe(f)) .unwrap_or_else(|payload| Err(EngineError::Internal(panic_message(payload.as_ref())))) } /// Extracts the message of a panic payload, which is a `&str` or a `String` /// for `panic!` with a literal or a format string. fn panic_message(payload: &(dyn Any + Send)) -> String { if let Some(s) = payload.downcast_ref::<&str>() { (*s).to_string() } else if let Some(s) = payload.downcast_ref::() { s.clone() } else { "a command panicked".to_string() } } #[cfg(test)] mod tests { use super::*; #[test] fn passes_results_through() { assert_eq!(run(|| Ok(3)), Ok(3)); assert_eq!( run::<()>(|| Err(EngineError::Failed("no".into()))), Err(EngineError::Failed("no".into())) ); } #[test] fn converts_panics() { let r = run::<()>(|| panic!("boom {}", 42)); assert_eq!(r, Err(EngineError::Internal("boom 42".into()))); let r = run::<()>(|| std::panic::panic_any(7_u8)); assert_eq!(r, Err(EngineError::Internal("a command panicked".into()))); } }