From 91da5a24144e5a82bf88c5f72068cf1628198668 Mon Sep 17 00:00:00 2001 From: Jimmy Ostler Date: Thu, 19 Dec 2024 22:25:33 -0800 Subject: [PATCH] rust: alloc: add doctest for `ArrayLayout::new()` 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 Link: https://github.com/Rust-for-Linux/linux/issues/1131 Reviewed-by: Danilo Krummrich Signed-off-by: Jimmy Ostler Link: https://lore.kernel.org/r/f1564da5bcaa6be87aee312767a1d1694a03d1b7.1734674670.git.jtostler1@gmail.com [ Added periods to example comments. Reworded title. - Miguel ] Signed-off-by: Miguel Ojeda --- rust/kernel/alloc/layout.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/rust/kernel/alloc/layout.rs b/rust/kernel/alloc/layout.rs index 4b3cd7fdc816c1..93ed514f7cc7ed 100644 --- a/rust/kernel/alloc/layout.rs +++ b/rust/kernel/alloc/layout.rs @@ -43,6 +43,25 @@ impl ArrayLayout { /// # Errors /// /// When `len * size_of::()` overflows or when `len * size_of::() > isize::MAX`. + /// + /// # Examples + /// + /// ``` + /// # use kernel::alloc::layout::{ArrayLayout, LayoutError}; + /// let layout = ArrayLayout::::new(15)?; + /// assert_eq!(layout.len(), 15); + /// + /// // Errors because `len * size_of::()` overflows. + /// let layout = ArrayLayout::::new(isize::MAX as usize); + /// assert!(layout.is_err()); + /// + /// // Errors because `len * size_of::() > isize::MAX`, + /// // even though `len < isize::MAX`. + /// let layout = ArrayLayout::::new(isize::MAX as usize / 2); + /// assert!(layout.is_err()); + /// + /// # Ok::<(), Error>(()) + /// ``` pub const fn new(len: usize) -> Result { match len.checked_mul(core::mem::size_of::()) { Some(size) if size <= ISIZE_MAX => {