* [PATCH v2] rust: error: implement Display for Error
@ 2026-05-03 16:06 Arnav Sharma
0 siblings, 0 replies; only message in thread
From: Arnav Sharma @ 2026-05-03 16:06 UTC (permalink / raw)
To: ojeda; +Cc: rust-for-linux, linux-kernel, Arnav Sharma
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.
Signed-off-by: Arnav Sharma <arnav4324@gmail.com>
---
rust/kernel/error.rs | 25 +++++++++++++++++++++++++
1 file changed, 25 insertions(+)
diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs
index 05cf869ac090..d1b48a4ebd90 100644
--- a/rust/kernel/error.rs
+++ b/rust/kernel/error.rs
@@ -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.pad(unsafe {
+ core::str::from_utf8_unchecked(name.to_bytes())
+ }),
+ }
+ }
+}
+
impl From<AllocError> for Error {
#[inline]
fn from(_: AllocError) -> Error {
--
2.43.0
^ permalink raw reply related [flat|nested] only message in thread
only message in thread, other threads:[~2026-05-03 16:06 UTC | newest]
Thread overview: (only message) (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-05-03 16:06 [PATCH v2] rust: error: implement Display for Error Arnav Sharma
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox