devela/code/result/panic/
namespace.rs

1// devela::code::result::panic::namespace
2//
3//! Defines the [`Panic`] namespace.
4//
5// - https://doc.rust-lang.org/stable/std/panic/index.html
6
7#[cfg(feature = "std")]
8use crate::{
9    Any, Box, PanicHookInfo, PanicUnwindSafe, ThreadResult,
10    _dep::_std::panic::{catch_unwind, panic_any, resume_unwind, set_hook, take_hook},
11};
12
13#[doc = crate::TAG_NAMESPACE!()]
14/// Panic-related operations.
15pub struct Panic;
16
17#[cfg(feature = "std")]
18#[cfg_attr(feature = "nightly_doc", doc(cfg(feature = "std")))]
19impl Panic {
20    /// Invokes a closure, capturing the cause of an unwinding panic if one occurs.
21    ///
22    /// See `std::panic::`[`catch_unwind`].
23    pub fn catch<F: FnOnce() -> R + PanicUnwindSafe, R>(f: F) -> ThreadResult<R> {
24        catch_unwind(f)
25    }
26
27    /// Panic the current thread with the given message as the panic payload.
28    ///
29    /// See `std::panic::`[`panic_any`].
30    pub fn any<M: 'static + Any + Send>(msg: M) -> ! {
31        panic_any(msg)
32    }
33
34    /// Triggers a panic without invoking the panic hook.
35    ///
36    /// See `std::panic::`[`resume_unwind`].
37    pub fn resume(payload: Box<dyn Any + Send>) -> ! {
38        resume_unwind(payload)
39    }
40
41    /// Registers a custom panic hook, replacing the previously registered hook.
42    pub fn set_hook(hook: Box<dyn Fn(&PanicHookInfo<'_>) + Sync + Send + 'static>) {
43        set_hook(hook);
44    }
45
46    /// Unregisters the current panic hook, returns it and registers.
47    pub fn take_hook() -> Box<dyn Fn(&PanicHookInfo<'_>) + Sync + Send + 'static> {
48        take_hook()
49    }
50}