[PATCH v2 2/2] rust: debugfs: remove unsafe blocks from traits impl for Vec

From: Josef Ippisch via B4 Relay

Date: Tue Jul 28 2026 - 14:54:44 EST


From: Josef Ippisch <josef.ippisch.dev@xxxxxxxxxxx>

The previous implementation used an `unsafe` block to manually cast Vec's
slice to a &[u8] using `core::slice::from_raw_parts`. Instead, the
implementation can be implemented in safe rust using zerocopy's trait
functions `as_bytes()` and `as_mut_bytes()`, respectively, and making use
of deref coercion to implicitly cast Vec to &[T] as `FromBytes` and
`IntoBytes` automatically are implemented on [T] when they are implemented
on T.

Signed-off-by: Josef Ippisch <josef.ippisch.dev@xxxxxxxxxxx>
---
rust/kernel/debugfs/traits.rs | 21 ++-------------------
1 file changed, 2 insertions(+), 19 deletions(-)

diff --git a/rust/kernel/debugfs/traits.rs b/rust/kernel/debugfs/traits.rs
index b794f7dd7e14..b295f8420abd 100644
--- a/rust/kernel/debugfs/traits.rs
+++ b/rust/kernel/debugfs/traits.rs
@@ -153,14 +153,7 @@ fn write_to_slice(
writer: &mut UserSliceWriter,
offset: &mut file::Offset,
) -> Result<usize> {
- let slice = self.as_slice();
-
- // SAFETY: `T: Immutable + IntoBytes` allows us to treat `&[T]` as `&[u8]`.
- let buffer = unsafe {
- core::slice::from_raw_parts(slice.as_ptr().cast(), core::mem::size_of_val(slice))
- };
-
- writer.write_slice_file(buffer, offset)
+ writer.write_slice_file(self.as_bytes(), offset)
}
}

@@ -261,17 +254,7 @@ fn read_from_slice_mut(
reader: &mut UserSliceReader,
offset: &mut file::Offset,
) -> Result<usize> {
- let slice = self.as_mut_slice();
-
- // SAFETY: `T: FromBytes + IntoBytes` allow us to treat `&mut [T]` as `&mut [u8]`.
- let buffer = unsafe {
- core::slice::from_raw_parts_mut(
- slice.as_mut_ptr().cast(),
- core::mem::size_of_val(slice),
- )
- };
-
- reader.read_slice_file(buffer, offset)
+ reader.read_slice_file(self.as_mut_bytes(), offset)
}
}


--
2.53.0