[<prev] [next>] [<thread-prev] [day] [month] [year] [list]
Message-ID: <CABeNrKVYy=9QKvTwnDPfRhXuJLCFgA9bbvd34V-P8jHLEJSGEg@mail.gmail.com>
Date: Sat, 26 Jul 2025 18:37:08 -0700
From: Kane York <kanepyork@...il.com>
To: christiansantoslima21@...il.com
Cc: a.hindborg@...nel.org, alex.gaynor@...il.com, aliceryhl@...gle.com,
benno.lossin@...ton.me, bjorn3_gh@...tonmail.com, boqun.feng@...il.com,
dakr@...nel.org, gary@...yguo.net, linux-kernel@...r.kernel.org,
ojeda@...nel.org, richard120310@...il.com, rust-for-linux@...r.kernel.org,
tmgross@...ch.edu, ~lkcamp/patches@...ts.sr.ht
Subject: Re: [PATCH v8] rust: transmute: Add methods for FromBytes trait
On Tue, 24 Jun 2025 01:28:02 -0300, Christian S. Lima wrote:
> +/// let result = u32::from_bytes(&foo)?;
> +///
> +/// #[cfg(target_endian = "little")]
> +/// assert_eq!(*result, 0x4030201);
> +///
> +/// #[cfg(target_endian = "big")]
> +/// assert_eq!(*result, 0x1020304);
I might start using this as a great example of conditional compilation.
> +// 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.
> +unsafe impl<T: FromBytes> FromBytes for [T] {
> + fn from_bytes(bytes: &[u8]) -> Option<&Self> {
> + let slice_ptr = bytes.as_ptr().cast::<T>();
> + if bytes.len() % ::core::mem::size_of::<T>() == 0 && slice_ptr.is_aligned() {
> + // SAFETY: Since the code checks the size and alignment, the slice is valid.
> + unsafe { Some(::core::slice::from_raw_parts(slice_ptr, bytes.len())) }
This is incorrect -- the second argument to slice::from_raw_parts is the
element count, not the byte count.
> + } else {
> + None
> + }
> + }
> +
> + fn from_mut_bytes(bytes: &mut [u8]) -> Option<&mut Self>
> + where
> + Self: AsBytes,
> + {
> + let slice_ptr = bytes.as_mut_ptr().cast::<T>();
> + if bytes.len() % ::core::mem::size_of::<T>() == 0 && slice_ptr.is_aligned() {
> + // SAFETY: Since the code checks the size and alignment, the slice is valid.
> + unsafe { Some(::core::slice::from_raw_parts_mut(slice_ptr, bytes.len())) }
Same here.
> + } else {
> + None
> + }
> + }
> }
>
> /// Types that can be viewed as an immutable slice of initialized bytes.
> --
> 2.49.0
Powered by blists - more mailing lists