Skip to content

Commit

Permalink
rust: alloc: Add doctest for ArrayLayout
Browse files Browse the repository at this point in the history
Add a rustdoc example and Kunit test to the `ArrayLayout` struct's
`ArrayLayout::new()` function.

Add an implementation of `From<LayoutError> for Error` for the
`kernel::alloc::LayoutError`. This is necessary for the new test to
compile.

Change the `From` implementation on `core::alloc::LayoutError` to avoid
collisions with `kernel::alloc::LayoutError`, and modify imports to
explicitly import `kernel::alloc::LayoutError` instead.

Suggested-by: Boqun Feng <[email protected]>
Link: Rust-for-Linux#1131
Signed-off-by: Jimmy Ostler <[email protected]>
  • Loading branch information
LordGoatius authored and intel-lab-lkp committed Dec 5, 2024
1 parent 1dc707e commit 8bf3592
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
19 changes: 19 additions & 0 deletions rust/kernel/alloc/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,25 @@ impl<T> ArrayLayout<T> {
/// # Errors
///
/// When `len * size_of::<T>()` overflows or when `len * size_of::<T>() > isize::MAX`.
///
/// # Examples
///
/// ```
/// # use kernel::alloc::layout::{ArrayLayout, LayoutError};
/// let layout = ArrayLayout::<i32>::new(15)?;
/// assert_eq!(layout.len(), 15);
///
/// // Errors because `len * size_of::<T>()` overflows
/// let layout = ArrayLayout::<i32>::new(isize::MAX as usize);
/// assert!(layout.is_err());
///
/// // Errors because `len * size_of::<i32>() > isize::MAX`,
/// // even though `len < isize::MAX`
/// let layout = ArrayLayout::<i32>::new(isize::MAX as usize / 2);
/// assert!(layout.is_err());
///
/// # Ok::<(), Error>(())
/// ```
pub const fn new(len: usize) -> Result<Self, LayoutError> {
match len.checked_mul(core::mem::size_of::<T>()) {
Some(size) if size <= ISIZE_MAX => {
Expand Down
13 changes: 10 additions & 3 deletions rust/kernel/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@
//!
//! C header: [`include/uapi/asm-generic/errno-base.h`](srctree/include/uapi/asm-generic/errno-base.h)
use crate::{alloc::AllocError, str::CStr};

use core::alloc::LayoutError;
use crate::{
alloc::{layout::LayoutError, AllocError},
str::CStr,
};

use core::fmt;
use core::num::NonZeroI32;
Expand Down Expand Up @@ -223,6 +224,12 @@ impl From<LayoutError> for Error {
}
}

impl From<core::alloc::LayoutError> for Error {
fn from(_: core::alloc::LayoutError) -> Error {
code::ENOMEM
}
}

impl From<core::fmt::Error> for Error {
fn from(_: core::fmt::Error) -> Error {
code::EINVAL
Expand Down

0 comments on commit 8bf3592

Please sign in to comment.