rust: device: implement impl_device_context_into_aref!
authorDanilo Krummrich <dakr@kernel.org>
Sun, 13 Apr 2025 17:36:57 +0000 (19:36 +0200)
committerDanilo Krummrich <dakr@kernel.org>
Thu, 17 Apr 2025 13:21:27 +0000 (15:21 +0200)
Implement a macro to implement all From conversions of a certain device
to ARef<Device>.

This avoids unnecessary boiler plate code for every device
implementation.

Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Link: https://lore.kernel.org/r/20250413173758.12068-3-dakr@kernel.org
[ Add missing `::` prefix in macros. - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
rust/kernel/device.rs
rust/kernel/pci.rs
rust/kernel/platform.rs

index 9520e05..7b96c99 100644 (file)
@@ -279,6 +279,27 @@ macro_rules! impl_device_context_deref {
     };
 }
 
+#[doc(hidden)]
+#[macro_export]
+macro_rules! __impl_device_context_into_aref {
+    ($src:ty, $device:tt) => {
+        impl ::core::convert::From<&$device<$src>> for $crate::types::ARef<$device> {
+            fn from(dev: &$device<$src>) -> Self {
+                (&**dev).into()
+            }
+        }
+    };
+}
+
+/// Implement [`core::convert::From`], such that all `&Device<Ctx>` can be converted to an
+/// `ARef<Device>`.
+#[macro_export]
+macro_rules! impl_device_context_into_aref {
+    ($device:tt) => {
+        ::kernel::__impl_device_context_into_aref!($crate::device::Core, $device);
+    };
+}
+
 #[doc(hidden)]
 #[macro_export]
 macro_rules! dev_printk {
index 8474608..7c6ec05 100644 (file)
@@ -425,12 +425,7 @@ impl Device<device::Core> {
 // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
 // argument.
 kernel::impl_device_context_deref!(unsafe { Device });
-
-impl From<&Device<device::Core>> for ARef<Device> {
-    fn from(dev: &Device<device::Core>) -> Self {
-        (&**dev).into()
-    }
-}
+kernel::impl_device_context_into_aref!(Device);
 
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl crate::types::AlwaysRefCounted for Device {
index 22590bd..9476b71 100644 (file)
@@ -10,7 +10,7 @@ use crate::{
     of,
     prelude::*,
     str::CStr,
-    types::{ARef, ForeignOwnable, Opaque},
+    types::{ForeignOwnable, Opaque},
     ThisModule,
 };
 
@@ -192,12 +192,7 @@ impl Device {
 // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
 // argument.
 kernel::impl_device_context_deref!(unsafe { Device });
-
-impl From<&Device<device::Core>> for ARef<Device> {
-    fn from(dev: &Device<device::Core>) -> Self {
-        (&**dev).into()
-    }
-}
+kernel::impl_device_context_into_aref!(Device);
 
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl crate::types::AlwaysRefCounted for Device {