Add PanicHookInfo::payload_as_str(). · model-checking/verify-rust-std@fea6b03
@@ -96,6 +96,45 @@ impl<'a> PanicHookInfo<'a> {
9696self.payload
9797}
989899+/// Returns the payload associated with the panic, if it is a string.
100+ ///
101+ /// This returns the payload if it is of type `&'static str` or `String`.
102+ ///
103+ /// A invocation of the `panic!()` macro in Rust 2021 or later will always result in a
104+ /// panic payload where `payload_as_str` returns `Some`.
105+ ///
106+ /// Only an invocation of [`panic_any`]
107+ /// (or, in Rust 2018 and earlier, `panic!(x)` where `x` is something other than a string)
108+ /// can result in a panic payload where `payload_as_str` returns `None`.
109+ ///
110+ /// # Example
111+ ///
112+ /// ```should_panic
113+ /// #![feature(panic_payload_as_str)]
114+ ///
115+ /// std::panic::set_hook(Box::new(|panic_info| {
116+ /// if let Some(s) = panic_info.payload_as_str() {
117+ /// println!("panic occurred: {s:?}");
118+ /// } else {
119+ /// println!("panic occurred");
120+ /// }
121+ /// }));
122+ ///
123+ /// panic!("Normal panic");
124+ /// ```
125+ #[must_use]
126+#[inline]
127+#[unstable(feature = "panic_payload_as_str", issue = "125175")]
128+pub fn payload_as_str(&self) -> Option<&str> {
129+if let Some(s) = self.payload.downcast_ref::<&str>() {
130+Some(s)
131+} else if let Some(s) = self.payload.downcast_ref::<String>() {
132+Some(s)
133+} else {
134+None
135+}
136+}
137+99138/// Returns information about the location from which the panic originated,
100139 /// if available.
101140 ///