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

From: Alvin Sun

Date: Fri Apr 17 2026 - 08:46:09 EST


Hi Onur,

On 4/17/26 16:28, Onur Özkan wrote:
On Fri, 17 Apr 2026 09:05:54 +0800
Alvin Sun <alvin.sun@xxxxxxxxx> 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@xxxxxxxxx>
---
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`;

Yeah, you're right - we can let the compiler infer the type automatically.
I haven't gotten used to that convenience yet :P


+ // 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.

I'm still not very used to the chained syntax style. For me, the if/else
approach is quite intuitive.

Best regards,
Alvin


-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