Unverified Commit ddd625d4 authored by Benjamin Woodruff's avatar Benjamin Woodruff Committed by GitHub

chore: Use from_raw_parts for ResolvedVc::deref_vec and ResolvedVc::deref_slice (#92749)

In reality, I expect this to compile to the same code, but using `from_raw_parts` is technically more correct here as there are no guarantees about the memory layout of `Vec<T>` or `[T]` for any two different values of `T`, even if both values of `T` have the same size and alignment.
parent df9e7d94
...@@ -4,8 +4,8 @@ use std::{ ...@@ -4,8 +4,8 @@ use std::{
future::IntoFuture, future::IntoFuture,
hash::{Hash, Hasher}, hash::{Hash, Hasher},
marker::PhantomData, marker::PhantomData,
mem::transmute,
ops::Deref, ops::Deref,
slice,
}; };
use anyhow::Result; use anyhow::Result;
...@@ -246,15 +246,16 @@ where ...@@ -246,15 +246,16 @@ where
/// Cheaply converts a Vec of resolved Vcs to a Vec of Vcs. /// Cheaply converts a Vec of resolved Vcs to a Vec of Vcs.
pub fn deref_vec(vec: Vec<ResolvedVc<T>>) -> Vec<Vc<T>> { pub fn deref_vec(vec: Vec<ResolvedVc<T>>) -> Vec<Vc<T>> {
debug_assert!(size_of::<ResolvedVc<T>>() == size_of::<Vc<T>>()); debug_assert!(size_of::<ResolvedVc<T>>() == size_of::<Vc<T>>());
let (ptr, len, capacity) = vec.into_raw_parts();
// Safety: The memory layout of `ResolvedVc<T>` and `Vc<T>` is the same. // Safety: The memory layout of `ResolvedVc<T>` and `Vc<T>` is the same.
unsafe { transmute::<Vec<ResolvedVc<T>>, Vec<Vc<T>>>(vec) } unsafe { Vec::from_raw_parts(ptr as *mut Vc<T>, len, capacity) }
} }
/// Cheaply converts a slice of resolved Vcs to a slice of Vcs. /// Cheaply converts a slice of resolved Vcs to a slice of Vcs.
pub fn deref_slice(slice: &[ResolvedVc<T>]) -> &[Vc<T>] { pub fn deref_slice(s: &[ResolvedVc<T>]) -> &[Vc<T>] {
debug_assert!(size_of::<ResolvedVc<T>>() == size_of::<Vc<T>>()); debug_assert!(size_of::<ResolvedVc<T>>() == size_of::<Vc<T>>());
// Safety: The memory layout of `ResolvedVc<T>` and `Vc<T>` is the same. // Safety: The memory layout of `ResolvedVc<T>` and `Vc<T>` is the same.
unsafe { transmute::<&[ResolvedVc<T>], &[Vc<T>]>(slice) } unsafe { slice::from_raw_parts(s.as_ptr() as *const Vc<T>, s.len()) }
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment