Skip to content

Commit 971a745

Browse files
felipeaggerojeda
authored andcommitted
rust: optimize error type to use nonzero
Optimize `Result<(), Error>` size by changing `Error` type to `NonZero*` for niche optimization. This reduces the space used by the `Result` type, as the `NonZero*` type enables the compiler to apply more efficient memory layout. For example, the `Result<(), Error>` changes size from 8 to 4 bytes. Link: #1120 Signed-off-by: Filipe Xavier <[email protected]> Reviewed-by: Gary Guo <[email protected]> Reviewed-by: Alice Ryhl <[email protected]> Reviewed-by: Fiona Behrens <[email protected]> Link: https://lore.kernel.org/r/BL0PR02MB4914B9B088865CF237731207E9732@BL0PR02MB4914.namprd02.prod.outlook.com [ Removed unneeded block around `match`, added backticks in panic message and added intra-doc link. - Miguel ] Signed-off-by: Miguel Ojeda <[email protected]>
1 parent 6f56651 commit 971a745

File tree

1 file changed

+29
-9
lines changed

1 file changed

+29
-9
lines changed

rust/kernel/error.rs

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use crate::{alloc::AllocError, str::CStr};
99
use alloc::alloc::LayoutError;
1010

1111
use core::fmt;
12+
use core::num::NonZeroI32;
1213
use core::num::TryFromIntError;
1314
use core::str::Utf8Error;
1415

@@ -20,7 +21,12 @@ pub mod code {
2021
$(
2122
#[doc = $doc]
2223
)*
23-
pub const $err: super::Error = super::Error(-(crate::bindings::$err as i32));
24+
pub const $err: super::Error =
25+
match super::Error::try_from_errno(-(crate::bindings::$err as i32)) {
26+
Some(err) => err,
27+
None => panic!("Invalid errno in `declare_err!`"),
28+
}
29+
;
2430
};
2531
}
2632

@@ -88,7 +94,7 @@ pub mod code {
8894
///
8995
/// The value is a valid `errno` (i.e. `>= -MAX_ERRNO && < 0`).
9096
#[derive(Clone, Copy, PartialEq, Eq)]
91-
pub struct Error(core::ffi::c_int);
97+
pub struct Error(NonZeroI32);
9298

9399
impl Error {
94100
/// Creates an [`Error`] from a kernel error code.
@@ -107,45 +113,59 @@ impl Error {
107113

108114
// INVARIANT: The check above ensures the type invariant
109115
// will hold.
110-
Error(errno)
116+
// SAFETY: `errno` is checked above to be in a valid range.
117+
unsafe { Error::from_errno_unchecked(errno) }
118+
}
119+
120+
/// Creates an [`Error`] from a kernel error code.
121+
///
122+
/// Returns [`None`] if `errno` is out-of-range.
123+
const fn try_from_errno(errno: core::ffi::c_int) -> Option<Error> {
124+
if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
125+
return None;
126+
}
127+
128+
// SAFETY: `errno` is checked above to be in a valid range.
129+
Some(unsafe { Error::from_errno_unchecked(errno) })
111130
}
112131

113132
/// Creates an [`Error`] from a kernel error code.
114133
///
115134
/// # Safety
116135
///
117136
/// `errno` must be within error code range (i.e. `>= -MAX_ERRNO && < 0`).
118-
unsafe fn from_errno_unchecked(errno: core::ffi::c_int) -> Error {
137+
const unsafe fn from_errno_unchecked(errno: core::ffi::c_int) -> Error {
119138
// INVARIANT: The contract ensures the type invariant
120139
// will hold.
121-
Error(errno)
140+
// SAFETY: The caller guarantees `errno` is non-zero.
141+
Error(unsafe { NonZeroI32::new_unchecked(errno) })
122142
}
123143

124144
/// Returns the kernel error code.
125145
pub fn to_errno(self) -> core::ffi::c_int {
126-
self.0
146+
self.0.get()
127147
}
128148

129149
#[cfg(CONFIG_BLOCK)]
130150
pub(crate) fn to_blk_status(self) -> bindings::blk_status_t {
131151
// SAFETY: `self.0` is a valid error due to its invariant.
132-
unsafe { bindings::errno_to_blk_status(self.0) }
152+
unsafe { bindings::errno_to_blk_status(self.0.get()) }
133153
}
134154

135155
/// Returns the error encoded as a pointer.
136156
pub fn to_ptr<T>(self) -> *mut T {
137157
#[cfg_attr(target_pointer_width = "32", allow(clippy::useless_conversion))]
138158
// SAFETY: `self.0` is a valid error due to its invariant.
139159
unsafe {
140-
bindings::ERR_PTR(self.0.into()) as *mut _
160+
bindings::ERR_PTR(self.0.get().into()) as *mut _
141161
}
142162
}
143163

144164
/// Returns a string representing the error, if one exists.
145165
#[cfg(not(testlib))]
146166
pub fn name(&self) -> Option<&'static CStr> {
147167
// SAFETY: Just an FFI call, there are no extra safety requirements.
148-
let ptr = unsafe { bindings::errname(-self.0) };
168+
let ptr = unsafe { bindings::errname(-self.0.get()) };
149169
if ptr.is_null() {
150170
None
151171
} else {

0 commit comments

Comments
 (0)