Skip to content

Instantly share code, notes, and snippets.

@thomcc

thomcc/reuse.rs Secret

Last active June 11, 2020 01:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomcc/67854fada2e65ceef7d5cf4ee93d7a86 to your computer and use it in GitHub Desktop.
Save thomcc/67854fada2e65ceef7d5cf4ee93d7a86 to your computer and use it in GitHub Desktop.
// 🚨 This is UB in current Rust!
fn new_vec_reusing_memory<T, U>(mut old: Vec<U>) -> Vec<T> {
if size_of::<T>() == 0
|| size_of::<U>() == 0
|| align_of::<T>() > align_of::<U>()
|| old.capacity() == 0
{
return vec![];
}
old.clear();
let p = old.as_mut_ptr();
let cap_bytes = old.capacity() * size_of::<U>();
let new_cap = cap_bytes / size_of::<T>();
mem::forget(old);
Vec::from_raw_parts(p as *mut T, 0, new_cap)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment