Skip to content

Commit

Permalink
Avoid some manual slice length calculation
Browse files Browse the repository at this point in the history
No need for us to write the multiplication when `size_of_val` does exactly what we need.
  • Loading branch information
scottmcm committed Apr 7, 2023
1 parent 9f52e3b commit 37423d6
Showing 1 changed file with 4 additions and 12 deletions.
16 changes: 4 additions & 12 deletions core/src/mem/maybe_uninit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1241,13 +1241,9 @@ impl<T> MaybeUninit<T> {
/// ```
#[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
pub fn slice_as_bytes(this: &[MaybeUninit<T>]) -> &[MaybeUninit<u8>] {
let bytes = mem::size_of_val(this);
// SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
unsafe {
slice::from_raw_parts(
this.as_ptr() as *const MaybeUninit<u8>,
this.len() * mem::size_of::<T>(),
)
}
unsafe { slice::from_raw_parts(this.as_ptr() as *const MaybeUninit<u8>, bytes) }
}

/// Returns the contents of this mutable slice of `MaybeUninit` as a mutable slice of
Expand All @@ -1274,13 +1270,9 @@ impl<T> MaybeUninit<T> {
/// ```
#[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
pub fn slice_as_bytes_mut(this: &mut [MaybeUninit<T>]) -> &mut [MaybeUninit<u8>] {
let bytes = mem::size_of_val(this);
// SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
unsafe {
slice::from_raw_parts_mut(
this.as_mut_ptr() as *mut MaybeUninit<u8>,
this.len() * mem::size_of::<T>(),
)
}
unsafe { slice::from_raw_parts_mut(this.as_mut_ptr() as *mut MaybeUninit<u8>, bytes) }
}
}

Expand Down

0 comments on commit 37423d6

Please sign in to comment.