rust: error: implement Display for Error
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.
Signed-off-by Arnav Sharma <[email protected]>
--- rust/kernel/error.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+)
rust/kernel/error.rs +25 -0
@@ -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