Re: [PATCH 03/10] rust: xarray: add `contains_index` method
From: Tamir Duberstein
Date: Mon Dec 29 2025 - 11:00:51 EST
On Wed, Dec 3, 2025 at 5:27 PM Andreas Hindborg <a.hindborg@xxxxxxxxxx> wrote:
>
> Add a convenience method `contains_index` to check whether an element
> exists at a given index in the XArray. This method provides a more
> ergonomic API compared to calling `get` and checking for `Some`.
It isn't clear when you'd want this API, and neither this nor the
example are particularly motivating.
>
> Signed-off-by: Andreas Hindborg <a.hindborg@xxxxxxxxxx>
> ---
> rust/kernel/xarray.rs | 21 +++++++++++++++++++++
> 1 file changed, 21 insertions(+)
>
> diff --git a/rust/kernel/xarray.rs b/rust/kernel/xarray.rs
> index d9762c6bef19c..ede48b5e1dba3 100644
> --- a/rust/kernel/xarray.rs
> +++ b/rust/kernel/xarray.rs
> @@ -218,6 +218,27 @@ fn load<F, U>(&self, index: usize, f: F) -> Option<U>
> Some(f(ptr))
> }
>
> + /// Checks if the XArray contains an element at the specified index.
> + ///
> + /// # Examples
> + ///
> + /// ```
> + /// # use kernel::{alloc::{flags::GFP_KERNEL, kbox::KBox}, xarray::{AllocKind, XArray}};
> + /// let xa = KBox::pin_init(XArray::new(AllocKind::Alloc), GFP_KERNEL)?;
> + ///
> + /// let mut guard = xa.lock();
> + /// assert_eq!(guard.contains_index(42), false);
> + ///
> + /// guard.store(42, KBox::new(0u32, GFP_KERNEL)?, GFP_KERNEL)?;
> + ///
> + /// assert_eq!(guard.contains_index(42), true);
> + ///
> + /// # Ok::<(), kernel::error::Error>(())
> + /// ```
> + pub fn contains_index(&self, index: usize) -> bool {
> + self.get(index).is_some()
> + }
> +
> /// Provides a reference to the element at the given index.
> pub fn get(&self, index: usize) -> Option<T::Borrowed<'_>> {
> self.load(index, |ptr| {
>
> --
> 2.51.2
>
>