Skip to content

Commit 0e60287

Browse files
committed
Implement Display for PanicInfo and Location
Due to being in libcore, this impl cannot access PanicInfo::payload if it’s a String.
1 parent 9e96c1e commit 0e60287

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

src/libcore/panic.rs

+23
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,23 @@ impl<'a> PanicInfo<'a> {
120120
}
121121
}
122122

123+
impl<'a> fmt::Display for PanicInfo<'a> {
124+
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
125+
formatter.write_str("panicked at ")?;
126+
if let Some(message) = self.message {
127+
write!(formatter, "'{}', ", message)?
128+
} else if let Some(payload) = self.payload.downcast_ref::<&'static str>() {
129+
write!(formatter, "'{}', ", payload)?
130+
}
131+
// NOTE: we cannot use downcast_ref::<String>() here
132+
// since String is not available in libcore!
133+
// A String payload and no message is what we’d get from `std::panic!`
134+
// called with multiple arguments.
135+
136+
self.location.fmt(formatter)
137+
}
138+
}
139+
123140
/// A struct containing information about the location of a panic.
124141
///
125142
/// This structure is created by the [`location`] method of [`PanicInfo`].
@@ -226,3 +243,9 @@ impl<'a> Location<'a> {
226243
self.col
227244
}
228245
}
246+
247+
impl<'a> fmt::Display for Location<'a> {
248+
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
249+
write!(formatter, "{}:{}:{}", self.file, self.line, self.col)
250+
}
251+
}

0 commit comments

Comments
 (0)