Skip to content

Commit

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

Kunit tests ran using `./tools/testing/kunit/kunit.py run \
--make_options LLVM=1 \
--kconfig_add CONFIG_RUST=y` passed.

Generated documentation looked as expected.

Signed-off-by: Jimmy Ostler <jtostler1@gmail.com>
Suggested-by: Boqun Feng <boqun.feng@gmail.com>
Link: Rust-for-Linux#1131
  • Loading branch information
LordGoatius authored and intel-lab-lkp committed Dec 3, 2024
1 parent 1dc707e commit 8da780d
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions rust/kernel/alloc/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use core::{alloc::Layout, marker::PhantomData};

/// Error when constructing an [`ArrayLayout`].
#[derive(Debug)]
pub struct LayoutError;

/// A layout for an array `[T; n]`.
Expand Down Expand Up @@ -43,6 +44,19 @@ impl<T> ArrayLayout<T> {
/// # Errors
///
/// When `len * size_of::<T>()` overflows or when `len * size_of::<T>() > isize::MAX`.
///
///
/// # Examples
///
/// ```rust
/// use kernel::alloc::layout::ArrayLayout;
///
/// let layout = ArrayLayout::<i32>::new(15);
/// assert_eq!(layout.expect("len * size_of::<i32>() does not overflow").len(), 15);
///
/// let layout = ArrayLayout::<i32>::new(isize::MAX as usize);
/// assert!(layout.is_err());
/// ```
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

0 comments on commit 8da780d

Please sign in to comment.