Re: [PATCH v7 03/16] rust: implement `IdArray`, `IdTable` and `RawDeviceId`

Tamir Duberstein
2025-03-15T16:53:05Z

On Thu, Dec 19, 2024 at 12:08 PM Danilo Krummrich <dakr@kernel.org> wrote:
>
> +/// Marker trait to indicate a Rust device ID type represents a corresponding C device ID type.
> +///
> +/// This is meant to be implemented by buses/subsystems so that they can use [`IdTable`] to
> +/// guarantee (at compile-time) zero-termination of device id tables provided by drivers.
> +///
> +/// # Safety
> +///
> +/// Implementers must ensure that:
> +/// - `Self` is layout-compatible with [`RawDeviceId::RawType`]; i.e. it's safe to transmute to
> +/// `RawDeviceId`.
> +///
> +/// This requirement is needed so `IdArray::new` can convert `Self` to `RawType` when building
> +/// the ID table.
> +///
> +/// Ideally, this should be achieved using a const function that does conversion instead of
> +/// transmute; however, const trait functions relies on `const_trait_impl` unstable feature,
> +/// which is broken/gone in Rust 1.73.
> +///
> +/// - `DRIVER_DATA_OFFSET` is the offset of context/data field of the device ID (usually named
> +/// `driver_data`) of the device ID, the field is suitable sized to write a `usize` value.
> +///
> +/// Similar to the previous requirement, the data should ideally be added during `Self` to
> +/// `RawType` conversion, but there's currently no way to do it when using traits in const.
> +pub unsafe trait RawDeviceId {
> + /// The raw type that holds the device id.
> + ///
> + /// Id tables created from [`Self`] are going to hold this type in its zero-terminated array.
> + type RawType: Copy;
> +
> + /// The offset to the context/data field.
> + const DRIVER_DATA_OFFSET: usize;
> +
> + /// The index stored at `DRIVER_DATA_OFFSET` of the implementor of the [`RawDeviceId`] trait.
> + fn index(&self) -> usize;
> +}

Very late to the game here, but have a question about the use of
OFFSET here. Why is this preferred to a method that returns a pointer
to the field?