Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

rust: device: implement Device::as_bound()

Provide an unsafe functions for abstractions to convert a regular
&Device to a &Device<Bound>.

This is useful for registrations that provide certain guarantees for the
scope of their callbacks, such as IRQs or certain class device
registrations (e.g. PWM, miscdevice).

Reviewed-by: Benno Lossin <lossin@kernel.org>
Link: https://lore.kernel.org/r/20250713182737.64448-2-dakr@kernel.org
[ Remove unnecessary cast(). - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>

+19
+19
rust/kernel/device.rs
··· 60 60 // SAFETY: By the safety requirements ptr is valid 61 61 unsafe { Self::as_ref(ptr) }.into() 62 62 } 63 + 64 + /// Convert a [`&Device`](Device) into a [`&Device<Bound>`](Device<Bound>). 65 + /// 66 + /// # Safety 67 + /// 68 + /// The caller is responsible to ensure that the returned [`&Device<Bound>`](Device<Bound>) 69 + /// only lives as long as it can be guaranteed that the [`Device`] is actually bound. 70 + pub unsafe fn as_bound(&self) -> &Device<Bound> { 71 + let ptr = core::ptr::from_ref(self); 72 + 73 + // CAST: By the safety requirements the caller is responsible to guarantee that the 74 + // returned reference only lives as long as the device is actually bound. 75 + let ptr = ptr.cast(); 76 + 77 + // SAFETY: 78 + // - `ptr` comes from `from_ref(self)` above, hence it's guaranteed to be valid. 79 + // - Any valid `Device` pointer is also a valid pointer for `Device<Bound>`. 80 + unsafe { &*ptr } 81 + } 63 82 } 64 83 65 84 impl Device<CoreInternal> {