Re: [PATCH v2] rust: transmute: add `as_bytes` method for `AsBytes` trait

From: Danilo Krummrich
Date: Fri Jul 25 2025 - 11:07:45 EST


On 7/25/25 3:08 PM, Alexandre Courbot wrote:
diff --git a/rust/kernel/transmute.rs b/rust/kernel/transmute.rs
index 1c7d43771a37b90150de86699f114a2ffb84db91..d4036986a3d7fb97e5da3e121e9590ad23b784e9 100644
--- a/rust/kernel/transmute.rs
+++ b/rust/kernel/transmute.rs
@@ -47,7 +47,16 @@ macro_rules! impl_frombytes {
///
/// Values of this type may not contain any uninitialized bytes. This type must not have interior
/// mutability.
-pub unsafe trait AsBytes {}
+pub unsafe trait AsBytes {
+ /// Returns `self` as a slice of bytes.
+ fn as_bytes(&self) -> &[u8] {
+ let data = (self as *const Self).cast::<u8>();

I'd probably use from_ref() instead. With that,

Reviewed-by: Danilo Krummrich <dakr@xxxxxxxxxx>

+ let len = size_of_val(self);
+
+ // SAFETY: `data` is non-null and valid for `len * sizeof::<u8>()` bytes.
+ unsafe { core::slice::from_raw_parts(data, len) }
+ }
+}