Re: [PATCH v6 1/2] rust: Add trait to convert a device reference to a bus device reference
From: Danilo Krummrich
Date: Fri Oct 24 2025 - 10:49:03 EST
On 10/23/25 7:28 PM, Markus Probst wrote:
> +// SAFETY: `auxilary::Device` is a transparent wrapper of `struct auxiliary_device`.
> +// The offset is guaranteed to point to a valid device field inside `auxilary::Device`.
s/auxilary/auxiliary/
> +unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx> {
> + const OFFSET: usize = offset_of!(bindings::auxiliary_device, dev);
> +}
<snip>
> +/// Bus devices can implement this trait to allow abstractions to provide the bus device in
> +/// class device callbacks.
In the first line, please briefly mention what the trait represents.
Subsequently, you can mention the use-case below as a more general description.
> +///
> +/// This must not be used by drivers and is intended for bus and class device abstractions only.
> +///
> +/// # Safety
> +///
> +/// `AsBusDevice::OFFSET` must be a offset to a device field in the implemented struct.
"... the offset of the embedded base `struct device` field within a bus device
structure"
> +pub(crate) unsafe trait AsBusDevice<Ctx: DeviceContext>: AsRef<Device<Ctx>> {
> + /// The relative offset to the device field.
> + ///
> + /// Use `offset_of!(bindings, field)` macro to avoid breakage.
> + const OFFSET: usize;
> +
> + /// Convert a reference to [`Device`] into `Self`.
> + ///
> + /// # Safety
> + ///
> + /// `dev` must be contained in `Self`.
> + unsafe fn from_device(dev: &Device<Ctx>) -> &Self
> + where
> + Self: Sized,
> + {
> + let raw = dev.as_raw();
> + // SAFETY: `raw - Self::OFFSET` is guaranteed by the safety requirements
> + // to be a valid pointer to `Self`.
> + unsafe { &*raw.byte_sub(Self::OFFSET).cast::<Self>() }
> + }
> +}