|
4 | 4 | //!
|
5 | 5 | //! C header: [`include/uapi/asm-generic/errno-base.h`](../../../include/uapi/asm-generic/errno-base.h)
|
6 | 6 |
|
| 7 | +use crate::str::CStr; |
7 | 8 | use crate::{bindings, c_types};
|
8 | 9 | use alloc::{alloc::AllocError, collections::TryReserveError};
|
9 | 10 | use core::convert::From;
|
10 |
| -use core::{num::TryFromIntError, str::Utf8Error}; |
| 11 | +use core::fmt; |
| 12 | +use core::num::TryFromIntError; |
| 13 | +use core::str::{self, Utf8Error}; |
11 | 14 |
|
12 | 15 | /// Generic integer kernel error.
|
13 | 16 | ///
|
14 | 17 | /// The kernel defines a set of integer generic error codes based on C and
|
15 | 18 | /// POSIX ones. These codes may have a more specific meaning in some contexts.
|
16 |
| -#[derive(Debug)] |
17 | 19 | pub struct Error(c_types::c_int);
|
18 | 20 |
|
19 | 21 | impl Error {
|
@@ -61,6 +63,26 @@ impl Error {
|
61 | 63 | }
|
62 | 64 | }
|
63 | 65 |
|
| 66 | +impl fmt::Debug for Error { |
| 67 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 68 | + // SAFETY: FFI call. |
| 69 | + #[cfg(CONFIG_SYMBOLIC_ERRNAME)] |
| 70 | + let name = unsafe { crate::bindings::errname(-self.0) }; |
| 71 | + #[cfg(not(CONFIG_SYMBOLIC_ERRNAME))] |
| 72 | + let name: *const c_types::c_char = core::ptr::null(); |
| 73 | + if !name.is_null() { |
| 74 | + // SAFETY: 'static string from C, and is not NULL. |
| 75 | + let cstr = unsafe { CStr::from_char_ptr(name) }; |
| 76 | + // SAFETY: These strings are ASCII-only |
| 77 | + let str = unsafe { str::from_utf8_unchecked(&cstr) }; |
| 78 | + f.debug_tuple(str).finish() |
| 79 | + } else { |
| 80 | + // Print out number if no name can be found. |
| 81 | + f.debug_tuple("Error").field(&-self.0).finish() |
| 82 | + } |
| 83 | + } |
| 84 | +} |
| 85 | + |
64 | 86 | impl From<TryFromIntError> for Error {
|
65 | 87 | fn from(_: TryFromIntError) -> Error {
|
66 | 88 | Error::EINVAL
|
|
0 commit comments