Skip to contentSkip to conversation

rust: error: implement Display for Error

PATCH Superseded Arnav Sharma 1 participant 1 message May 3 Rust

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 rust: error: implement Display for Error

Implement the fmt::Display trait for the kernel Error type. Unlike the existing Debug implementation which outputs 'EPERM()', Display produces cleaner user-facing output like 'EPERM', which is the idiomatic Rust way to present errors.

This enables using {e} instead of {e:?} in format strings throughout the kernel's Rust code.

---
 rust/kernel/error.rs | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)
rust/kernel/error.rs +25 -0
index 05cf869ac090..87ea3ce2d269 100644
@@ -216,6 +216,31 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     }
 }
 
+impl fmt::Display for Error {
+    /// Displays the error name if available, otherwise the numeric error code.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::prelude::*;
+    /// # use kernel::str::CString;
+    /// let err = EPERM;
+    /// let s = CString::try_from_fmt(fmt!("{err}"))?;
+    /// assert_eq!(s.to_bytes(), "EPERM".as_bytes());
+    /// # Ok::<(), Error>(())
+    /// ```
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match self.name() {
+            // Print out the numeric error code if no name can be found.
+            None => write!(f, "Unknown error {}", -self.0.get()),
+            // SAFETY: These strings are ASCII-only.
+            Some(name) => f.write_str(unsafe {
+                core::str::from_utf8_unchecked(name.to_bytes())
+            }),
+        }
+    }
+}
+
 impl From<AllocError> for Error {
     #[inline]
     fn from(_: AllocError) -> Error {
Signature · 1 line
2.43.0