Re: [PATCH 1/6] rust: add `container_of!` macro

From: Alice Ryhl
Date: Mon Feb 12 2024 - 04:57:05 EST


On Sat, Feb 10, 2024 at 9:05 AM Trevor Gross <tmgross@xxxxxxxxx> wrote:
>
> On Mon, Feb 5, 2024 at 9:50 AM <mattgilbride@xxxxxxxxxx> wrote:
> > +macro_rules! container_of {
> > + ($ptr:expr, $type:ty, $($f:tt)*) => {{
> > + let ptr = $ptr as *const _ as *const u8;
> > + let offset: usize = ::core::mem::offset_of!($type, $($f)*);
>
> `offset_of` will be stable in 1.77 BUT only for a single field [1]. I
> don't know if there are other blockers in the kernel already, but if
> this could be changed to call `offset_of!` recursively then it will
> work with the stable version.
>
> We might want an `offset_of_many!(a, b, c)` macro somewhere if there
> are other places that need this nesting.
>
> [1]: https://github.com/rust-lang/rust/pull/118799

Rust Binder *does* need that in one place. Creating a nested
offset_of! is kind of tricky, because you have to fail to compile when
you're following a pointer with the Deref trait. I haven't figured out
how to do that yet.

> > + ptr.sub(offset) as *const $type
>
> Instead of casting to and from `u8`, you should be able to use `byte_sub`

Casting to and from u8 also has the side-effect of making it not work
when the target type is !Sized. Not allowing this might be desirable.

Alice