Skip to content

Commit fd08f2e

Browse files
committed
The patch adds core::num::NonZeroI16 as Error inner type.
Solves Rust-for-Linux#296 Signed-off-by: angelos <agathangelos.stylianidis@gmail.com>
1 parent 25fa03c commit fd08f2e

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

Diff for: rust/kernel/error.rs

+11-8
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use alloc::{
1212
};
1313
use core::convert::From;
1414
use core::fmt;
15-
use core::num::TryFromIntError;
15+
use core::num::{NonZeroI16, TryFromIntError};
1616
use core::str::{self, Utf8Error};
1717

1818
/// Contains the C-compatible error codes.
@@ -22,7 +22,7 @@ pub mod code {
2222
$(
2323
#[doc = $doc]
2424
)*
25-
pub const $err: super::Error = super::Error(-(crate::bindings::$err as i32));
25+
pub const $err: super::Error = super::Error(unsafe { super::NonZeroI16::new_unchecked(-(crate::bindings::$err as i16)) });
2626
};
2727
}
2828

@@ -317,7 +317,7 @@ pub mod code {
317317
///
318318
/// The value is a valid `errno` (i.e. `>= -MAX_ERRNO && < 0`).
319319
#[derive(Clone, Copy, PartialEq, Eq)]
320-
pub struct Error(core::ffi::c_int);
320+
pub struct Error(NonZeroI16);
321321

322322
impl Error {
323323
/// Creates an [`Error`] from a kernel error code.
@@ -336,7 +336,7 @@ impl Error {
336336

337337
// INVARIANT: The check above ensures the type invariant
338338
// will hold.
339-
Error(errno)
339+
Error(unsafe { NonZeroI16::new_unchecked(errno as i16) })
340340
}
341341

342342
/// Creates an [`Error`] from a kernel error code.
@@ -347,19 +347,19 @@ impl Error {
347347
pub(crate) unsafe fn from_kernel_errno_unchecked(errno: core::ffi::c_int) -> Error {
348348
// INVARIANT: The contract ensures the type invariant
349349
// will hold.
350-
Error(errno)
350+
Error(unsafe { NonZeroI16::new_unchecked(errno as i16) })
351351
}
352352

353353
/// Returns the kernel error code.
354354
pub fn to_kernel_errno(self) -> core::ffi::c_int {
355-
self.0
355+
self.0.get() as i32
356356
}
357357

358358
/// Returns a string representing the error, if one exists.
359359
#[cfg(not(testlib))]
360360
pub fn name(&self) -> Option<&'static CStr> {
361361
// SAFETY: Just an FFI call, there are no extra safety requirements.
362-
let ptr = unsafe { bindings::errname(-self.0) };
362+
let ptr = unsafe { bindings::errname(-(self.0.get() as i32)) };
363363
if ptr.is_null() {
364364
None
365365
} else {
@@ -383,7 +383,10 @@ impl fmt::Debug for Error {
383383
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384384
match self.name() {
385385
// Print out number if no name can be found.
386-
None => f.debug_tuple("Error").field(&-self.0).finish(),
386+
None => f
387+
.debug_tuple("Error")
388+
.field(&-(self.0.get() as i32))
389+
.finish(),
387390
// SAFETY: These strings are ASCII-only.
388391
Some(name) => f
389392
.debug_tuple(unsafe { str::from_utf8_unchecked(name) })

0 commit comments

Comments
 (0)