diff options
| author | Mara Bos <m-ou.se@m-ou.se> | 2024-05-16 13:08:27 +0200 |
|---|---|---|
| committer | Mara Bos <m-ou.se@m-ou.se> | 2024-06-11 15:47:00 +0200 |
| commit | de07c1a928b3a1e6e12946c9d9d0ff47c2310ead (patch) | |
| tree | 0bf7eef882f5b008b6565c6e4f62c5f6af74a237 /library/std/src/panic.rs | |
| parent | fb0990d1e1e67a512930665bf7df5fb91f55982c (diff) | |
| download | rust-de07c1a928b3a1e6e12946c9d9d0ff47c2310ead.tar.gz rust-de07c1a928b3a1e6e12946c9d9d0ff47c2310ead.zip | |
Add PanicHookInfo::payload_as_str().
Diffstat (limited to 'library/std/src/panic.rs')
| -rw-r--r-- | library/std/src/panic.rs | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/library/std/src/panic.rs b/library/std/src/panic.rs index d5566caa369..f1b45b18630 100644 --- a/library/std/src/panic.rs +++ b/library/std/src/panic.rs @@ -96,6 +96,45 @@ impl<'a> PanicHookInfo<'a> { self.payload } + /// Returns the payload associated with the panic, if it is a string. + /// + /// This returns the payload if it is of type `&'static str` or `String`. + /// + /// A invocation of the `panic!()` macro in Rust 2021 or later will always result in a + /// panic payload where `payload_as_str` returns `Some`. + /// + /// Only an invocation of [`panic_any`] + /// (or, in Rust 2018 and earlier, `panic!(x)` where `x` is something other than a string) + /// can result in a panic payload where `payload_as_str` returns `None`. + /// + /// # Example + /// + /// ```should_panic + /// #![feature(panic_payload_as_str)] + /// + /// std::panic::set_hook(Box::new(|panic_info| { + /// if let Some(s) = panic_info.payload_as_str() { + /// println!("panic occurred: {s:?}"); + /// } else { + /// println!("panic occurred"); + /// } + /// })); + /// + /// panic!("Normal panic"); + /// ``` + #[must_use] + #[inline] + #[unstable(feature = "panic_payload_as_str", issue = "125175")] + pub fn payload_as_str(&self) -> Option<&str> { + if let Some(s) = self.payload.downcast_ref::<&str>() { + Some(s) + } else if let Some(s) = self.payload.downcast_ref::<String>() { + Some(s) + } else { + None + } + } + /// Returns information about the location from which the panic originated, /// if available. /// |
