Re: [PATCH 4/4] rust: xarray: Add Guard::find() helper

Onur Özkan
2026-04-17T08:28:49Z

On Fri, 17 Apr 2026 09:05:54 +0800
Alvin Sun <alvin.sun@linux.dev> wrote:

> Add a helper to find the first present entry in the XArray.
>
> Returns the index of the first present entry, or None if the array
> is empty.
>
> Signed-off-by: Alvin Sun <alvin.sun@linux.dev>
> ---
> rust/kernel/xarray.rs | 22 ++++++++++++++++++++++
> 1 file changed, 22 insertions(+)
>
> diff --git a/rust/kernel/xarray.rs b/rust/kernel/xarray.rs
> index 235fda0e394ba..e43129d032d9d 100644
> --- a/rust/kernel/xarray.rs
> +++ b/rust/kernel/xarray.rs
> @@ -217,6 +217,28 @@ pub fn remove(&mut self, index: usize) -> Option<T> {
> unsafe { T::try_from_foreign(ptr) }
> }
>
> + /// Finds the first present entry.
> + ///
> + /// Returns the index of the first present entry, or `None` if the array is empty.
> + pub fn find(&mut self) -> Option<usize> {
> + let mut index = 0usize;

Nit: I don't know if this verbosity can ever be useful, it can simply be `= 0`;

> + // SAFETY: `self.xa.xa` is always valid by the type invariant, and we hold the lock.
> + let ptr = unsafe {
> + bindings::xa_find(
> + self.xa.xa.get(),
> + &mut index,
> + usize::MAX,
> + bindings::XA_PRESENT,
> + )
> + };
> +
> + if ptr.is_null() {
> + None
> + } else {
> + Some(index)
> + }

This can be written with the `then_some` chain e.g., !ptr.is_null().then_some(..
.) but I don't know if it ever makes it more readable or simpler. I guess it's
up to preference.

-Onur

> + }
> +
> /// Stores an element at the given index.
> ///
> /// May drop the lock if needed to allocate memory, and then reacquire it afterwards.
>
> --
> 2.43.0
>