]> git.lizzy.rs Git - rust.git/commitdiff
Implement Display for PanicInfo and Location
authorSimon Sapin <simon.sapin@exyr.org>
Tue, 23 Jan 2018 16:49:43 +0000 (17:49 +0100)
committerSimon Sapin <simon.sapin@exyr.org>
Tue, 23 Jan 2018 17:04:50 +0000 (18:04 +0100)
Due to being in libcore,
this impl cannot access PanicInfo::payload if it’s a String.

src/libcore/panic.rs

index 2dfd950225c36fd2e8b2a0902a41ad951392c419..cf8ceff6cda0d8fd186634ca086055119a7885e7 100644 (file)
@@ -120,6 +120,23 @@ pub fn location(&self) -> Option<&Location> {
     }
 }
 
+impl<'a> fmt::Display for PanicInfo<'a> {
+    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+        formatter.write_str("panicked at ")?;
+        if let Some(message) = self.message {
+            write!(formatter, "'{}', ", message)?
+        } else if let Some(payload) = self.payload.downcast_ref::<&'static str>() {
+            write!(formatter, "'{}', ", payload)?
+        }
+        // NOTE: we cannot use downcast_ref::<String>() here
+        // since String is not available in libcore!
+        // A String payload and no message is what we’d get from `std::panic!`
+        // called with multiple arguments.
+
+        self.location.fmt(formatter)
+    }
+}
+
 /// A struct containing information about the location of a panic.
 ///
 /// This structure is created by the [`location`] method of [`PanicInfo`].
@@ -226,3 +243,9 @@ pub fn column(&self) -> u32 {
         self.col
     }
 }
+
+impl<'a> fmt::Display for Location<'a> {
+    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+        write!(formatter, "{}:{}:{}", self.file, self.line, self.col)
+    }
+}