rust-for-linux.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
From: christian <christiansantoslima21@gmail.com>
To: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org,
	"Miguel Ojeda" <ojeda@kernel.org>,
	"Alex Gaynor" <alex.gaynor@gmail.com>,
	"Boqun Feng" <boqun.feng@gmail.com>,
	"Gary Guo" <gary@garyguo.net>,
	"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
	"Benno Lossin" <benno.lossin@proton.me>,
	"Andreas Hindborg" <a.hindborg@kernel.org>,
	"Alice Ryhl" <aliceryhl@google.com>,
	"Trevor Gross" <tmgross@umich.edu>,
	"Danilo Krummrich" <dakr@kernel.org>,
	~lkcamp/patches@lists.sr.ht, richard120310@gmail.com
Subject: [PATCH v4] Add methods for FromBytes trait.
Date: Fri, 14 Mar 2025 00:49:10 -0300	[thread overview]
Message-ID: <20250314034910.134463-1-christiansantoslima21@gmail.com> (raw)

Methods receive a slice and perform size check to add
a valid way to make conversion safe.
In the invalid case return the EINVAL error.

The conversion between slices ([T])
is separated from others, because I couldn't implement it
in the same way as the other conversions.

Link: https://github.com/Rust-for-Linux/linux/issues/1119
Signed-off-by: christian <christiansantoslima21@gmail.com>
---
 rust/kernel/transmute.rs | 67 ++++++++++++++++++++++++++++++++++++++--
 1 file changed, 64 insertions(+), 3 deletions(-)

diff --git a/rust/kernel/transmute.rs b/rust/kernel/transmute.rs
index 1c7d43771a37..5924c0daccfc 100644
--- a/rust/kernel/transmute.rs
+++ b/rust/kernel/transmute.rs
@@ -2,6 +2,8 @@
 
 //! Traits for transmuting types.
 
+use crate::prelude::{Error, EINVAL};
+
 /// Types for which any bit pattern is valid.
 ///
 /// Not all types are valid for all values. For example, a `bool` must be either zero or one, so
@@ -12,26 +14,85 @@
 /// # Safety
 ///
 /// All bit-patterns must be valid for this type. This type must not have interior mutability.
-pub unsafe trait FromBytes {}
+///
+/// # Example
+///
+/// ```
+/// let foo = &[1, 2, 3, 4];
+///
+/// let result = u8::from_bytes(foo);
+///
+/// assert_eq!(*result, 0x40300201);
+/// ```
+pub trait FromBytes {
+    /// Receives a slice of bytes and converts to a valid reference of Self when it's possible.
+    fn from_bytes(slice_of_bytes: &[u8]) -> Result<&Self, Error>;
+
+    /// Receives a mutable slice of bytes and converts to a valid reference of Self when it's possible.
+    fn from_bytes_mut(mut_slice_of_bytes: &mut [u8]) -> Result<&mut Self, Error>;
+}
 
 macro_rules! impl_frombytes {
     ($($({$($generics:tt)*})? $t:ty, )*) => {
         // SAFETY: Safety comments written in the macro invocation.
-        $(unsafe impl$($($generics)*)? FromBytes for $t {})*
+        $(impl$($($generics)*)? FromBytes for $t {
+            fn from_bytes(slice_of_bytes: &[u8]) -> Result<&$t, Error> {
+                if slice_of_bytes.len() == core::mem::size_of::<$t>() {
+                    let slice_ptr = slice_of_bytes.as_ptr() as *const $t;
+                    unsafe { Ok(&*slice_ptr) }
+                } else {
+                    Err(EINVAL)
+                }
+            }
+
+            fn from_bytes_mut(mut_slice_of_bytes: &mut [u8]) -> Result<&mut $t, Error> {
+                if mut_slice_of_bytes.len() == core::mem::size_of::<$t>() {
+                    let slice_ptr = mut_slice_of_bytes.as_mut_ptr() as *mut $t;
+                    unsafe { Ok(&mut *slice_ptr) }
+                } else {
+                    Err(EINVAL)
+                }
+            }
+        })*
     };
 }
 
 impl_frombytes! {
     // SAFETY: All bit patterns are acceptable values of the types below.
+    // SAFETY: Dereferencing the pointer is safe because slice has the same size of Self.
     u8, u16, u32, u64, usize,
     i8, i16, i32, i64, isize,
 
     // SAFETY: If all bit patterns are acceptable for individual values in an array, then all bit
     // patterns are also acceptable for arrays of that type.
-    {<T: FromBytes>} [T],
+    // SAFETY: Dereferencing the pointer is safe because slice has the same size of Self.
     {<T: FromBytes, const N: usize>} [T; N],
 }
 
+impl<T: FromBytes> FromBytes for [T] {
+    fn from_bytes(slice_of_bytes: &[u8]) -> Result<&Self, Error> {
+        let slice_ptr = slice_of_bytes.as_ptr() as *const T;
+        if slice_of_bytes.len() % core::mem::size_of::<T>() == 0 {
+            let slice_len = slice_of_bytes.len() / core::mem::size_of::<T>();
+            // SAFETY: Creating a slice is safe because the slice can be divided into T sized blocks.
+            unsafe { Ok(core::slice::from_raw_parts(slice_ptr, slice_len)) }
+        } else {
+            Err(EINVAL)
+        }
+    }
+
+    fn from_bytes_mut(mut_slice_of_bytes: &mut [u8]) -> Result<&mut Self, Error> {
+        let slice_ptr = mut_slice_of_bytes.as_mut_ptr() as *mut T;
+        if mut_slice_of_bytes.len() % core::mem::size_of::<T>() == 0 {
+            let slice_len = mut_slice_of_bytes.len() / core::mem::size_of::<T>();
+            // SAFETY: Creating a slice is safe because the slice can be divided into T sized blocks.
+            unsafe { Ok(core::slice::from_raw_parts_mut(slice_ptr, slice_len)) }
+        } else {
+            Err(EINVAL)
+        }
+    }
+}
+
 /// Types that can be viewed as an immutable slice of initialized bytes.
 ///
 /// If a struct implements this trait, then it is okay to copy it byte-for-byte to userspace. This
-- 
2.48.1


             reply	other threads:[~2025-03-14  3:49 UTC|newest]

Thread overview: 4+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2025-03-14  3:49 christian [this message]
2025-03-14 10:45 ` [PATCH v4] Add methods for FromBytes trait Benno Lossin
2025-03-17 23:14   ` Christian
2025-03-18  9:05     ` Benno Lossin

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20250314034910.134463-1-christiansantoslima21@gmail.com \
    --to=christiansantoslima21@gmail.com \
    --cc=a.hindborg@kernel.org \
    --cc=alex.gaynor@gmail.com \
    --cc=aliceryhl@google.com \
    --cc=benno.lossin@proton.me \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun.feng@gmail.com \
    --cc=dakr@kernel.org \
    --cc=gary@garyguo.net \
    --cc=linux-kernel@vger.kernel.org \
    --cc=ojeda@kernel.org \
    --cc=richard120310@gmail.com \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=tmgross@umich.edu \
    --cc=~lkcamp/patches@lists.sr.ht \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).