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

Alice Ryhl
2024-12-13T13:40:53Z

On Thu, Dec 12, 2024 at 9:31 PM Tamir Duberstein <tamird@gmail.com> 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@igalia.com>
> Inspired-by: Asahi Lina <lina@asahilina.net>
> Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org>
> Signed-off-by: Tamir Duberstein <tamird@gmail.com>

Reviewed-by: Alice Ryhl <aliceryhl@google.com>

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