rune/runtime/
panic.rs

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