rune/runtime/
panic.rs

1use core::fmt;
2
3use rust_alloc::boxed::Box;
4
5use crate::runtime::PanicReason;
6use crate::vm_error;
7
8pub trait BoxedPanic: fmt::Display + fmt::Debug + Send + Sync {}
9impl<T> BoxedPanic for T where T: ?Sized + fmt::Display + fmt::Debug + Send + Sync {}
10
11vm_error!(Panic);
12
13/// A descriptive panic.
14///
15/// This can be used as an error variant in native functions that you want to be
16/// able to panic.
17#[derive(Debug)]
18pub struct Panic {
19    inner: Box<dyn BoxedPanic>,
20}
21
22impl Panic {
23    /// A custom panic reason.
24    pub(crate) fn custom<D>(message: D) -> Self
25    where
26        D: 'static + BoxedPanic,
27    {
28        Self {
29            inner: Box::new(message),
30        }
31    }
32}
33
34impl fmt::Display for Panic {
35    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
36        write!(fmt, "{}", self.inner)
37    }
38}
39
40impl From<PanicReason> for Panic {
41    fn from(value: PanicReason) -> Self {
42        Self {
43            inner: Box::new(value),
44        }
45    }
46}
47
48#[cfg(test)]
49impl PartialEq for Panic {
50    #[inline]
51    fn eq(&self, _: &Self) -> bool {
52        true
53    }
54}