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.

This patch depends on the first patch in this series in order for the
kunit test to compile.

Suggested-by: Boqun Feng <boqun.feng@gmail.com>
Link: Rust-for-Linux#1131
Signed-off-by: Jimmy Ostler <jtostler1@gmail.com>
  • Loading branch information
LordGoatius authored and intel-lab-lkp committed Dec 18, 2024
1 parent 33d805a commit 2bec087
Showing 1 changed file with 19 additions and 0 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

0 comments on commit 2bec087

Please sign in to comment.