Re: [PATCH v12 2/2] rust: xarray: Add an abstraction for XArray

From: Alice Ryhl
Date: Fri Dec 13 2024 - 08:41:02 EST


On Thu, Dec 12, 2024 at 9:31 PM Tamir Duberstein <tamird@xxxxxxxxx> wrote:
>
> `XArray` is an efficient sparse array of pointers. Add a Rust
> abstraction for this type.
>
> This implementation bounds the element type on `ForeignOwnable` and
> requires explicit locking for all operations. Future work may leverage
> RCU to enable lockless operation.
>
> Inspired-by: Maíra Canal <mcanal@xxxxxxxxxx>
> Inspired-by: Asahi Lina <lina@xxxxxxxxxxxxx>
> Reviewed-by: Andreas Hindborg <a.hindborg@xxxxxxxxxx>
> Signed-off-by: Tamir Duberstein <tamird@xxxxxxxxx>

Reviewed-by: Alice Ryhl <aliceryhl@xxxxxxxxxx>

This code looks okay to me, though I have one comment below:

> + // SAFETY: `self.xa` is always valid by the type invariant.
> + iter::once(unsafe {
> + bindings::xa_find(self.xa.get(), &mut index, MAX, bindings::XA_PRESENT)
> + })
> + .chain(iter::from_fn(move || {
> + // SAFETY: `self.xa` is always valid by the type invariant.
> + Some(unsafe {
> + bindings::xa_find_after(self.xa.get(), &mut index, MAX, bindings::XA_PRESENT)
> + })
> + }))
> + .map_while(|ptr| NonNull::new(ptr.cast()))

> + // SAFETY: `self.xa` is always valid by the type invariant.
> + (unsafe { bindings::xa_trylock(self.xa.get()) } != 0).then(|| Guard {
> + xa: self,
> + _not_send: NotThreadSafe,
> + })

This coding style is pretty far in the functional programming camp
compared to the rest of Rust code in the kernel. I tend to stick with
a more imperative style to be more familiar to C folks.

Alice